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): complete sharing management and automatic invitation admission

DavidShenbc2cab9e6a8d
diff --git a/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx b/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx
index a4e2272591..09bbe0d2fb 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx
@@ -20,6 +20,7 @@ import {
Settings2,
Sparkles,
Wrench,
+ Users,
} from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -72,6 +73,7 @@ const TAB_ICON: Record<VisibleSettingsTab, SettingsNavIcon> = {
'agent-island': AgentIslandNavIcon,
import: FileUp,
'remote-control': MonitorSmartphone,
+ 'shared-tasks': Users,
ghosts: Plug,
'builtin-tools': Wrench,
'computer-use': MonitorCog,
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index b8f25c0c8d..d9235913a3 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -22,6 +22,7 @@ import { VisionBridgeSection } from './VisionBridgeSection';
import { ProvidersSection } from './ProvidersSection';
import { McpServersSection } from './McpServersSection';
import { RemoteControlSection } from './RemoteControlSection';
+import { SharedTaskDialog } from '@/features/device-link/SharedTaskDialog';
import { NotificationSection } from './NotificationSection';
import { WindowBehaviorSection } from './WindowBehaviorSection';
import { ComposerSendShortcutSection } from './ComposerSendShortcutSection';
@@ -579,6 +580,11 @@ export function SettingsView() {
</section>
</div>
)}
+ {activeTab === 'shared-tasks' && (
+ <div role="tabpanel" id="settings-panel-shared-tasks" aria-labelledby="settings-tab-shared-tasks">
+ <SharedTaskDialog open presentation="settings" onOpenChange={() => undefined} />
+ </div>
+ )}
{activeTab === 'ghosts' && (
<div
diff --git a/apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts b/apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts
new file mode 100644
index 0000000000..4e0d789958
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts
@@ -0,0 +1,7 @@
+import type { SettingsSearchModule } from './settingsSearchTypes';
+
+export default {
+ id: 'shared-tasks',
+ order: 3,
+ entries: [{ id: 'sharedTasks', tab: 'shared-tasks', targetId: 'settings-panel-shared-tasks', titleKey: 'sharedTask.title', sectionKey: 'sharedTask.manageSharing', keywordKeys: ['sharedTask.join', 'sharedTask.invitation'] }],
+} satisfies SettingsSearchModule;
diff --git a/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx b/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
index 0abf1cfbdd..b5d1b4a43d 100644
--- a/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
@@ -15,7 +15,6 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tip } from '@/components/ui/tooltip';
-import { JoinSharedTaskDialog } from '@/features/device-link/JoinSharedTaskDialog';
import { useSharedTaskTasks } from '@/features/device-link/useSharedTaskTasks';
import { SharedTaskEndedNotice } from '@/features/device-link/SharedTaskEndedNotice';
@@ -24,7 +23,6 @@ export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void
const navigate = useNavigate();
const location = useLocation();
const [menuOpen, setMenuOpen] = useState(false);
- const [joinOpen, setJoinOpen] = useState(false);
useSharedTaskTasks();
return (
@@ -49,9 +47,6 @@ export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void
</Tip>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="bg-titlebar border-titlebar-border">
- <DropdownMenuItem className="focus:bg-titlebar-button-hover" onSelect={() => setJoinOpen(true)}>
- {t('sharedTask.join')}
- </DropdownMenuItem>
{onExitFullscreen && (
<DropdownMenuItem className="focus:bg-titlebar-button-hover" onSelect={onExitFullscreen}>
{t('contentHeader.exitFullscreen')}
@@ -121,7 +116,7 @@ export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <SharedTaskEndedNotice onJoin={() => setJoinOpen(true)} />
- {joinOpen && <JoinSharedTaskDialog open={joinOpen} onOpenChange={setJoinOpen} />}</>
+ <SharedTaskEndedNotice onReturnToTasks={() => navigate('/')} />
+ </>
);
}
diff --git a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
index 9c8609fa62..0a087550c9 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: { initialInvitation?: string; open: boolean; onOpenChange(open: boolean): void }) {
- return <SharedTaskDialog {...props} />;
+ return <SharedTaskDialog {...props} presentation="join" />;
}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
index 537df1fd23..a4e8eaa8ab 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
@@ -1,5 +1,5 @@
import * as Dialog from '@radix-ui/react-dialog';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
import { ArrowLeft, Check, Clock, FileText, Link2, Users, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -10,7 +10,7 @@ import {
} from '@cindy/device-link';
import { Button } from '@/components/ui/button';
import { FormField } from '@/components/ui/form-field';
-import { Input } from '@/components/ui/input';
+import { Textarea } from '@/components/ui/input';
import { useAuth } from '@/contexts/AuthContext';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import type { Session } from '@/lib/ccAgent.types';
@@ -36,9 +36,11 @@ 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, initialInvitation }: {
- open: boolean; onOpenChange(open: boolean): void; session?: Session; returnFocus?(): void; initialInvitation?: string;
+export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, initialInvitation, presentation = 'dialog' }: {
+ open: boolean; onOpenChange(open: boolean): void; session?: Session; returnFocus?(): void; initialInvitation?: string; presentation?: 'dialog' | 'settings' | 'join';
}) {
+ const embedded = presentation === 'settings';
+ const admissionOnly = presentation === 'join';
const { t } = useTranslation();
const navigate = useNavigate();
const { dataOwnerId, isAuthenticated, user } = useAuth();
@@ -63,12 +65,13 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
const [success, setSuccess] = useState<{ sharedTaskId: string; title: string } | null>(null);
const [confirm, setConfirm] = useState<Confirmation | null>(null);
const [busy, setBusy] = useState(false);
+ const [manualOpen, setManualOpen] = useState(false);
const epoch = useRef(0);
const targetEpoch = useRef(0);
const detailRequest = useRef<{ target: Target; epoch: number; sequence: number } | null>(null);
const pending = useRef(false);
const lists = useRef({ owned: { sequence: 0, loading: false }, joined: { sequence: 0, loading: false } });
- const codeInput = useRef<HTMLInputElement>(null);
+ const codeInput = useRef<HTMLTextAreaElement>(null);
const keep = useRef<HTMLButtonElement>(null);
const panel = useRef<HTMLDivElement>(null);
const confirmationOrigin = useRef<Origin>(null);
@@ -126,14 +129,14 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
useEffect(() => {
epoch.current++; targetEpoch.current++; invalidateLists();
- setTab('join'); setTarget(initialTarget); setState(null); setDetailError(null);
+ setTab(embedded ? 'owned' : 'join'); setManualOpen(false); setTarget(initialTarget); setState(null); setDetailError(null);
setOwned(null); setJoined(null); setListErrors({ owned: false, joined: false });
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, initialInvitation, loadList]);
+ }, [open, dataOwnerId, ownerGeneration, isAuthenticated, initialTarget, initialInvitation, loadList, embedded]);
useEffect(() => {
setState(null); setDetailError(null);
if (open && target && isAuthenticated) void loadDetail(target, target.connect);
@@ -164,6 +167,8 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
};
const switchTab = (next: Tab) => {
if (pending.current) return;
+ if (embedded && next === 'join') { setManualOpen(true); setInvitation(''); setErrors({}); return; }
+ setManualOpen(false);
setTarget(null); setSuccess(null); setTab(next);
if (next !== 'join') void loadList(next);
};
@@ -266,6 +271,14 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
navigate('/cc-agent/' + encodeURIComponent(item.sessionId)); onOpenChange(false);
};
const openTask = (sharedTaskId: string) => void run(current => enterTask(sharedTaskId, current));
+ const openOwnedTask = (item: SharedTaskOwnedItem) => void run(async current => {
+ if (!item.local) {
+ await window.electronAPI.deviceLink.openLink(item.hostDeviceId);
+ if (!current()) return;
+ remoteProjectsStore.pinSessionOrigin(item.hostDeviceId, item.sessionId);
+ }
+ if (current()) { navigate('/cc-agent/' + encodeURIComponent(item.sessionId)); onOpenChange(false); }
+ });
useEffect(() => {
if (!open || !isAuthenticated || !initialInvitation || invitation !== initialInvitation
|| autoAttempted.current === initialInvitation || !isDataOwnerGenerationCurrent(invitationOwner.current)) return;
@@ -338,56 +351,83 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
const listView = (kind: 'owned' | 'joined') => {
const items = kind === 'owned' ? owned : joined;
return <>
- <p className="mb-5 text-13 text-[var(--text-secondary)]">{t(kind === 'owned' ? 'sharedTask.ownedManageIntro' : 'sharedTask.joinedManageIntro')}</p>
+ {!embedded && <p className="mb-5 text-13 text-[var(--text-secondary)]">{t(kind === 'owned' ? 'sharedTask.ownedManageIntro' : 'sharedTask.joinedManageIntro')}</p>}
{listErrors[kind] && <div className="mb-4 flex items-center justify-between gap-3 text-13" role="status"><p>{t(kind === 'owned' ? 'sharedTask.ownedLoadFailed' : 'sharedTask.joinedLoadFailed')}</p><Button variant="secondary" onClick={() => void loadList(kind)}>{t('sharedTask.retryAction')}</Button></div>}
{items === null ? !listErrors[kind] && <p role="status" className="text-13 text-[var(--text-secondary)]">{t('sharedTask.loadingOwned')}</p>
: !items.length ? <>{empty(kind === 'owned' ? 'sharedTask.ownedEmptyTitle' : 'sharedTask.joinedEmptyTitle', kind === 'owned' ? 'sharedTask.ownedEmptyHint' : 'sharedTask.joinedEmptyHint')}
- {kind === 'joined' && <div className="text-center"><Button variant="secondary" onClick={() => switchTab('join')}>{t('sharedTask.joinTab')}</Button></div>}</>
+ {kind === 'joined' && !embedded && <div className="text-center"><Button variant="secondary" onClick={() => switchTab('join')}>{t('sharedTask.joinTab')}</Button></div>}</>
: <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">{items.map((item, index) => <div key={item.sharedTaskId} className={`flex flex-wrap items-center gap-3 p-3 ${index ? 'border-t border-[var(--border-default)]' : ''}`}>
<Users size={18} aria-hidden className="shrink-0" /><div className="min-w-0 flex-1">
- {kind === 'owned' ? <h3 className="break-words text-13 font-medium">{item.title}</h3>
+ {kind === 'owned' ? <Button variant="secondary" tone="quiet" disabled={busy} className="h-auto min-h-9 max-w-full justify-start whitespace-normal break-words px-2 text-left text-13" onClick={() => openOwnedTask(item as SharedTaskOwnedItem)}>{item.title}</Button>
: <Button variant="secondary" tone="quiet" disabled={busy} className="h-auto min-h-9 max-w-full justify-start whitespace-normal break-words px-2 text-left text-13 text-[var(--text-primary)]" onClick={() => openTask(item.sharedTaskId)}>{item.title}</Button>}
<p className="text-12 text-[var(--text-secondary)]">{kind === 'owned' ? deviceName(item as SharedTaskOwnedItem)
: t(isRemoteDeviceMarkedDisconnected(sharedTaskHostPeer(item.sharedTaskId, item.hostDeviceId)) ? 'sharedTask.reconnecting' : 'sharedTask.roleGuest')}</p></div>
<Button variant="secondary" tone={kind === 'joined' ? 'quiet' : 'default'} disabled={busy} data-task-id={item.sharedTaskId} className="px-3 text-12"
onClick={() => kind === 'owned' ? manage(item as SharedTaskOwnedItem) : ask({ kind: 'leave', item })}>{t(kind === 'owned' ? 'sharedTask.manage' : 'sharedTask.leaveShort')}</Button>
</div>)}</div>}
- {kind === 'owned' && !!owned?.length && <div className="mt-6 border-t border-[var(--border-default)] pt-5"><Button variant="secondary" size="lg" disabled={busy} className="w-full text-[var(--error-fg)]" onClick={() => ask({ kind: 'close', all: true, targets: owned.map(item => ({ ...item })) })}>{t('sharedTask.closeAll', { count: owned.length })}</Button>
- <p className="mt-2 text-center text-11 text-[var(--text-secondary)]">{t('sharedTask.recordsKept')}</p></div>}
+ {embedded && !!items?.length && <p className="mt-3 text-13 text-[var(--text-secondary)]">{t(kind === 'owned' ? 'sharedTask.ownedManageIntro' : 'sharedTask.joinedManageIntro')}</p>}
+ {kind === 'owned' && !!owned?.length && <div className="mt-8 flex flex-wrap items-center justify-between gap-4 border-t border-[var(--border-default)] pt-5">
+ {embedded && <div><h3 className="text-14 font-medium">{t('sharedTask.closeAllLabel')}</h3><p className="mt-1 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllDescription')}</p></div>}
+ <Button variant="secondary" size="lg" disabled={busy} className={`${embedded ? '' : 'w-full '}text-[var(--error-fg)]`} onClick={() => ask({ kind: 'close', all: true, targets: owned.map(item => ({ ...item })) })}>{t(embedded ? 'sharedTask.closeAllLabel' : 'sharedTask.closeAll', { count: owned.length })}</Button>
+ {!embedded && <p className="w-full text-center text-11 text-[var(--text-secondary)]">{t('sharedTask.recordsKept')}</p>}</div>}
</>;
};
+ const joinForm = (<form ref={node => { codeInput.current = node?.querySelector('textarea') ?? null; }} onSubmit={event => { event.preventDefault(); join(embedded || admissionOnly); }} className="space-y-3">
+ <FormField label={t('sharedTask.invitation')} required reserveFeedback error={errors.invitation && t(errors.invitation)}>{props => <Textarea {...props} rows={3} maxLength={8192} value={invitation} onChange={value => { setInvitation(value); setErrors(previous => ({ ...previous, invitation: undefined })); }} disabled={busy} surface="ivory" autoComplete="off" spellCheck={false} placeholder={t('sharedTask.invitationPlaceholder')} />}</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>);
+ const tabKeys: Tab[] = embedded ? ['owned', 'joined'] : ['join', 'joined', 'owned'];
const hub = <>
- <div role="tablist" aria-label={t('sharedTask.title')} className="mb-5 flex flex-wrap gap-1 border-b border-[var(--border-default)] pb-4">
- {(['join', 'joined', 'owned'] as const).map((key, index, keys) => <Button key={key} id={`shared-task-tab-${key}`} role="tab" aria-selected={tab === key} aria-controls={`shared-task-panel-${key}`} tabIndex={tab === key ? 0 : -1}
- variant={tab === key ? 'primary' : 'secondary'} tone={tab === key ? 'default' : 'quiet'} size="lg" disabled={busy} className="min-w-0 flex-1 px-2 text-12" onClick={() => switchTab(key)}
- onKeyDown={event => {
- if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
- event.preventDefault(); const next = keys[event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + (event.key === 'ArrowRight' ? 1 : 2)) % 3];
- switchTab(next); document.getElementById(`shared-task-tab-${next}`)?.focus();
- }}>{t(key === 'join' ? 'sharedTask.joinTab' : key === 'joined' ? 'sharedTask.joinedTab' : 'sharedTask.tabOwned')}
- {key !== 'join' && (key === 'owned' ? owned : joined) !== null && <span className="ml-1 text-11 text-[var(--text-secondary)]">{(key === 'owned' ? owned : joined)?.length}</span>}</Button>)}
+ <div role="tablist" aria-label={t('sharedTask.title')} className={`flex flex-wrap border-b border-[var(--border-default)] ${embedded ? 'mb-6 gap-7' : 'mb-5 gap-1 pb-4'}`}>
+ {tabKeys.map((key, index, keys) => {
+ const props = {
+ id: `shared-task-tab-${key}`, role: 'tab', 'aria-selected': tab === key,
+ 'aria-controls': `shared-task-panel-${key}`, tabIndex: tab === key ? 0 : -1,
+ disabled: busy, onClick: () => switchTab(key),
+ onKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => {
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
+ event.preventDefault(); const next = keys[event.key === 'Home' ? 0 : event.key === 'End' ? keys.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : keys.length - 1)) % keys.length];
+ switchTab(next); document.getElementById(`shared-task-tab-${next}`)?.focus();
+ },
+ };
+ const label = <>{t(key === 'join' ? 'sharedTask.joinTab' : key === 'joined' ? 'sharedTask.joinedTab' : 'sharedTask.tabOwned')}
+ {key !== 'join' && (key === 'owned' ? owned : joined) !== null && <span className="ml-2 text-11 text-[var(--text-secondary)]">{(key === 'owned' ? owned : joined)?.length}</span>}</>;
+ return embedded ? <button key={key} {...props} type="button"
+ className={`relative min-h-11 min-w-0 pb-3 text-13 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:opacity-50 ${tab === key ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]'}`}>
+ {label}{tab === key && <span aria-hidden className="absolute -bottom-px inset-x-0 h-0.5 bg-[var(--text-primary)]" />}
+ </button> : <Button key={key} {...props} variant={tab === key ? 'primary' : 'secondary'} tone={tab === key ? 'default' : 'quiet'} size="lg" className="min-w-0 flex-1 px-2 text-13">{label}</Button>;
+ })}
</div>
- <div hidden={tab !== 'join'} role="tabpanel" id="shared-task-panel-join" aria-labelledby="shared-task-tab-join">
+ {!embedded && <div hidden={tab !== 'join'} role="tabpanel" id="shared-task-panel-join" aria-labelledby="shared-task-tab-join">
<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>
- {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>
+ {joinForm}
+ </div>}
<div hidden={tab !== 'joined'} role="tabpanel" id="shared-task-panel-joined" aria-labelledby="shared-task-tab-joined">{tab === 'joined' && listView('joined')}</div>
<div hidden={tab !== 'owned'} role="tabpanel" id="shared-task-panel-owned" aria-labelledby="shared-task-tab-owned">{tab === 'owned' && listView('owned')}</div>
</>;
- return <Dialog.Root open={open} onOpenChange={value => { if (!pending.current) { if (confirm) cancel(); else onOpenChange(value); } }}><Dialog.Portal>
+ const dismiss = () => {
+ if (pending.current) return;
+ if (confirm) cancel();
+ else if (embedded) { setTarget(null); setManualOpen(false); setSuccess(null); }
+ else onOpenChange(false);
+ };
+ return <>{embedded && <section>
+ <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
+ <div><h2 className="text-20 font-medium">{t('sharedTask.title')}</h2><p className="mt-2 text-13 text-[var(--text-secondary)]">{t('sharedTask.managementIntro')}</p></div>
+ <Button variant="secondary" size="lg" disabled={!isAuthenticated || busy} onClick={() => switchTab('join')}>{t('sharedTask.join')}</Button>
+ </div>
+ {isAuthenticated ? hub : <p className="text-13">{t('sharedTask.login')}</p>}
+ </section>}<Dialog.Root open={open && (!embedded || !!target || !!confirm || manualOpen || !!success)} onOpenChange={value => { if (!value) dismiss(); }}><Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
<Dialog.Content ref={panel} aria-describedby={undefined} className="fixed left-1/2 top-1/2 z-[10001] max-h-[calc(100dvh-32px)] w-[min(460px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5 text-[var(--text-primary)]"
- onOpenAutoFocus={event => { if (!initialTarget) { event.preventDefault(); codeInput.current?.focus(); } }}
+ onOpenAutoFocus={event => { if (!target && !confirm) { event.preventDefault(); codeInput.current?.focus(); } }}
onCloseAutoFocus={returnFocus ? event => { event.preventDefault(); returnFocus(); } : undefined}
onEscapeKeyDown={event => { if (pending.current || confirm || target) { event.preventDefault(); if (confirm) cancel(); else if (target) back(); } }}
onInteractOutside={event => event.preventDefault()}>
<div className="mb-5 flex items-center justify-between gap-3"><div className="flex min-w-0 items-center gap-2">
{target && !confirm && <Button variant="secondary" tone="quiet" size="lg" className="w-9 shrink-0 p-0" aria-label={t('sharedTask.back')} disabled={busy} onClick={back}><ArrowLeft size={18} aria-hidden /></Button>}
- <Dialog.Title className="text-18 font-medium">{confirm ? confirmTitle : t(target ? 'sharedTask.manageSharing' : success ? 'sharedTask.joined' : 'sharedTask.title')}</Dialog.Title></div>
- <Button variant="secondary" tone="quiet" size="lg" className="w-9 shrink-0 p-0" disabled={busy} aria-label={t(confirm ? 'sharedTask.cancelOperation' : 'sharedTask.dismiss')} onClick={() => confirm ? cancel() : onOpenChange(false)}><X size={18} aria-hidden /></Button>
+ <Dialog.Title className="text-18 font-medium">{confirm ? confirmTitle : t(target ? 'sharedTask.manageSharing' : success ? 'sharedTask.joined' : embedded || admissionOnly ? 'sharedTask.join' : 'sharedTask.title')}</Dialog.Title></div>
+ <Button variant="secondary" tone="quiet" size="lg" className="w-9 shrink-0 p-0" disabled={busy} aria-label={t(confirm ? 'sharedTask.cancelOperation' : 'sharedTask.dismiss')} onClick={dismiss}><X size={18} aria-hidden /></Button>
</div>
{confirm && <div><p className="text-13 leading-relaxed text-[var(--text-secondary)]">{t(confirmBody)}</p>
<div className="my-5 overflow-hidden rounded-xl border border-[var(--border-default)]">{confirm.kind === 'close' ? confirm.targets.map((item, index) => <div key={item.sharedTaskId} className={`p-3 ${index ? 'border-t border-[var(--border-default)]' : ''}`}><p className="break-words text-13 font-medium">{item.title}</p><p className="text-12 text-[var(--text-secondary)]">{deviceName(item)}</p></div>)
@@ -399,8 +439,8 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
<div hidden={!!confirm}>{!isAuthenticated ? <p className="text-13">{t('sharedTask.login')}</p> : target ? hostView : success ? <div className="py-6 text-center">
<span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]"><Check size={18} aria-hidden /></span>
<h3 className="break-words text-14 font-medium">{success.title ? t('sharedTask.joinedTitle', { title: success.title }) : t('sharedTask.joined')}</h3><p className="mb-5 mt-2 text-12 text-[var(--text-secondary)]">{t('sharedTask.joinedBody')}</p>
- <Button variant="cta" size="lg" loading={busy} onClick={() => openTask(success.sharedTaskId)}>{t('sharedTask.enterTask')}</Button><div className="mt-3"><Button variant="secondary" tone="quiet" disabled={busy} onClick={() => switchTab('joined')}>{t('sharedTask.viewJoined')}</Button></div>
- </div> : hub}</div>
+ <Button variant="cta" size="lg" loading={busy} onClick={() => openTask(success.sharedTaskId)}>{t('sharedTask.enterTask')}</Button>{!admissionOnly && <div className="mt-3"><Button variant="secondary" tone="quiet" disabled={busy} onClick={() => switchTab('joined')}>{t('sharedTask.viewJoined')}</Button></div>}
+ </div> : embedded || admissionOnly ? <><p className="mb-5 text-13 text-[var(--text-secondary)]">{t('sharedTask.joinIntro')}</p>{joinForm}</> : hub}</div>
</Dialog.Content>
- </Dialog.Portal></Dialog.Root>;
+ </Dialog.Portal></Dialog.Root></>;
}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx
index e017d2134a..a8b8b53713 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx
@@ -17,7 +17,7 @@ export function notifySharedTaskEnded(peer: string | undefined): boolean {
}
/** Lives in the window menu so leaving the revoked task cannot unmount the ending screen. */
-export function SharedTaskEndedNotice({ onJoin }: { onJoin(): void }) {
+export function SharedTaskEndedNotice({ onReturnToTasks }: { onReturnToTasks(): void }) {
const { t } = useTranslation();
const { dataOwnerId } = useAuth();
const [owner, setOwner] = useState<DataOwnerGeneration | null>(null);
@@ -42,7 +42,7 @@ export function SharedTaskEndedNotice({ onJoin }: { onJoin(): void }) {
<span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]"><CircleStop size={18} aria-hidden /></span>
<h3 className="text-14 font-medium">{t('sharedTask.ended')}</h3>
<Dialog.Description className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.accessEndedBody')}</Dialog.Description>
- <Button variant="cta" size="lg" onClick={() => { setOwner(null); onJoin(); }}>{t('sharedTask.rejoin')}</Button>
+ <Button variant="cta" size="lg" onClick={() => { setOwner(null); onReturnToTasks(); }}>{t('sharedTask.returnToTasks')}</Button>
</div>
</Dialog.Content>
</Dialog.Portal>
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx b/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx
index c69e73c590..e4c447eef7 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx
@@ -2,7 +2,6 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown, ChevronRight, Crown, FileText, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { isSharedTaskPeer, type SharedTaskOwnedItem } from '@cindy/device-link';
-import { Button } from '@/components/ui/button';
import { SessionCard } from '@/features/cc-agent/sidebar/SessionCard';
import { SessionItem } from '@/features/cc-agent/sidebar/SessionItem';
import { sessionActivityMs } from '@/features/cc-agent/lib/dateSessionGrouping';
@@ -161,7 +160,7 @@ export function SharedTasksSection({ activeSessionId, localSessions = [], runnin
{collapsed ? <ChevronRight size={14} aria-hidden /> : <ChevronDown size={14} aria-hidden />}
{t('sharedTask.title')}
</button>
- <Button variant="secondary" className="w-8 shrink-0 border-transparent bg-transparent p-0" aria-label={t('sharedTask.join')} title={t('sharedTask.join')} onClick={() => setJoinOpen(true)}><Plus size={16} aria-hidden /></Button>
+ <button type="button" className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--sidebar-list-muted)] transition-colors hover:bg-sidebar-item-hover hover:text-[var(--sidebar-nav-text)]" aria-label={t('sharedTask.join')} title={t('sharedTask.join')} onClick={() => setJoinOpen(true)}><Plus size={15} aria-hidden /></button>
</div>
{!collapsed && rows.map(row => {
if (row.role === 'joined') {
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 15ef879766..d0263b3bdd 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
@@ -4,6 +4,7 @@ import { MemoryRouter } from 'react-router-dom';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { sharedTaskHostPeer } from '@cindy/device-link';
import { JoinSharedTaskDialog } from '../JoinSharedTaskDialog';
+import { SharedTaskDialog } from '../SharedTaskDialog';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
@@ -43,7 +44,7 @@ beforeEach(() => {
});
afterEach(() => { cleanup(); vi.useRealTimers(); });
function open(onOpenChange = vi.fn()) {
- render(<MemoryRouter><JoinSharedTaskDialog open onOpenChange={onOpenChange} /></MemoryRouter>);
+ render(<MemoryRouter><SharedTaskDialog open onOpenChange={onOpenChange} /></MemoryRouter>);
return onOpenChange;
}
function tab(kind: 'join' | 'joined' | 'owned') {
@@ -55,12 +56,72 @@ function fill(submit = true) {
fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
if (submit) click('join');
}
+it('embeds two management tabs in settings and keeps manual join available on an empty list', async () => {
+ ownedItems = []; joinedItems = [];
+ render(<MemoryRouter><SharedTaskDialog open presentation="settings" onOpenChange={vi.fn()} /></MemoryRouter>);
+ await screen.findByText('sharedTask.ownedEmptyTitle');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getAllByRole('tab')).toHaveLength(2);
+ click('join');
+ const dialog = screen.getByRole('dialog');
+ expect(dialog.querySelectorAll('textarea')).toHaveLength(1);
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
+ click('dismiss');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getByRole('tab', { name: /sharedTask.tabOwned/ }).getAttribute('aria-selected')).toBe('true');
+ expect(state.account).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'join' }));
+});
+it('enters a manually joined task directly from settings', async () => {
+ const close = vi.fn();
+ render(<MemoryRouter><SharedTaskDialog open presentation="settings" onOpenChange={close} /></MemoryRouter>);
+ await act(async () => {}); click('join');
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
+ fireEvent.submit(screen.getByLabelText('sharedTask.invitation').closest('form')!);
+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));
+ expect(state.account).toHaveBeenCalledWith({ action: 'join', invitation: 'A'.repeat(43), displayName: 'Account Guest' });
+ expect(state.openLink).toHaveBeenCalledWith(sharedTaskHostPeer(joinedTask.sharedTaskId, joinedTask.hostDeviceId));
+});
+
+it('keeps settings tabs keyboard accessible when switching between owned and joined tasks', async () => {
+ render(<MemoryRouter><SharedTaskDialog open presentation="settings" onOpenChange={vi.fn()} /></MemoryRouter>);
+ await screen.findByRole('button', { name: owned[0].title });
+ const ownerTab = screen.getByRole('tab', { name: /sharedTask.tabOwned/ });
+ const joinedTab = screen.getByRole('tab', { name: /sharedTask.joinedTab/ });
+ fireEvent.keyDown(ownerTab, { key: 'ArrowRight' });
+ await screen.findByRole('button', { name: joinedTask.title });
+ expect(joinedTab.getAttribute('aria-selected')).toBe('true');
+ expect(document.activeElement).toBe(joinedTab);
+ fireEvent.keyDown(joinedTab, { key: 'ArrowRight' });
+ await screen.findByRole('button', { name: owned[0].title });
+ expect(ownerTab.getAttribute('aria-selected')).toBe('true');
+ expect(document.activeElement).toBe(ownerTab);
+ fireEvent.keyDown(ownerTab, { key: 'End' });
+ expect(document.activeElement).toBe(joinedTab);
+ fireEvent.keyDown(joinedTab, { key: 'Home' });
+ expect(document.activeElement).toBe(ownerTab);
+ await act(async () => {});
+});
async function closeAll() { tab('owned'); await screen.findByRole('button', { name: 'sharedTask.closeAll' }); click('closeAll'); }
+it.each(['A'.repeat(43), 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43)])('enters directly through the compact sidebar admission for %s', async invitation => {
+ const close = vi.fn();
+ render(<MemoryRouter><JoinSharedTaskDialog open onOpenChange={close} /></MemoryRouter>);
+ await act(async () => {});
+ expect(screen.queryByRole('tab')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'sharedTask.cancelOperation' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'sharedTask.dismiss' })).toBeTruthy();
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: invitation } });
+ click('join');
+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));
+ expect(state.account).toHaveBeenCalledWith({ action: 'join', invitation, displayName: 'Account Guest' });
+ expect(state.openLink).toHaveBeenCalledWith(sharedTaskHostPeer(joinedTask.sharedTaskId, joinedTask.hostDeviceId));
+ expect(state.setSessions).toHaveBeenCalled();
+});
+
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.invitation').tagName).toBe('TEXTAREA');
expect(screen.queryByLabelText('sharedTask.joinNickname')).toBeNull();
expect(screen.queryByRole('button', { name: 'sharedTask.closeAll' })).toBeNull();
expect(document.activeElement).toBe(screen.getByLabelText('sharedTask.invitation'));
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx
index 570725e7b7..d33f5a39ea 100644
--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx
@@ -10,24 +10,24 @@ vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'owner
beforeEach(() => setDataOwnerGeneration('owner'));
afterEach(cleanup);
-it('keeps ordinary remote exits unchanged and offers a new invitation after a shared-task exit', () => {
- const onJoin = vi.fn();
- render(<SharedTaskEndedNotice onJoin={onJoin} />);
+it('keeps ordinary remote exits unchanged and returns to tasks after a shared-task exit', () => {
+ const onReturnToTasks = vi.fn();
+ render(<SharedTaskEndedNotice onReturnToTasks={onReturnToTasks} />);
act(() => { expect(notifySharedTaskEnded('ordinary-device')).toBe(false); });
expect(screen.queryByRole('dialog')).toBeNull();
act(() => { expect(notifySharedTaskEnded(sharedTaskHostPeer('share-1', 'desktop'))).toBe(true); });
expect(screen.getByRole('dialog').textContent).toContain('sharedTask.accessEndedBody');
- fireEvent.click(screen.getByRole('button', { name: 'sharedTask.rejoin' }));
- expect(onJoin).toHaveBeenCalledOnce();
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.returnToTasks' }));
+ expect(onReturnToTasks).toHaveBeenCalledOnce();
expect(screen.queryByRole('dialog')).toBeNull();
});
it('does not keep an ending notice visible across an account boundary', () => {
- const onJoin = vi.fn();
- const view = render(<SharedTaskEndedNotice onJoin={onJoin} />);
+ const onReturnToTasks = vi.fn();
+ const view = render(<SharedTaskEndedNotice onReturnToTasks={onReturnToTasks} />);
act(() => { notifySharedTaskEnded(sharedTaskHostPeer('share-1', 'desktop')); });
expect(screen.getByRole('dialog')).toBeTruthy();
setDataOwnerGeneration('other');
- view.rerender(<SharedTaskEndedNotice onJoin={onJoin} />);
+ view.rerender(<SharedTaskEndedNotice onReturnToTasks={onReturnToTasks} />);
expect(screen.queryByRole('dialog')).toBeNull();
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 27ca9b3dbb..e026fa80b1 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -55,16 +55,16 @@
"manageMembers": "Manage Members…",
"cancelSharing": "Stop Sharing",
"cancelTitle": "Stop sharing?",
- "leaveShort": "Leave Sharing",
+ "leaveShort": "Leave",
"joinTab": "Join Shared Task",
- "joinedEmptyTitle": "No Shared Tasks Joined",
- "joinedEmptyHint": "Enter the host’s invitation link in “Join Shared Task”.",
+ "joinedEmptyTitle": "No shared tasks joined",
+ "joinedEmptyHint": "Open an invitation link from a teammate to join a shared task.",
"joinedLoadFailed": "Could not load your joined shared tasks. Try again.",
- "joinedTab": "Joined",
+ "joinedTab": "Joined by Me",
"reconnecting": "Reconnecting…",
"ownedLoadFailed": "Unable to load",
"loadingOwned": "Loading…",
- "retryAction": "Retry",
+ "retryAction": "Reload",
"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.",
@@ -87,7 +87,7 @@
"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 Link",
+ "invitation": "Invitation link or code",
"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.",
@@ -135,15 +135,21 @@
"closedToast": "Stopped sharing {{count}} tasks",
"closeFailedToast": "Could not stop sharing {{count}} tasks. Try again later.",
"back": "Back",
- "cancelOperation": "Cancel action",
+ "cancelOperation": "Cancel",
"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.",
+ "ownedManageIntro": "Includes tasks shared from your other computers.",
+ "joinedManageIntro": "Leaving removes your access. The host and other members are not affected.",
"recordsKept": "Task history and Agent work are kept.",
"othersUnaffected": "Other members and Agent work are not affected.",
"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."
+ "invitationDifferentServer": "This invitation belongs to another Cindy service. Open the link in the matching app.",
+ "managementIntro": "Manage the tasks you share and join.",
+ "returnToTasks": "Back to Tasks",
+ "invitationDetected": "Shared task invitation found",
+ "notNow": "Not Now",
+ "closeAllLabel": "Stop All Sharing",
+ "closeAllDescription": "Guests will lose access. Task history is kept."
},
"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 b842d4296f..90ae7e5a46 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -55,16 +55,16 @@
"manageMembers": "メンバーを管理…",
"cancelSharing": "共有を停止",
"cancelTitle": "共有を停止しますか?",
- "leaveShort": "共有から退出",
+ "leaveShort": "退出",
"joinTab": "共有に参加",
- "joinedEmptyTitle": "参加中の共有タスクはありません",
- "joinedEmptyHint": "「共有に参加」でホストの招待リンクを入力してください。",
+ "joinedEmptyTitle": "参加している共有タスクはありません",
+ "joinedEmptyHint": "仲間からの招待リンクを開いて共有タスクに参加できます。",
"joinedLoadFailed": "参加中の共有タスクを取得できませんでした。再試行してください。",
- "joinedTab": "参加",
+ "joinedTab": "参加した共有",
"reconnecting": "再接続中…",
"ownedLoadFailed": "取得できません",
"loadingOwned": "取得中…",
- "retryAction": "再試行",
+ "retryAction": "再読み込み",
"invitationCopyFailed": "招待リンクをコピーできませんでした。もう一度お試しください。",
"accessEndedBody": "この共有セッションにはアクセスできません。再参加するには、ホストから新しい招待リンクを受け取ってください。",
"joinIntro": "ホストからの招待リンクを貼り付けると、アカウント名でタスクに参加します。",
@@ -87,7 +87,7 @@
"waitingHost": "ホストの対応を待っています。引き続きメッセージを送信できます。",
"join": "共有セッションに参加",
"login": "セッションに参加するには Cindy にログインしてください。",
- "invitation": "招待リンク",
+ "invitation": "招待リンクまたは招待コード",
"dismiss": "ダイアログを閉じる",
"title": "セッションを共有",
"hostLimit": "共有タスクの開始数が現在の上限に達しました。上限を下回るまで共有タスクを終了してから再試行してください。",
@@ -135,15 +135,21 @@
"closedToast": "{{count}} 件の共有を停止しました",
"closeFailedToast": "{{count}} 件の共有を停止できませんでした。後でもう一度お試しください。",
"back": "戻る",
- "cancelOperation": "操作をキャンセル",
+ "cancelOperation": "キャンセル",
"invalidInvitation": "有効な招待リンクまたは招待コードを貼り付けてください。",
- "ownedManageIntro": "他のパソコンを含め、自分が共有しているセッションを管理できます。",
- "joinedManageIntro": "セッションを開いて作業を続けるか、参加しなくなった共有セッションから退出できます。",
+ "ownedManageIntro": "このアカウントの別のパソコンで開始した共有も含みます。",
+ "joinedManageIntro": "退出するとこの共有にアクセスできなくなります。ホストや他のメンバーには影響しません。",
"recordsKept": "セッションの履歴と Agent の作業は保持されます。",
"othersUnaffected": "他のメンバーや Agent の作業には影響しません。",
"viewJoined": "参加中のセッションを表示",
"invalid": "有効な招待リンクまたは招待コードを貼り付けてください。",
- "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。"
+ "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。",
+ "managementIntro": "開始した共有と参加した共有を管理します。",
+ "returnToTasks": "タスク一覧に戻る",
+ "invitationDetected": "共有タスクへの招待が見つかりました",
+ "notNow": "今は参加しない",
+ "closeAllLabel": "すべての共有を停止",
+ "closeAllDescription": "すべてのゲストがアクセスできなくなります。タスクの履歴は保持されます。"
},
"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 ab353dcbdd..372c197ca1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -55,16 +55,16 @@
"manageMembers": "멤버 관리…",
"cancelSharing": "공유 중지",
"cancelTitle": "공유를 중지할까요?",
- "leaveShort": "공유 나가기",
+ "leaveShort": "나가기",
"joinTab": "공유 참여",
- "joinedEmptyTitle": "참여 중인 공유 작업이 없습니다",
- "joinedEmptyHint": "“공유 참여”에서 호스트의 초대 링크를 입력하세요.",
+ "joinedEmptyTitle": "참여한 공유 작업이 없습니다",
+ "joinedEmptyHint": "동료가 보낸 초대 링크를 열어 공유 작업에 참여하세요.",
"joinedLoadFailed": "참여 중인 공유 작업을 불러오지 못했습니다. 다시 시도하세요.",
- "joinedTab": "참여",
+ "joinedTab": "참여한 공유",
"reconnecting": "다시 연결 중…",
"ownedLoadFailed": "불러올 수 없음",
"loadingOwned": "불러오는 중…",
- "retryAction": "다시 시도",
+ "retryAction": "새로 고침",
"invitationCopyFailed": "초대 링크를 복사하지 못했습니다. 다시 시도하세요.",
"accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대 링크를 요청하세요.",
"joinIntro": "호스트의 초대 링크를 붙여넣으면 계정 이름으로 작업에 참여합니다.",
@@ -87,7 +87,7 @@
"waitingHost": "호스트의 응답을 기다리고 있습니다. 메시지는 계속 보낼 수 있습니다.",
"join": "공유 세션 참여",
"login": "세션에 참가하려면 Cindy에 로그인하세요.",
- "invitation": "초대 링크",
+ "invitation": "초대 링크 또는 초대 코드",
"dismiss": "대화 상자 닫기",
"title": "세션 공유",
"hostLimit": "공유 중인 작업 수가 현재 한도에 도달했습니다. 한도 미만이 될 때까지 공유 작업을 종료한 후 다시 시도하세요.",
@@ -135,15 +135,21 @@
"closedToast": "작업 {{count}}개의 공유를 중지했습니다",
"closeFailedToast": "작업 {{count}}개의 공유를 중지하지 못했습니다. 나중에 다시 시도하세요.",
"back": "뒤로",
- "cancelOperation": "작업 취소",
+ "cancelOperation": "취소",
"invalidInvitation": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
- "ownedManageIntro": "다른 컴퓨터의 작업을 포함하여 내가 공유한 작업을 관리합니다.",
- "joinedManageIntro": "작업을 열어 계속 진행하거나 더 이상 참여하지 않는 공유 작업에서 나갈 수 있습니다.",
+ "ownedManageIntro": "이 계정의 다른 컴퓨터에서 시작한 공유도 포함합니다.",
+ "joinedManageIntro": "나가면 이 공유에 접근할 수 없습니다. 호스트와 다른 멤버에게는 영향이 없습니다.",
"recordsKept": "작업 기록과 Agent 작업은 유지됩니다.",
"othersUnaffected": "다른 멤버와 Agent 작업에는 영향을 주지 않습니다.",
"viewJoined": "참여한 작업 보기",
"invalid": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
- "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요."
+ "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요.",
+ "managementIntro": "시작하거나 참여한 공유를 관리합니다.",
+ "returnToTasks": "작업 목록으로 돌아가기",
+ "invitationDetected": "공유 작업 초대를 찾았습니다",
+ "notNow": "나중에",
+ "closeAllLabel": "모든 공유 중지",
+ "closeAllDescription": "모든 게스트의 접근이 차단됩니다. 작업 기록은 유지됩니다."
},
"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 282bdc6b4e..35849d3d6e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -55,16 +55,16 @@
"manageMembers": "管理成员…",
"cancelSharing": "取消共享",
"cancelTitle": "取消共享?",
- "leaveShort": "退出共享",
+ "leaveShort": "退出",
"joinTab": "加入共享",
- "joinedEmptyTitle": "还没有加入共享任务",
- "joinedEmptyHint": "在「加入共享」中填入房主提供的邀请链接。",
+ "joinedEmptyTitle": "还没有加入共享",
+ "joinedEmptyHint": "打开伙伴发来的邀请链接,即可加入共享任务。",
"joinedLoadFailed": "暂时无法获取已加入的共享任务,请重试",
"joinedTab": "我加入的",
"reconnecting": "正在重新连接…",
"ownedLoadFailed": "暂时无法获取",
"loadingOwned": "正在获取…",
- "retryAction": "重试",
+ "retryAction": "重新加载",
"invitationCopyFailed": "未能复制邀请链接,请重试",
"accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新的邀请链接。",
"joinIntro": "粘贴房主发来的邀请链接,使用你的账号昵称加入任务。",
@@ -87,7 +87,7 @@
"waitingHost": "等待房主处理,你可以继续发送消息。",
"join": "加入共享任务",
"login": "请登录 Cindy 后加入任务",
- "invitation": "邀请链接",
+ "invitation": "邀请链接或邀请码",
"dismiss": "关闭窗口",
"title": "共享任务",
"hostLimit": "开启的共享任务已达当前上限,请关闭共享任务,直到数量低于上限后再试。",
@@ -135,15 +135,21 @@
"closedToast": "已取消 {{count}} 个任务的共享",
"closeFailedToast": "部分共享未能取消({{count}} 项),可稍后重试。",
"back": "返回",
- "cancelOperation": "取消操作",
+ "cancelOperation": "取消",
"invalidInvitation": "请粘贴有效的邀请链接或邀请码",
- "ownedManageIntro": "管理你发起的共享,包括其他电脑上的任务。",
- "joinedManageIntro": "打开任务继续工作,或退出不再参与的共享。",
+ "ownedManageIntro": "包含这个账号在其他电脑上发起的共享。",
+ "joinedManageIntro": "退出后将无法继续访问该共享;房主和其他成员不受影响。",
"recordsKept": "任务记录和 Agent 工作保留。",
"othersUnaffected": "其他成员与 Agent 的工作不受影响。",
"viewJoined": "查看我加入的",
"invalid": "请粘贴有效的邀请链接或邀请码",
- "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接"
+ "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接",
+ "managementIntro": "管理你发起和加入的共享。",
+ "returnToTasks": "返回任务列表",
+ "invitationDetected": "发现共享任务邀请",
+ "notNow": "暂不加入",
+ "closeAllLabel": "取消全部共享",
+ "closeAllDescription": "所有访客将无法继续访问,任务记录保留。"
},
"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 d1c40b700b..bc5b5e63c7 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -55,16 +55,16 @@
"manageMembers": "管理成員…",
"cancelSharing": "取消共享",
"cancelTitle": "取消共享?",
- "leaveShort": "退出共享",
+ "leaveShort": "退出",
"joinTab": "加入共享",
- "joinedEmptyTitle": "尚未加入共享任務",
- "joinedEmptyHint": "在「加入共享」中填入房主提供的邀請連結。",
+ "joinedEmptyTitle": "還沒有加入共享",
+ "joinedEmptyHint": "開啟夥伴傳來的邀請連結,即可加入共享任務。",
"joinedLoadFailed": "暫時無法取得已加入的共享任務,請重試",
"joinedTab": "我加入的",
"reconnecting": "正在重新連線…",
"ownedLoadFailed": "暫時無法取得",
"loadingOwned": "正在取得…",
- "retryAction": "重試",
+ "retryAction": "重新載入",
"invitationCopyFailed": "無法複製邀請連結,請重試",
"accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新的邀請連結。",
"joinIntro": "貼上房主傳來的邀請連結,使用你的帳號暱稱加入任務。",
@@ -87,7 +87,7 @@
"waitingHost": "等待房主處理,你可以繼續傳送訊息。",
"join": "加入共享任務",
"login": "請登入 Cindy 後加入任務",
- "invitation": "邀請連結",
+ "invitation": "邀請連結或邀請碼",
"dismiss": "關閉視窗",
"title": "共享任務",
"hostLimit": "開啟的共享任務已達目前上限,請關閉共享任務,直到數量低於上限後再試。",
@@ -135,15 +135,21 @@
"closedToast": "已取消 {{count}} 個任務的共享",
"closeFailedToast": "部分共享未能取消({{count}} 項),可稍後重試。",
"back": "返回",
- "cancelOperation": "取消操作",
+ "cancelOperation": "取消",
"invalidInvitation": "請貼上有效的邀請連結或邀請碼",
- "ownedManageIntro": "管理你發起的共享,包括其他電腦上的任務。",
- "joinedManageIntro": "開啟任務繼續工作,或退出不再參與的共享。",
+ "ownedManageIntro": "包含這個帳號在其他電腦上發起的共享。",
+ "joinedManageIntro": "退出後將無法繼續存取此共享;房主和其他成員不受影響。",
"recordsKept": "任務記錄和 Agent 工作會保留。",
"othersUnaffected": "其他成員與 Agent 的工作不受影響。",
"viewJoined": "查看我加入的",
"invalid": "請貼上有效的邀請連結或邀請碼",
- "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結"
+ "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結",
+ "managementIntro": "管理你發起和加入的共享。",
+ "returnToTasks": "返回任務清單",
+ "invitationDetected": "發現共享任務邀請",
+ "notNow": "暫不加入",
+ "closeAllLabel": "取消全部共享",
+ "closeAllDescription": "所有訪客將無法繼續存取,任務記錄保留。"
},
"privacyExit": {
"status": "正在透過 Cindy 被遠端控制",
diff --git a/apps/desktop/src/renderer/lib/tabLabels.ts b/apps/desktop/src/renderer/lib/tabLabels.ts
index 7d575a8c6e..5aaaa6cc95 100644
--- a/apps/desktop/src/renderer/lib/tabLabels.ts
+++ b/apps/desktop/src/renderer/lib/tabLabels.ts
@@ -20,6 +20,7 @@ export type SettingsTab =
| 'import'
| 'connections'
| 'remote-control'
+ | 'shared-tasks'
| 'tina'
| 'ghosts'
| 'builtin-tools'
@@ -52,6 +53,7 @@ export const TAB_IDS = [
// 意识化收尾(Google/Jira/GitHub/GitLab 此前已迁意识)。id 仍留在 SettingsTab
// 类型与 TAB_LABEL_KEY 保留,供旧深链重定向到插件分区。
'remote-control',
+ 'shared-tasks',
'ghosts',
'builtin-tools',
'computer-use',
@@ -76,6 +78,7 @@ export const TAB_LABEL_KEY: Record<SettingsTab, string> = {
connections: 'settings.tabs.connections',
providers: 'settings.tabs.providers',
'remote-control': 'settings.tabs.remoteControl',
+ 'shared-tasks': 'sharedTask.title',
tina: 'settings.tabs.tina',
ghosts: 'settings.tabs.ghosts',
'builtin-tools': 'settings.tabs.builtinTools',
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index f1ab17bf9b..e64e1dcfa7 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -78,6 +78,7 @@ import {
} from '@/session/precreatedWorktreeRecovery';
import { IncomingShareBridge } from '@/session/IncomingShareBridge';
import { usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
+import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';
import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntryProvider';
import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';
@@ -92,6 +93,7 @@ function NavigationGate() {
const auth = useAuth();
const router = useRouter();
const segments = useSegments();
+ useClipboardSharedTaskInvitation(auth.initialized && auth.isAuthenticated, segments.join('/') === 'shared-session');
const { mode, colors, preferenceReady } = useTheme();
const { releaseSplash, splashActive } = useStartupSplash();
// iOS 状态栏样式走 react-native-screens 的 VC-based 通道(Info.plist 已翻
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 734d228dfb..450bb639f7 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -9324,7 +9324,7 @@ export default function SessionScreen() {
<View style={styles.sessionMainLayer} testID="session.mainLayer">
{isSharedTaskAccessRevoked ? (
<ScrollView contentContainerStyle={{ paddingTop: topOverlayHeight + spacing.lg, paddingHorizontal: spacing.lg }}>
- <SharedTaskEndedState onRejoin={() => router.replace('/shared-session')} />
+ <SharedTaskEndedState onReturnToTasks={() => router.replace('/devices')} />
</ScrollView>
) : sessionOperationLayout.composerSlot === 'missing-session' && remoteUnavailableReason ? (
// 会话行尚未到达时保留状态占位;自动恢复类错误不再提供手动同步入口。
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 1c5f3cc4e2..f12f03300a 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -1142,6 +1142,16 @@ export default function SettingsScreen() {
]}
</SettingsGroup>
+ <SettingsGroup title={t('sharedTask.title')}>
+ <ActionInfoRow
+ accessibilityLabel={t('sharedTask.manageSharing')}
+ label={t('sharedTask.manageSharing')}
+ value=""
+ onPress={() => router.push({ pathname: '/shared-session', params: { mode: 'manage' } })}
+ testID="settings.sharedTasks.row"
+ />
+ </SettingsGroup>
+
{/* 显示模式:默认跟随系统,手动选择浅色 / 深色即持久化 override(恢复跟随系统 = 清除 override) */}
<SettingsGroup title={t('settings.appearance.title')}>
<NativePullDownMenu
diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsx
index a330a30929..be28adf9a1 100644
--- a/apps/mobile/app/shared-session.tsx
+++ b/apps/mobile/app/shared-session.tsx
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
-import { AppState, Keyboard, Platform, StyleSheet, View } from 'react-native';
-import * as Clipboard from 'expo-clipboard';
+import { AppState, Keyboard, Pressable, StyleSheet, View } from 'react-native';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { Check, Clock, FileText, Laptop, Link, Users } from 'lucide-react-native';
@@ -17,10 +16,11 @@ import { sharedTaskErrorKey } from '@/device-link/sharedTaskCompatibility';
import { isSharedTaskGone } from '@/device-link/sharedTaskAccessWatch';
import { markDeviceAccessRevoked } from '@/device-link/accessRevoked';
import { Text, TextInput } from '@/components/AppText';
-import { MainWindowRowButton } from '@/components/MobilePrimitives';
+import { MainWindowActionButton, MainWindowRowButton } from '@/components/MobilePrimitives';
import { SharedTaskAction, SharedTaskScreen } from '@/session/SharedTaskScreen';
import { useSharedTaskConfirmation } from '@/session/useSharedTaskConfirmation';
import { SharedTaskEndedState } from '@/session/SharedTaskEndedState';
+import { SharedTaskAdmissionDialog } from '@/session/SharedTaskAdmissionDialog';
import { remoteSessionStore } from '@/session/remoteSessionStore';
import { writeClipboardText } from '@/session/messageActions';
import type { RemoteSession } from '@/session/types';
@@ -29,11 +29,11 @@ import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/
/** Plan B management only; conversation/input continue through the ordinary remote task. */
export default function SharedSessionScreen() {
- const { sessionId, deviceId, sharedTaskId } = useLocalSearchParams<{ sessionId?: string; deviceId?: string; sharedTaskId?: string }>();
+ const { sessionId, deviceId, sharedTaskId, expectedOwnedSharedTaskId, mode } = useLocalSearchParams<{ sessionId?: string; deviceId?: string; sharedTaskId?: string; expectedOwnedSharedTaskId?: string; mode?: string }>();
+ const management = mode === 'manage' && !sessionId && !deviceId && !sharedTaskId;
const router = useRouter();
const { t } = useTranslation();
const { isAuthenticated, accountGeneration, user } = useAuth();
- const pasteOwner = getMobileAuthOwner();
const incomingInvitation = usePendingSharedTaskInvitationIntent();
const api = useSharedTaskApi();
const confirmation = useSharedTaskConfirmation();
@@ -42,12 +42,16 @@ export default function SharedSessionScreen() {
const styles = useThemedStyles(makeStyles);
const [invitation, setInvitation] = 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 [ownedTargetUnavailable, setOwnedTargetUnavailable] = useState(false);
const [owned, setOwned] = useState<SharedTaskListItem[]>([]);
+ const [joined, setJoined] = useState<SharedTaskListItem[]>([]);
+ const [loaded, setLoaded] = useState(false);
+ const [manualOpen, setManualOpen] = useState(false);
+ const [clipboardInvitation, setClipboardInvitation] = useState(false);
const [guestCounts, setGuestCounts] = useState<Record<string, number>>({});
const [deviceNames, setDeviceNames] = useState<Record<string, string>>({});
- const [tab, setTab] = useState<'current' | 'owned'>('current');
+ const [tab, setTab] = useState<'current' | 'owned' | 'joined'>('current');
const [joinedId, setJoinedId] = useState<string>();
const [ended, setEnded] = useState(false);
const [notice, setNotice] = useState('');
@@ -79,11 +83,13 @@ export default function SharedSessionScreen() {
const owner = getMobileAuthOwner();
const current = () => visible() && mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner);
if (!isAuthenticated || link.sharedTaskAvailable !== true || ended) return;
- if (!guestId && tab === 'owned') {
+ if (!guestId && (management || tab === 'owned')) {
const value = await api.list();
if (!current()) return;
const mine = value.filter((task) => task.ownerAccountId === owner.accountId);
setOwned(mine);
+ setJoined(value.filter((task) => task.ownerAccountId !== owner.accountId));
+ setLoaded(true);
const counts: Record<string, number> = {};
for (const task of mine) {
if (!current()) return;
@@ -99,6 +105,14 @@ export default function SharedSessionScreen() {
const value = guestId ? { available: true, detail: await api.get(guestId) }
: await host({ action: 'state', sessionId: sessionId! }) as SharedTaskHostState;
if (!current()) return;
+ // A management list entry identifies one sharing lifetime, not its replacement.
+ if (hostContext && expectedOwnedSharedTaskId && (!value.detail
+ || value.detail.sharedTaskId !== expectedOwnedSharedTaskId
+ || value.detail.sessionId !== sessionId || value.detail.status !== 'active')) {
+ setState(null); setOwnedTargetUnavailable(true);
+ return;
+ }
+ setOwnedTargetUnavailable(false);
if (guestId && value.detail?.status === 'closed') endAccess();
else setState(value);
if (hostContext) {
@@ -115,15 +129,15 @@ export default function SharedSessionScreen() {
setOwned(value.filter((task) => task.ownerAccountId === owner.accountId));
}
}
- }, [api, ended, endAccess, guestId, host, hostContext, isAuthenticated, link.readDeviceList, link.sharedTaskAvailable, sessionId, tab]);
+ }, [api, ended, endAccess, expectedOwnedSharedTaskId, guestId, host, hostContext, isAuthenticated, link.readDeviceList, link.sharedTaskAvailable, sessionId, tab, management]);
useEffect(() => {
mounted.current = true;
epoch.current++; pending.current = false; setBusy(false);
- setState(null); setOwned([]); setGuestCounts({}); setJoinedId(undefined); setEnded(false);
- setInvitation(''); setIncomingLink(null); pasteVersion.current++;
- setNotice(''); setLoadError(''); setTab('current'); confirmationPending.current = null;
+ setState(null); setOwnedTargetUnavailable(false); setOwned([]); setJoined([]); setLoaded(false); setManualOpen(false); setClipboardInvitation(false); setGuestCounts({}); setJoinedId(undefined); setEnded(false);
+ setInvitation(''); setIncomingLink(null);
+ setNotice(''); setLoadError(''); setTab(management ? 'owned' : 'current'); confirmationPending.current = null;
return () => { mounted.current = false; epoch.current++; };
- }, [accountGeneration, deviceId, sessionId, sharedTaskId]);
+ }, [accountGeneration, deviceId, sessionId, sharedTaskId, expectedOwnedSharedTaskId, management]);
useFocusEffect(useCallback(() => {
const captured = ++pageGeneration.current;
return () => {
@@ -218,6 +232,7 @@ export default function SharedSessionScreen() {
const joined = await api.join(parsed.invitation, sharedTaskAccountName(user?.name));
if (!current()) return;
Keyboard.dismiss(); setInvitation(''); setJoinedId(joined.sharedTaskId);
+ setManualOpen(false); setClipboardInvitation(false);
if (enter) await openTask(joined.sharedTaskId, current);
}, false, 'join');
useEffect(() => {
@@ -226,36 +241,16 @@ export default function SharedSessionScreen() {
// 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() });
+ setIncomingLink(incomingInvitation.source === 'link' ? { link: input, owner: getMobileAuthOwner() } : null);
clearSharedTaskInvitationIntent();
setInvitation(input);
+ setClipboardInvitation(incomingInvitation.source === 'clipboard');
}, [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);
@@ -290,21 +285,74 @@ export default function SharedSessionScreen() {
router.replace('/devices');
}, false);
const taskCard = <View style={styles.taskRow}><FileText size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{title}</Text><Text style={styles.metadata}>{task?.deviceLinkDeviceName ?? t('sharedTask.runsOnHostDevice')}</Text></View></View>;
+ const leaveListed = (item: SharedTaskListItem) => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async current => {
+ await api.leave(item.sharedTaskId);
+ if (!current()) return;
+ const target = sharedTaskHostPeer(item.sharedTaskId, item.hostDeviceId);
+ link.closeLink(target); remoteSessionStore.removeDevice(target);
+ setJoined(items => items.filter(task => task.sharedTaskId !== item.sharedTaskId));
+ });
+ const manageListed = (item: SharedTaskListItem) => void run(async current => {
+ await link.openLink(item.hostDeviceId);
+ if (current()) router.push({ pathname: '/shared-session', params: { sessionId: item.sessionId, deviceId: item.hostDeviceId, expectedOwnedSharedTaskId: item.sharedTaskId, mode: 'detail' } });
+ }, false);
+ const invitationForm = <>
+ <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={text => { setIncomingLink(null); setInvitation(text); setNotice(''); }} maxLength={8192} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></View>
+ <Text style={styles.smallMuted}>{t('sharedTask.joinNotice')}</Text>
+ {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
+ <View style={styles.footer}>
+ <SharedTaskAction grow action={{ label: t('sharedTask.cancelOperation'), disabled: busy, onPress: () => setManualOpen(false) }} />
+ <SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, disabled: !invitation.trim(), onPress: () => joinInvitation(invitation, true) }} />
+ </View>
+ </>;
+ const managementView = <>
+ <View style={styles.managementHeading}>
+ <View style={styles.managementHeadingCopy}><Text accessibilityRole="header" style={styles.managementTitle}>{t('sharedTask.title')}</Text><Text style={styles.managementDescription}>{t('sharedTask.managementIntro')}</Text></View>
+ <MainWindowActionButton density="compact" style={styles.managementButton} textStyle={styles.managementButtonText} action={{ label: t('sharedTask.join'), disabled: busy, onPress: () => { setNotice(''); setInvitation(''); setManualOpen(true); } }} />
+ </View>
+ <View style={styles.managementTabs}>{(['owned', 'joined'] as const).map(kind => <Pressable key={kind} accessibilityRole="tab" accessibilityLabel={t(kind === 'owned' ? 'sharedTask.tabOwned' : 'sharedTask.joinedTab')} accessibilityState={{ selected: tab === kind, disabled: busy }} disabled={busy} style={styles.managementTab} onPress={() => { setNotice(''); setTab(kind); }}>
+ <View style={styles.managementTabLabel}><Text style={[styles.managementTabText, tab === kind && styles.managementTabTextSelected]}>{t(kind === 'owned' ? 'sharedTask.tabOwned' : 'sharedTask.joinedTab')}</Text>{loaded && <Text style={styles.metadata}>{(kind === 'owned' ? owned : joined).length}</Text>}</View>
+ {tab === kind && <View style={styles.managementTabIndicator} />}
+ </Pressable>)}</View>
+ {!loaded ? !loadError && <Text style={styles.intro}>{t('shared.syncing')}</Text> : (tab === 'owned' ? owned : joined).length === 0 ? <View style={styles.managementEmpty}>
+ <View style={styles.managementEmptyIcon}><Users size={iconSize.md} color={colors.textTertiary} /></View><Text style={styles.emptyTitle}>{t(tab === 'owned' ? 'sharedTask.ownedEmptyTitle' : 'sharedTask.joinedEmptyTitle')}</Text><Text style={styles.emptyCopy}>{t(tab === 'owned' ? 'sharedTask.ownedEmptyHint' : 'sharedTask.joinedEmptyHint')}</Text>
+ {tab === 'owned' && <MainWindowActionButton density="compact" style={styles.managementButton} textStyle={styles.managementButtonText} action={{ label: t('sharedTask.returnToTasks'), onPress: () => router.replace('/devices') }} />}
+ </View> : <>
+ <View style={styles.managementList}>{(tab === 'owned' ? owned : joined).map((item, index) => <View key={item.sharedTaskId} style={[styles.managementRow, index > 0 && styles.managementRowDivider]}>
+ <View style={styles.grow}>
+ <Pressable accessibilityRole="button" accessibilityLabel={item.title} disabled={busy} style={styles.managementTaskTitleTarget} onPress={() => void run(current => openTask(item.sharedTaskId, current), false)}><Text style={styles.taskTitle}>{item.title}</Text></Pressable>
+ <Text style={styles.managementMetadata}>{tab === 'owned' ? deviceName(item.hostDeviceId) : t('sharedTask.roleGuest')} · {t('sharedTask.sharingBadge')}</Text>
+ </View>
+ <View style={styles.managementRowActions}>
+ {tab === 'joined' && <MainWindowActionButton density="compact" style={styles.managementButton} textStyle={styles.managementButtonText} action={{ label: t('sharedTask.enterTask'), disabled: busy, onPress: () => void run(current => openTask(item.sharedTaskId, current), false) }} />}
+ <MainWindowActionButton density="compact" style={styles.managementButton} textStyle={styles.managementButtonText} action={{ label: t(tab === 'owned' ? 'sharedTask.manage' : 'sharedTask.leaveShort'), tone: tab === 'joined' ? 'danger' : undefined, disabled: busy, onPress: () => tab === 'owned' ? manageListed(item) : leaveListed(item) }} />
+ </View>
+ </View>)}</View>
+ <Text style={styles.managementListNote}>{t(tab === 'owned' ? 'sharedTask.ownedManageIntro' : 'sharedTask.joinedManageIntro')}</Text>
+ {tab === 'owned' && <View style={styles.managementDangerZone}>
+ <Text style={styles.taskTitle}>{t('sharedTask.closeAllLabel')}</Text><Text style={styles.managementDangerDescription}>{t('sharedTask.closeAllDescription')}</Text>
+ <MainWindowActionButton density="compact" style={styles.managementDangerButton} textStyle={styles.managementButtonText} action={{ label: t('sharedTask.closeAllLabel'), tone: 'danger', disabled: busy, onPress: () => closeTasks([...owned]) }} />
+ </View>}
+ </>}
+ {manualOpen && <SharedTaskAdmissionDialog title={t('sharedTask.join')} onClose={() => { if (!pending.current) setManualOpen(false); }}>{invitationForm}</SharedTaskAdmissionDialog>}
+ </>;
return <SharedTaskScreen
- title={t(ended ? 'sharedTask.ended' : !guestId && tab === 'owned' ? 'sharedTask.ownedTitle' : hostContext || guestId ? 'sharedTask.title' : 'sharedTask.join')}
+ management={management && !guestId}
+ title={t(ended ? 'sharedTask.ended' : management ? 'sharedTask.title' : !guestId && tab === 'owned' ? 'sharedTask.ownedTitle' : hostContext || guestId ? 'sharedTask.title' : 'sharedTask.join')}
onClose={() => { clearSharedTaskInvitationIntent(); setIncomingLink(null); goBackGuarded(router, '/devices'); }}>
{confirmation.dialog}
- {!isAuthenticated ? <Text style={styles.intro}>{t('sharedTask.login')}</Text> : ended ? <SharedTaskEndedState onRejoin={() => {
+ {!isAuthenticated ? <Text style={styles.intro}>{t('sharedTask.login')}</Text> : ended ? <SharedTaskEndedState onReturnToTasks={() => {
setJoinedId(undefined); setEnded(false); setState(null); setNotice(''); setLoadError('');
- router.replace('/shared-session');
+ router.replace('/devices');
}} /> : link.sharedTaskAvailable !== true ? <Text style={styles.intro}>{t(link.sharedTaskAvailable === false ? 'sharedTask.upgrade' : 'sharedTask.retry')}</Text> : <>
- {!guestId && <View style={styles.tabs}>
+ {!guestId && !management && !clipboardInvitation && <View style={styles.tabs}>
<MainWindowRowButton accessibilityLabel={t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')} selected={tab === 'current'} style={[styles.tab, tab === 'current' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('current'); }}><Text style={styles.small}>{t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')}</Text></MainWindowRowButton>
<MainWindowRowButton accessibilityLabel={t('sharedTask.tabOwned')} selected={tab === 'owned'} style={[styles.tab, tab === 'owned' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('owned'); }}><Text style={styles.small}>{t('sharedTask.tabOwned')}</Text><View style={styles.badge}><Text style={styles.metadata}>{owned.length}</Text></View></MainWindowRowButton>
</View>}
- {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
- {!!loadError && <Text accessibilityRole="alert" style={styles.noticeText}>{loadError}</Text>}
- {!guestId && tab === 'owned' ? owned.length === 0 ? <View style={styles.empty}>
+ {!!notice && !manualOpen && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
+ {!!loadError && <View><Text accessibilityRole="alert" style={styles.noticeText}>{loadError}</Text><SharedTaskAction action={{ label: t('sharedTask.retryAction'), disabled: busy, onPress: () => void run(async current => { await load(current); if (current()) setLoadError(''); }, false) }} /></View>}
+ {management && !guestId ? managementView : !guestId && tab === 'owned' ? owned.length === 0 ? <View style={styles.empty}>
<View style={styles.largeIcon}><Check size={iconSize.md} color={colors.textPrimary} /></View>
<Text style={styles.emptyTitle}>{t('sharedTask.ownedEmptyTitle')}</Text><Text style={styles.emptyCopy}>{t('sharedTask.ownedEmptyHint')}</Text>
{hostContext && <SharedTaskAction action={{ label: t('sharedTask.shareCurrent'), onPress: () => setTab('current') }} />}
@@ -323,7 +371,7 @@ export default function SharedSessionScreen() {
<SharedTaskAction action={{ label: t('sharedTask.enterTask'), tone: 'primary', busy, onPress: () => void run((current) => openTask(guestId, current), false) }} />
</View>
{!ownDetail && <><View style={styles.rule} /><SharedTaskAction action={{ label: t('sharedTask.leave'), tone: 'danger', disabled: busy, onPress: leave }} /></>}
- </> : hostContext ? !state ? <Text style={styles.intro}>{t('shared.syncing')}</Text> : !state.available ? <Text style={styles.intro}>{t('sharedTask.upgrade')}</Text> : !detail ? <>
+ </> : hostContext ? ownedTargetUnavailable ? <Text style={styles.intro}>{t('sharedTask.unavailable')}</Text> : !state ? <Text style={styles.intro}>{t('shared.syncing')}</Text> : !state.available ? <Text style={styles.intro}>{t('sharedTask.upgrade')}</Text> : !detail ? <>
<Text style={styles.intro}>{t('sharedTask.startIntro')}</Text>{taskCard}
<View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.inviteNotice')}</Text></View>
<Text style={styles.smallMuted}>{t('sharedTask.offlineAutoClose')}</Text>
@@ -345,18 +393,19 @@ export default function SharedSessionScreen() {
<SharedTaskAction compact action={{ label: t('sharedTask.removeShort'), tone: 'danger', accessibilityLabel: t('sharedTask.removeNamedTitle', { name: member.displayName }), disabled: busy, onPress: () => confirm(t('sharedTask.removeNamedTitle', { name: member.displayName }), t('sharedTask.removeBody'), t('sharedTask.removeKeep'), t('sharedTask.remove'), async () => { await host({ action: 'remove', sharedTaskId: detail.sharedTaskId, memberId: member.memberId }); }) }} />
</View>)}
<View style={styles.noticeBox}><Clock size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.remoteHostOfflineNote')}</Text></View>
- <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>
- </> : <>
+ <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 current => {
+ await host({ action: 'close', sharedTaskId: detail.sharedTaskId });
+ if (current() && mode === 'detail') goBackGuarded(router, { pathname: '/shared-session', params: { mode: 'manage' } });
+ }) }} /></View>
+ </> : clipboardInvitation ? <SharedTaskAdmissionDialog title={t('sharedTask.invitationDetected')} onClose={() => { if (!pending.current) router.replace('/devices'); }}>
<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={(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>
+ <Text style={styles.taskTitle}>{sharedTaskAccountName(user?.name)}</Text>
+ <Text style={styles.emptyCopy}>{t('sharedTask.joinNotice')}</Text>
+ {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.notNow'), disabled: busy, onPress: () => router.replace('/devices') }} /><SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, onPress: () => joinInvitation(invitation, true) }} /></View>
+ </SharedTaskAdmissionDialog> : <>
+ <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={(text) => { setIncomingLink(null); setInvitation(text); }} maxLength={8192} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></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(), onPress: () => joinInvitation(invitation) }} /></View>
</>}
@@ -364,7 +413,30 @@ export default function SharedSessionScreen() {
</SharedTaskScreen>;
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
- pasteButton: { minHeight: 44, width: 160 },
+ managementEmpty: { alignItems: 'center', paddingVertical: spacing.xxl * 2, paddingHorizontal: spacing.md },
+ managementEmptyIcon: { width: 48, height: 48, alignItems: 'center', justifyContent: 'center', borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.pill, marginBottom: spacing.lg + spacing.xs },
+ managementHeading: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start', gap: spacing.sm + spacing.xs, marginTop: spacing.sm, marginBottom: spacing.lg + spacing.xs },
+ managementHeadingCopy: { flex: 1, minWidth: 160 },
+ managementTitle: { color: colors.textPrimary, fontSize: typeScale.headline, lineHeight: lineHeight.headline, fontWeight: fontWeight.semibold },
+ managementDescription: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.sm },
+ managementButton: { minHeight: 44, paddingHorizontal: spacing.md, backgroundColor: colors.surface, flexShrink: 0 },
+ managementButtonText: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
+ managementTabs: { flexDirection: 'row', gap: spacing.lg + spacing.md, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: colors.border, marginBottom: spacing.xl },
+ managementTab: { minHeight: 44, justifyContent: 'center', paddingBottom: spacing.md },
+ managementTabLabel: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
+ managementTabText: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ managementTabTextSelected: { color: colors.textPrimary },
+ managementTabIndicator: { position: 'absolute', bottom: -StyleSheet.hairlineWidth, left: 0, right: 0, height: 2, backgroundColor: colors.textPrimary },
+ managementList: { borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.container, overflow: 'hidden' },
+ managementRow: { flexDirection: 'row', alignItems: 'flex-start', paddingVertical: spacing.lg, paddingHorizontal: spacing.md, gap: spacing.md },
+ managementRowDivider: { borderTopWidth: StyleSheet.hairlineWidth, borderColor: colors.border },
+ managementTaskTitleTarget: { minHeight: 44, justifyContent: 'center' },
+ managementMetadata: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginTop: spacing.xs },
+ managementRowActions: { gap: spacing.xs, alignItems: 'flex-end' },
+ managementListNote: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.lg },
+ managementDangerZone: { borderTopWidth: StyleSheet.hairlineWidth, borderColor: colors.border, marginTop: spacing.xxl, paddingTop: spacing.xl },
+ managementDangerDescription: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.xs },
+ managementDangerButton: { minHeight: 44, marginTop: spacing.lg, backgroundColor: colors.surface },
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__/clipboardSharedTaskInvitation.test.tsx b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
new file mode 100644
index 0000000000..e0c46c3fe2
--- /dev/null
+++ b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
@@ -0,0 +1,77 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';
+import { clearSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
+
+const h = vi.hoisted(() => ({ read: vi.fn(), state: 'active', listener: null as null | ((state: string) => void) }));
+vi.mock('expo-clipboard', () => ({ getStringAsync: h.read }));
+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test' }));
+vi.mock('react-native', () => ({ AppState: {
+ get currentState() { return h.state; },
+ addEventListener: (_event: string, listener: (state: string) => void) => {
+ h.listener = listener; return { remove: () => { if (h.listener === listener) h.listener = null; } };
+ },
+} }));
+const token = 'A'.repeat(43);
+const link = 'https://relay.example.test/shared-task/join#' + token;
+let root: Root;
+function Harness({ enabled, joining }: { enabled: boolean; joining: boolean }) {
+ useClipboardSharedTaskInvitation(enabled, joining); return null;
+}
+async function render(enabled = true, joining = false) {
+ await act(async () => root.render(createElement(Harness, { enabled, joining })));
+}
+async function state(next: string) { await act(async () => { h.state = next; h.listener?.(next); }); }
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.useFakeTimers(); h.read.mockReset(); h.read.mockResolvedValue(link); h.state = 'active';
+ clearSharedTaskInvitationIntent(); setMobileAuthOwner('guest');
+ root = createRoot(document.createElement('div'));
+});
+afterEach(async () => { await act(async () => root.unmount()); clearSharedTaskInvitationIntent(); vi.useRealTimers(); });
+
+it('reads on startup and identifies the invitation as clipboard admission', async () => {
+ await render();
+ expect(h.read).toHaveBeenCalledTimes(1);
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });
+});
+it('reads on foreground, deduplicates consumed links, and detects a newly copied link', async () => {
+ await render(); clearSharedTaskInvitationIntent();
+ await state('background'); await state('active');
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ h.read.mockResolvedValue(link.replace(token, 'B'.repeat(43)));
+ await state('background'); await state('active');
+ expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe('B'.repeat(43));
+ clearSharedTaskInvitationIntent(); h.read.mockResolvedValue(link);
+ await state('background'); await state('active');
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+});
+it.each(['hello', token, link.replace('relay.example.test', 'other.example.test'), link + '?app=unknown'])('ignores ordinary or incompatible clipboard content: %s', async text => {
+ h.read.mockResolvedValue(text); await render(); expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+});
+it('does not reread after an inactive/active permission prompt', async () => {
+ await render(); clearSharedTaskInvitationIntent();
+ await state('inactive'); await state('active'); expect(h.read).toHaveBeenCalledTimes(1);
+});
+it('waits for login and leaves an open admission form alone', async () => {
+ await render(false); expect(h.read).not.toHaveBeenCalled();
+ await render(true, true); expect(h.read).not.toHaveBeenCalled();
+});
+it.each(['account', 'manual', 'link'] as const)('discards delayed clipboard results superseded by %s', async reason => {
+ let finish!: (text: string) => void;
+ h.read.mockImplementation(() => new Promise(resolve => { finish = resolve; })); await render();
+ if (reason === 'account') setMobileAuthOwner('another');
+ if (reason === 'manual') await render(true, true);
+ if (reason === 'link') {
+ receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test');
+ clearSharedTaskInvitationIntent();
+ }
+ await act(async () => finish(link)); expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+});
+it('ignores clipboard denial without interrupting the app', async () => {
+ h.read.mockRejectedValue(new Error('Clipboard unavailable')); await render();
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+});
diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
index 3620411ef2..960346acc6 100644
--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
@@ -52,7 +52,7 @@ describe('mobile session main layer desktop-first noise budget', () => {
expect(revokedEnd).toBeGreaterThan(revokedStart);
expect(source.slice(revokedStart, revokedEnd)).toContain('paddingTop: topOverlayHeight + spacing.lg');
expect(source.slice(revokedStart, revokedEnd)).toContain('<SharedTaskEndedState');
- expect(source.slice(revokedStart, revokedEnd)).toContain("router.replace('/shared-session')");
+ expect(source.slice(revokedStart, revokedEnd)).toContain("router.replace('/devices')");
expect(routeSource).toContain('cachedOnly={showCachedHistoryNotice}');
expect(source.replace(/\r\n/g, '\n'))
.toContain('useShowConnectionBanner(\n status,\n bannerError,');
diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
index 01317a6522..10bff18eff 100644
--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
@@ -6,13 +6,12 @@ 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(() => ({
- params: {} as { sessionId?: string; deviceId?: string; sharedTaskId?: string }, generation: 1,
- router: { replace: vi.fn() }, alert: vi.fn(), revoked: vi.fn(),
+ params: {} as { sessionId?: string; deviceId?: string; sharedTaskId?: string; expectedOwnedSharedTaskId?: string; mode?: string }, generation: 1,
+ router: { replace: vi.fn(), push: vi.fn() }, alert: vi.fn(), revoked: vi.fn(),
link: { sharedTaskAvailable: true, invoke: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), readDeviceList: vi.fn() },
api: { list: vi.fn(), get: vi.fn(), join: vi.fn(), leave: vi.fn(), close: vi.fn() },
store: { getSessions: () => [], removeDevice: vi.fn(), setDeviceSessions: vi.fn(), upsertDeviceSession: vi.fn() },
@@ -20,7 +19,6 @@ const h = vi.hoisted(() => ({
}));
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 }));
@@ -44,6 +42,7 @@ vi.mock('react-native', () => ({
ActionSheetIOS: {},
Alert: { alert: h.alert }, AppState: { currentState: 'active' }, Keyboard: { dismiss: vi.fn() },
Platform: { OS: 'android' },
+ Modal: ({ children }: { children?: ReactNode }) => createElement('div', { role: 'dialog' }, children),
AccessibilityInfo: { setAccessibilityFocus: vi.fn() }, findNodeHandle: () => null,
View: ({ children, testID, accessibilityElementsHidden }: { children?: ReactNode; testID?: string; accessibilityElementsHidden?: boolean }) => createElement('div', { 'data-testid': testID, hidden: accessibilityElementsHidden }, children),
KeyboardAvoidingView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
@@ -57,6 +56,7 @@ vi.mock('@/components/AppText', () => ({
TextInput: ({ accessibilityLabel, multiline, maxLength, value, onChangeText }: { accessibilityLabel: string; multiline?: boolean; maxLength?: number; value: string; onChangeText(value: string): void }) => createElement(multiline ? 'textarea' : 'input', { 'aria-label': accessibilityLabel, maxLength, value, onInput: (e: { currentTarget: HTMLInputElement }) => onChangeText(e.currentTarget.value), onChange: () => {} }),
}));
vi.mock('@/components/MobilePrimitives', () => ({
+ ScreenBackButton: ({ onPress }: { onPress(): void }) => createElement('button', { onClick: onPress }, 'back'),
MainWindowActionButton: ({ action }: { action: { label: string; disabled?: boolean; busy?: boolean; onPress(): void } }) => createElement('button', { disabled: action.disabled || action.busy, onClick: action.onPress }, action.label),
MainWindowRowButton: ({ children, onPress, accessibilityLabel }: { children?: ReactNode; onPress(): void; accessibilityLabel?: string }) => createElement('button', { onClick: onPress, 'aria-label': accessibilityLabel }, children),
MainWindowOptionButton: ({ label, onPress }: { label: string; onPress(): void }) => createElement('button', { onClick: onPress }, label),
@@ -93,12 +93,13 @@ beforeEach(() => {
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);
+it('uses an automatically detected clipboard invitation without a paste or nickname control', async () => {
+ receiveSharedTaskInvitationIntent(invitationIntent, 'clipboard');
await render();
- expect(Clipboard.getStringAsync).not.toHaveBeenCalled();
- await click('sharedTask.pasteInvitation');
- expect((element.querySelector('textarea') as HTMLTextAreaElement).value).toContain(invitationLink);
+ expect(element.querySelector('textarea')).toBeNull();
+ expect(element.textContent).toContain('sharedTask.invitationDetected');
+ expect(element.textContent).not.toContain('sharedTask.pasteInvitation');
+ expect(h.api.join).not.toHaveBeenCalled();
await click('sharedTask.join');
expect(h.api.join).toHaveBeenCalledExactlyOnceWith('A'.repeat(43), 'Account Guest');
expect(element.querySelector('[aria-label="sharedTask.joinNickname"]')).toBeNull();
@@ -109,14 +110,6 @@ it('rejects an invitation from another service without joining', async () => {
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);
@@ -282,10 +275,8 @@ it('replaces stale guest state only for confirmed membership loss and can join a
expect(h.revoked).toHaveBeenCalledWith(sharedTaskHostPeer('shared', 'desktop'));
await act(async () => oldConfirm.onPress());
expect(h.api.leave).not.toHaveBeenCalled();
- await click('sharedTask.rejoin');
- expect(h.router.replace).toHaveBeenCalledWith('/shared-session');
- h.params = {}; await render();
- expect(element.querySelector('textarea')).not.toBeNull();
+ await click('sharedTask.returnToTasks');
+ expect(h.router.replace).toHaveBeenCalledWith('/devices');
});
it('closes only the confirmed owned tasks and retains failures for retry', async () => {
h.params = { sessionId: 'task', deviceId: 'host' };
@@ -367,3 +358,74 @@ it('ignores an old poll after switching away from and back to the current task',
expect(element.textContent).toContain('Design review');
expect(element.textContent).toContain('sharedTask.closeCurrent');
});
+
+it('keeps manual admission available on empty management and accepts a legacy code with the account nickname', async () => {
+ h.params = { mode: 'manage' };
+ h.link.invoke.mockResolvedValue({ id: 'task' });
+ await render();
+ expect(element.querySelector('textarea')).toBeNull();
+ expect(element.textContent).toContain('sharedTask.ownedEmptyTitle');
+ await click('sharedTask.join');
+ await fill('sharedTask.invitation', 'A'.repeat(43));
+ await click('sharedTask.join');
+ expect(h.api.join).toHaveBeenCalledExactlyOnceWith('A'.repeat(43), 'Account Guest');
+ expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/sessions/[sessionId]' }));
+});
+
+it('preserves the joined management tab on canceled admission and canceled leave', async () => {
+ h.params = { mode: 'manage' };
+ h.api.list.mockResolvedValue([{ ...owned('guest-task'), ownerAccountId: 'someone' }, owned('My task')]);
+ await render(); await click('sharedTask.joinedTab');
+ await click('sharedTask.join'); await click('sharedTask.cancelOperation');
+ expect(element.textContent).toContain('guest-task');
+ expect(element.textContent).not.toContain('My task');
+ await click('sharedTask.leaveShort');
+ await act(async () => confirmation()[0].onPress());
+ expect(h.api.leave).not.toHaveBeenCalled();
+ expect(element.textContent).toContain('guest-task');
+ await click('sharedTask.leaveShort');
+ h.api.list.mockResolvedValue([owned('My task')]);
+ await act(async () => confirmation()[1].onPress());
+ expect(h.api.leave).toHaveBeenCalledWith('guest-task');
+ expect(element.textContent).toContain('sharedTask.joinedEmptyTitle');
+ expect(h.router.replace).not.toHaveBeenCalled();
+});
+
+it('shows a retry on failed discovery instead of an empty management list', async () => {
+ h.params = { mode: 'manage' }; h.api.list.mockRejectedValue(new Error('offline'));
+ await render();
+ expect(element.textContent).not.toContain('sharedTask.ownedEmptyTitle');
+ h.api.list.mockResolvedValue([owned('My task')]);
+ await click('sharedTask.retryAction');
+ expect(element.textContent).toContain('My task');
+});
+
+it('opens owner management through the physical host and preserves the settings page beneath it', async () => {
+ h.params = { mode: 'manage' }; h.api.list.mockResolvedValue([owned('My task')]);
+ await render(); await click('sharedTask.manage');
+ expect(h.link.openLink).toHaveBeenCalledWith('host');
+ expect(h.router.push).toHaveBeenCalledWith({ pathname: '/shared-session', params: { sessionId: 'task', deviceId: 'host', expectedOwnedSharedTaskId: 'My task', mode: 'detail' } });
+ expect(h.router.replace).not.toHaveBeenCalled();
+});
+
+it.each([
+ { ...detail, sharedTaskId: 'replacement', title: 'Replacement sharing' },
+ { ...detail, sessionId: 'another-task' },
+ { ...detail, status: 'closed' },
+ null,
+])('rejects an expired owner management target instead of managing its replacement: %j', async replacement => {
+ vi.useFakeTimers();
+ h.params = { sessionId: 'task', deviceId: 'host', mode: 'detail', expectedOwnedSharedTaskId: 'shared' };
+ h.link.invoke.mockResolvedValue({ available: true, detail });
+ await render();
+ expect(element.textContent).toContain('sharedTask.closeCurrent');
+ h.link.invoke.mockResolvedValue({ available: true, detail: replacement });
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(element.textContent).toContain('sharedTask.unavailable');
+ expect(element.textContent).not.toContain('Replacement sharing');
+ for (const action of ['closeCurrent', 'removeShort', 'copyInvitation', 'open']) {
+ expect(element.textContent).not.toContain('sharedTask.' + action);
+ }
+ expect(h.revoked).not.toHaveBeenCalled();
+ expect(h.link.closeLink).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts
index d5a5e82267..920cc14304 100644
--- a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts
+++ b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts
@@ -2,7 +2,7 @@ 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 pending: (SharedTaskInvitationIntent & { id: number; source: 'link' | 'clipboard' }) | null = null;
let sequence = 0;
let stopWatching: (() => void) | undefined;
let expiry: ReturnType<typeof setTimeout> | undefined;
@@ -17,13 +17,13 @@ export function clearSharedTaskInvitationIntent(): void {
notify();
}
-export function receiveSharedTaskInvitationIntent(url: string): boolean {
+export function receiveSharedTaskInvitationIntent(url: string, source: 'link' | 'clipboard' = 'link'): boolean {
const value = parseSharedTaskInvitationIntent(url);
if (!value) return false;
clearSharedTaskInvitationIntent();
let owner = getMobileAuthOwner();
if (owner.switching) return true;
- pending = { ...value, id: ++sequence };
+ pending = { ...value, id: ++sequence, source };
stopWatching = subscribeMobileAuthOwner(() => {
const next = getMobileAuthOwner();
if (next.switching || (owner.accountKey && !isMobileAuthOwnerCurrent(owner))) clearSharedTaskInvitationIntent();
@@ -35,5 +35,6 @@ export function receiveSharedTaskInvitationIntent(url: string): boolean {
}
export const getPendingSharedTaskInvitationIntent = () => pending;
+export const getSharedTaskInvitationIntentSequence = () => sequence;
const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
export const usePendingSharedTaskInvitationIntent = () => useSyncExternalStore(subscribe, getPendingSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent);
diff --git a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
new file mode 100644
index 0000000000..835537e63b
--- /dev/null
+++ b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
@@ -0,0 +1,65 @@
+import { useEffect, useRef } from 'react';
+import { AppState, type AppStateStatus } from 'react-native';
+import * as Clipboard from 'expo-clipboard';
+import { parseSharedTaskInvitation } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
+import {
+ getPendingSharedTaskInvitationIntent, getSharedTaskInvitationIntentSequence,
+ receiveSharedTaskInvitationIntent,
+} from './sharedTaskInvitationIntent';
+
+/** Clipboard contents stay in memory. Only a valid link for this service opens admission. */
+export function useClipboardSharedTaskInvitation(enabled: boolean, joining: boolean): void {
+ const joiningRef = useRef(joining);
+ joiningRef.current = joining;
+ const seenInvitations = useRef(new Set<string>());
+ useEffect(() => {
+ if (!enabled) return;
+ let disposed = false;
+ let reading = false;
+ let started = false;
+ let background = false;
+ let activation = 0;
+ const check = async () => {
+ if (reading || joiningRef.current || getPendingSharedTaskInvitationIntent()) return;
+ const owner = getMobileAuthOwner();
+ if (owner.switching) return;
+ reading = true;
+ const captured = activation;
+ const sequence = getSharedTaskInvitationIntentSequence();
+ try {
+ const text = await Clipboard.getStringAsync();
+ if (disposed) return;
+ // Bare codes could be unrelated clipboard data; automatic detection accepts links only.
+ if (!/https?:\/\//.test(text)) return;
+ const parsed = parseSharedTaskInvitation(text, DEVICE_LINK_API_BASE_URL);
+ if (!parsed.ok || seenInvitations.current.has(parsed.invitation)) return;
+ if (joiningRef.current || !isMobileAuthOwnerCurrent(owner)
+ || sequence !== getSharedTaskInvitationIntentSequence() || getPendingSharedTaskInvitationIntent()) {
+ seenInvitations.current.add(parsed.invitation);
+ return;
+ }
+ if (captured !== activation || AppState.currentState !== 'active') return;
+ seenInvitations.current.add(parsed.invitation);
+ const url = 'cindy://shared-session?invitation=' + encodeURIComponent(parsed.invitation)
+ + '&server=' + encodeURIComponent(DEVICE_LINK_API_BASE_URL);
+ receiveSharedTaskInvitationIntent(url, 'clipboard');
+ } catch {
+ // Denied/unavailable clipboard access leaves the current page usable.
+ } finally {
+ reading = false;
+ if (!disposed && captured !== activation && AppState.currentState === 'active') void check();
+ }
+ };
+ const activate = (state: AppStateStatus) => {
+ if (state === 'background') { background = true; activation++; }
+ if (state !== 'active' || (started && !background)) return;
+ started = true; background = false;
+ void check();
+ };
+ const subscription = AppState.addEventListener('change', activate);
+ activate(AppState.currentState);
+ return () => { disposed = true; subscription.remove(); };
+ }, [enabled]);
+}
diff --git a/apps/mobile/src/i18n/locales/en/sharedTask.json b/apps/mobile/src/i18n/locales/en/sharedTask.json
index 0101297eac..103c72dc8f 100644
--- a/apps/mobile/src/i18n/locales/en/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/en/sharedTask.json
@@ -5,7 +5,7 @@
"login": "Sign in to Cindy to join a task.",
"openTask": "Open Task",
"notJoined": "This task is no longer shared with you.",
- "invitation": "Invitation Link",
+ "invitation": "Invitation link or code",
"invalid": "Paste a valid invitation link or code.",
"requestJoin": "Join",
"dismiss": "Close Dialog",
@@ -32,7 +32,7 @@
"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 host’s invitation link to join using your account name.",
+ "joinIntro": "Join the host’s shared task 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}}”",
@@ -68,8 +68,8 @@
"closeCurrent": "Stop Sharing This Task",
"sharingBadge": "Sharing",
"ownedIntro": "{{count}} tasks you share in this region",
- "ownedEmptyTitle": "Nothing is being shared",
- "ownedEmptyHint": "Open any task and click “Share Task” to invite a partner.",
+ "ownedEmptyTitle": "No shared tasks started yet",
+ "ownedEmptyHint": "Open a task and choose “Share Task” from its menu.",
"closeAll": "Stop All Sharing ({{count}})",
"closeAllNote": "After everything is closed, guests lose access and old invitations expire. Task history and Agent work are kept.",
"closeAllTitle": "Stop all sharing?",
@@ -89,7 +89,20 @@
"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.",
- "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."
+ "invitationDifferentServer": "This invitation belongs to another Cindy service. Open the link in the matching app.",
+ "managementIntro": "Manage the tasks you share and join.",
+ "manageSharing": "Manage Sharing",
+ "joinedTab": "Joined by Me",
+ "joinedEmptyTitle": "No shared tasks joined",
+ "joinedEmptyHint": "Open an invitation link from a teammate to join a shared task.",
+ "ownedManageIntro": "Includes tasks shared from your other computers.",
+ "retryAction": "Reload",
+ "cancelOperation": "Cancel",
+ "leaveShort": "Leave",
+ "returnToTasks": "Back to Tasks",
+ "invitationDetected": "Shared task invitation found",
+ "notNow": "Not Now",
+ "closeAllLabel": "Stop All Sharing",
+ "closeAllDescription": "Guests will lose access. Task history is kept.",
+ "joinedManageIntro": "Leaving removes your access. The host and other members are not affected."
}
diff --git a/apps/mobile/src/i18n/locales/ja/sharedTask.json b/apps/mobile/src/i18n/locales/ja/sharedTask.json
index 14ca97ecbc..683823ab22 100644
--- a/apps/mobile/src/i18n/locales/ja/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ja/sharedTask.json
@@ -5,7 +5,7 @@
"login": "セッションに参加するには Cindy にログインしてください。",
"openTask": "セッションを開く",
"notJoined": "この共有セッションにはアクセスできません。",
- "invitation": "招待リンク",
+ "invitation": "招待リンクまたは招待コード",
"invalid": "有効な招待リンクまたは招待コードを貼り付けてください。",
"requestJoin": "参加",
"dismiss": "ダイアログを閉じる",
@@ -32,7 +32,7 @@
"invitationCopied": "招待リンクをコピーしました",
"invitationCopyFailed": "招待リンクをコピーできませんでした。もう一度お試しください。",
"accessEndedBody": "この共有タスクにはアクセスできなくなりました。再参加するには、ホストに新しい招待を依頼してください。",
- "joinIntro": "ホストからの招待リンクを貼り付けると、アカウント名でタスクに参加します。",
+ "joinIntro": "アカウント名でホストの共有タスクに参加します。",
"invitationPlaceholder": "招待リンクまたは招待コードを貼り付け",
"joinNotice": "参加するとすべての履歴を閲覧でき、ホストの承認を待たずに Agent にメッセージを送信できます。",
"joinedTitle": "「{{title}}」に参加しました",
@@ -68,8 +68,8 @@
"closeCurrent": "このセッションの共有を停止",
"sharingBadge": "共有中",
"ownedIntro": "このリージョンで自分が共有中の {{count}} 件",
- "ownedEmptyTitle": "共有中のセッションはありません",
- "ownedEmptyHint": "任意のセッションを開いて「セッションを共有」から招待できます。",
+ "ownedEmptyTitle": "まだ共有を開始していません",
+ "ownedEmptyHint": "タスクを開き、タスクメニューから「タスクを共有」を選択してください。",
"closeAll": "すべての共有を停止({{count}})",
"closeAllNote": "すべて停止すると、ゲストはアクセスできなくなり、古い招待は無効になります。セッションの記録と Agent の作業は保持されます。",
"closeAllTitle": "すべての共有を停止しますか?",
@@ -89,7 +89,20 @@
"hostOfflineBody": "このセッションの共有は終了し、招待は無効になりました。ホストに再度共有を開始してもらい、新しい招待を送ってもらってください。",
"closedToast": "{{count}} 件のセッションの共有を停止しました",
"closeFailedToast": "停止できなかった共有があります({{count}} 件)。後ほど再試行できます。",
- "pasteInvitation": "招待リンクを貼り付け",
- "pasteFailed": "クリップボードを読み取れませんでした。入力欄に招待リンクを貼り付けてください。",
- "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。"
+ "invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。",
+ "managementIntro": "開始した共有と参加した共有を管理します。",
+ "manageSharing": "共有管理",
+ "joinedTab": "参加した共有",
+ "joinedEmptyTitle": "参加している共有タスクはありません",
+ "joinedEmptyHint": "仲間からの招待リンクを開いて共有タスクに参加できます。",
+ "ownedManageIntro": "このアカウントの別のパソコンで開始した共有も含みます。",
+ "retryAction": "再読み込み",
+ "cancelOperation": "キャンセル",
+ "leaveShort": "退出",
+ "returnToTasks": "タスク一覧に戻る",
+ "invitationDetected": "共有タスクへの招待が見つかりました",
+ "notNow": "今は参加しない",
+ "closeAllLabel": "すべての共有を停止",
+ "closeAllDescription": "すべてのゲストがアクセスできなくなります。タスクの履歴は保持されます。",
+ "joinedManageIntro": "退出するとこの共有にアクセスできなくなります。ホストや他のメンバーには影響しません。"
}
diff --git a/apps/mobile/src/i18n/locales/ko/sharedTask.json b/apps/mobile/src/i18n/locales/ko/sharedTask.json
index 10e169e46e..cb147ff6e6 100644
--- a/apps/mobile/src/i18n/locales/ko/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/ko/sharedTask.json
@@ -5,7 +5,7 @@
"login": "세션에 참가하려면 Cindy에 로그인하세요.",
"openTask": "세션 열기",
"notJoined": "이 공유 세션에 더 이상 접근할 수 없습니다.",
- "invitation": "초대 링크",
+ "invitation": "초대 링크 또는 초대 코드",
"invalid": "유효한 초대 링크 또는 초대 코드를 붙여넣으세요.",
"requestJoin": "참여",
"dismiss": "대화 상자 닫기",
@@ -32,7 +32,7 @@
"invitationCopied": "초대 링크를 복사했습니다",
"invitationCopyFailed": "초대 링크를 복사하지 못했습니다. 다시 시도하세요.",
"accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대를 요청하세요.",
- "joinIntro": "호스트의 초대 링크를 붙여넣으면 계정 이름으로 작업에 참여합니다.",
+ "joinIntro": "계정 이름으로 호스트의 공유 작업에 참여합니다.",
"invitationPlaceholder": "초대 링크 또는 초대 코드 붙여넣기",
"joinNotice": "참여하면 전체 기록을 보고 호스트의 승인을 기다리지 않고 Agent에게 메시지를 보낼 수 있습니다.",
"joinedTitle": "「{{title}}」에 참여했습니다",
@@ -68,8 +68,8 @@
"closeCurrent": "이 세션 공유 중지",
"sharingBadge": "공유 중",
"ownedIntro": "이 리전에서 내가 공유한 {{count}}개 세션",
- "ownedEmptyTitle": "공유 중인 세션이 없습니다",
- "ownedEmptyHint": "아무 세션이나 열고 \"세션 공유\"를 눌러 파트너를 초대하세요.",
+ "ownedEmptyTitle": "아직 시작한 공유가 없습니다",
+ "ownedEmptyHint": "작업을 열고 작업 메뉴에서 “작업 공유”를 선택하세요.",
"closeAll": "전체 공유 중지 ({{count}})",
"closeAllNote": "모두 중지하면 게스트는 접근할 수 없고 기존 초대는 만료됩니다. 세션 기록과 Agent 작업은 유지됩니다.",
"closeAllTitle": "전체 공유를 중지할까요?",
@@ -89,7 +89,20 @@
"hostOfflineBody": "이 세션의 공유는 종료되었고 초대는 만료되었습니다. 호스트에게 공유를 다시 시작하고 새 초대를 보내달라고 요청하세요.",
"closedToast": "{{count}}개 세션의 공유를 중지했습니다",
"closeFailedToast": "중지하지 못한 공유가 있습니다({{count}}건). 나중에 다시 시도할 수 있습니다.",
- "pasteInvitation": "초대 링크 붙여넣기",
- "pasteFailed": "클립보드를 읽지 못했습니다. 입력란에 초대 링크를 붙여넣으세요.",
- "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요."
+ "invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요.",
+ "managementIntro": "시작하거나 참여한 공유를 관리합니다.",
+ "manageSharing": "공유 관리",
+ "joinedTab": "참여한 공유",
+ "joinedEmptyTitle": "참여한 공유 작업이 없습니다",
+ "joinedEmptyHint": "동료가 보낸 초대 링크를 열어 공유 작업에 참여하세요.",
+ "ownedManageIntro": "이 계정의 다른 컴퓨터에서 시작한 공유도 포함합니다.",
+ "retryAction": "새로 고침",
+ "cancelOperation": "취소",
+ "leaveShort": "나가기",
+ "returnToTasks": "작업 목록으로 돌아가기",
+ "invitationDetected": "공유 작업 초대를 찾았습니다",
+ "notNow": "나중에",
+ "closeAllLabel": "모든 공유 중지",
+ "closeAllDescription": "모든 게스트의 접근이 차단됩니다. 작업 기록은 유지됩니다.",
+ "joinedManageIntro": "나가면 이 공유에 접근할 수 없습니다. 호스트와 다른 멤버에게는 영향이 없습니다."
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
index d388f68d28..889379a080 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
@@ -5,7 +5,7 @@
"login": "请登录 Cindy 后加入任务",
"openTask": "打开任务",
"notJoined": "你已无法访问此共享任务。",
- "invitation": "邀请链接",
+ "invitation": "邀请链接或邀请码",
"invalid": "请粘贴有效的邀请链接或邀请码",
"requestJoin": "加入",
"dismiss": "关闭窗口",
@@ -32,7 +32,7 @@
"invitationCopied": "邀请链接已复制",
"invitationCopyFailed": "未能复制邀请链接,请重试",
"accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新邀请。",
- "joinIntro": "粘贴房主发来的邀请链接,使用你的账号昵称加入任务。",
+ "joinIntro": "使用你的账号昵称加入房主邀请的任务。",
"invitationPlaceholder": "粘贴邀请链接或邀请码",
"joinNotice": "加入后可查看全部历史,并直接向 Agent 发消息,无需等待房主审批。",
"joinedTitle": "已加入「{{title}}」",
@@ -68,8 +68,8 @@
"closeCurrent": "关闭此任务的共享",
"sharingBadge": "共享中",
"ownedIntro": "当前账号在此区域发起的 {{count}} 个共享任务",
- "ownedEmptyTitle": "没有正在共享的任务",
- "ownedEmptyHint": "回到任意任务,点击「共享任务」邀请伙伴。",
+ "ownedEmptyTitle": "还没有发起共享",
+ "ownedEmptyHint": "打开一个任务,在任务菜单中选择“共享任务”。",
"closeAll": "关闭全部共享({{count}})",
"closeAllNote": "全部关闭后,访客无法继续访问,原邀请失效。任务记录和 Agent 工作会保留。",
"closeAllTitle": "关闭全部共享?",
@@ -89,7 +89,20 @@
"hostOfflineBody": "这个任务的共享已关闭,原邀请已失效。请联系房主重新开启共享并发送新邀请。",
"closedToast": "已关闭 {{count}} 个任务的共享",
"closeFailedToast": "部分共享未能关闭({{count}} 项),可稍后重试。",
- "pasteInvitation": "粘贴邀请链接",
- "pasteFailed": "未能读取剪贴板,请在输入框中粘贴邀请链接",
- "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接"
+ "invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接",
+ "managementIntro": "管理你发起和加入的共享。",
+ "manageSharing": "共享管理",
+ "joinedTab": "我加入的",
+ "joinedEmptyTitle": "还没有加入共享",
+ "joinedEmptyHint": "打开伙伴发来的邀请链接,即可加入共享任务。",
+ "ownedManageIntro": "包含这个账号在其他电脑上发起的共享。",
+ "retryAction": "重新加载",
+ "cancelOperation": "取消",
+ "leaveShort": "退出",
+ "returnToTasks": "返回任务列表",
+ "invitationDetected": "发现共享任务邀请",
+ "notNow": "暂不加入",
+ "closeAllLabel": "取消全部共享",
+ "closeAllDescription": "所有访客将无法继续访问,任务记录保留。",
+ "joinedManageIntro": "退出后将无法继续访问该共享;房主和其他成员不受影响。"
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
index 2f4e8e9d0e..29f50014b3 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
@@ -5,7 +5,7 @@
"login": "請登入 Cindy 後加入任務",
"openTask": "開啟任務",
"notJoined": "你已無法存取此共享任務。",
- "invitation": "邀請連結",
+ "invitation": "邀請連結或邀請碼",
"invalid": "請貼上有效的邀請連結或邀請碼",
"requestJoin": "加入",
"dismiss": "關閉視窗",
@@ -32,7 +32,7 @@
"invitationCopied": "邀請連結已複製",
"invitationCopyFailed": "無法複製邀請連結,請重試",
"accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新邀請。",
- "joinIntro": "貼上房主傳來的邀請連結,使用你的帳號暱稱加入任務。",
+ "joinIntro": "使用你的帳號暱稱加入房主邀請的任務。",
"invitationPlaceholder": "貼上邀請連結或邀請碼",
"joinNotice": "加入後可查看全部歷史,並直接向 Agent 傳送訊息,無需等待房主審批。",
"joinedTitle": "已加入「{{title}}」",
@@ -68,8 +68,8 @@
"closeCurrent": "關閉此任務的共享",
"sharingBadge": "共享中",
"ownedIntro": "目前帳號在此區域發起的 {{count}} 個共享任務",
- "ownedEmptyTitle": "沒有正在共享的任務",
- "ownedEmptyHint": "回到任意任務,點擊「共享任務」邀請夥伴。",
+ "ownedEmptyTitle": "還沒有發起共享",
+ "ownedEmptyHint": "開啟一個任務,在任務選單中選擇「共享任務」。",
"closeAll": "關閉全部共享({{count}})",
"closeAllNote": "全部關閉後,訪客無法繼續存取,原邀請失效。任務記錄和 Agent 工作會保留。",
"closeAllTitle": "關閉全部共享?",
@@ -89,7 +89,20 @@
"hostOfflineBody": "這個任務的共享已關閉,原邀請已失效。請聯絡房主重新開啟共享並傳送新邀請。",
"closedToast": "已關閉 {{count}} 個任務的共享",
"closeFailedToast": "部分共享未能關閉({{count}} 項),可稍後重試。",
- "pasteInvitation": "貼上邀請連結",
- "pasteFailed": "無法讀取剪貼簿,請在輸入欄位中貼上邀請連結",
- "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結"
+ "invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結",
+ "managementIntro": "管理你發起和加入的共享。",
+ "manageSharing": "共享管理",
+ "joinedTab": "我加入的",
+ "joinedEmptyTitle": "還沒有加入共享",
+ "joinedEmptyHint": "開啟夥伴傳來的邀請連結,即可加入共享任務。",
+ "ownedManageIntro": "包含這個帳號在其他電腦上發起的共享。",
+ "retryAction": "重新載入",
+ "cancelOperation": "取消",
+ "leaveShort": "退出",
+ "returnToTasks": "返回任務清單",
+ "invitationDetected": "發現共享任務邀請",
+ "notNow": "暫不加入",
+ "closeAllLabel": "取消全部共享",
+ "closeAllDescription": "所有訪客將無法繼續存取,任務記錄保留。",
+ "joinedManageIntro": "退出後將無法繼續存取此共享;房主和其他成員不受影響。"
}
diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsx
index b24d3c449d..05128e85a5 100644
--- a/apps/mobile/src/session/HomeChromeDrawer.tsx
+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx
@@ -66,7 +66,6 @@ export function HomeChromeDrawer({
onOpenSearch,
onOpenAccounts,
onOpenDevices,
- onOpenSharedSession,
onOpenSettings,
onLogout,
loggingOut = false,
@@ -82,7 +81,6 @@ export function HomeChromeDrawer({
onOpenSearch(): void;
onOpenAccounts(): void;
onOpenDevices(): void;
- onOpenSharedSession?(): void;
onOpenSettings(): void;
onLogout(): void;
loggingOut?: boolean;
@@ -344,16 +342,6 @@ export function HomeChromeDrawer({
<Text numberOfLines={1} style={styles.menuLabel}>{t('devices.management.title')}</Text>
</Pressable>
- {onOpenSharedSession && <Pressable
- accessibilityLabel={t('sharedTask.join')}
- accessibilityRole="button"
- onPress={onOpenSharedSession}
- style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
- >
- <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text numberOfLines={1} style={styles.menuLabel}>{t('sharedTask.join')}</Text>
- </Pressable>}
-
<Pressable
accessibilityLabel={t("devices.list.a11y.openSettings")}
accessibilityRole="button"
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 854201af80..5e05a13670 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -3025,12 +3025,6 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newS
setChromeMenuCloseInstant(true);
setChromeMenuOpen(false);
}}
- onOpenSharedSession={() => {
- pendingMenuActionRef.current = null;
- guardedPush('/shared-session');
- setChromeMenuCloseInstant(true);
- setChromeMenuOpen(false);
- }}
onLogout={() => void logout()}
open={chromeMenuOpen}
user={user}
diff --git a/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx
new file mode 100644
index 0000000000..ed9becc164
--- /dev/null
+++ b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx
@@ -0,0 +1,28 @@
+import type { ReactNode } from 'react';
+import { KeyboardAvoidingView, Modal, Platform, ScrollView, StyleSheet, View } from 'react-native';
+import { Text } from '@/components/AppText';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+
+/** Compact invitation form; the management page stays mounted behind it. */
+export function SharedTaskAdmissionDialog({ title, onClose, children }: {
+ title: string; onClose(): void; children: ReactNode;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ return <Modal transparent visible animationType="fade" onRequestClose={onClose}>
+ <KeyboardAvoidingView style={styles.backdrop} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
+ <View style={styles.card} accessibilityViewIsModal testID="sharedTask.admissionDialog">
+ <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content} bounces={false}>
+ <Text style={styles.title} accessibilityRole="header">{title}</Text>
+ {children}
+ </ScrollView>
+ </View>
+ </KeyboardAvoidingView>
+ </Modal>;
+}
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ backdrop: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.xl, backgroundColor: colors.overlay },
+ card: { width: '100%', maxWidth: 440, maxHeight: '85%', borderRadius: radius.container, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, backgroundColor: colors.surfaceElevated },
+ content: { padding: spacing.lg },
+ title: { fontSize: typeScale.title, lineHeight: lineHeight.title, fontWeight: fontWeight.semibold, color: colors.textPrimary, marginBottom: spacing.lg },
+});
diff --git a/apps/mobile/src/session/SharedTaskEndedState.tsx b/apps/mobile/src/session/SharedTaskEndedState.tsx
index 19d39481ed..e65195f062 100644
--- a/apps/mobile/src/session/SharedTaskEndedState.tsx
+++ b/apps/mobile/src/session/SharedTaskEndedState.tsx
@@ -7,7 +7,7 @@ import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
/** Membership loss has a recovery action, without claiming an unverified offline cause. */
-export function SharedTaskEndedState({ onRejoin }: { onRejoin(): void }) {
+export function SharedTaskEndedState({ onReturnToTasks }: { onReturnToTasks(): void }) {
const { t } = useTranslation();
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
@@ -15,7 +15,7 @@ export function SharedTaskEndedState({ onRejoin }: { onRejoin(): void }) {
<View style={styles.icon}><Square size={iconSize.md} color={colors.textTertiary} /></View>
<Text style={styles.title}>{t('sharedTask.ended')}</Text>
<Text style={styles.text}>{t('sharedTask.accessEndedBody')}</Text>
- <SharedTaskAction action={{ label: t('sharedTask.rejoin'), tone: 'primary', onPress: onRejoin }} />
+ <SharedTaskAction action={{ label: t('sharedTask.returnToTasks'), tone: 'primary', onPress: onReturnToTasks }} />
</View>;
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
diff --git a/apps/mobile/src/session/SharedTaskScreen.tsx b/apps/mobile/src/session/SharedTaskScreen.tsx
index d8867dd9e1..a61d9d3bed 100644
--- a/apps/mobile/src/session/SharedTaskScreen.tsx
+++ b/apps/mobile/src/session/SharedTaskScreen.tsx
@@ -1,20 +1,29 @@
import { type ReactNode, type Ref } from 'react';
-import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, type View } from 'react-native';
+import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
import { SafeAreaView } from 'react-native-safe-area-context';
-import { MainWindowActionButton, type MainWindowAction } from '@/components/MobilePrimitives';
+import { MainWindowActionButton, ScreenBackButton, type MainWindowAction } from '@/components/MobilePrimitives';
+import { Text } from '@/components/AppText';
import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';
import { useThemedStyles, type ThemeColors } from '@/theme';
-import { fontWeight, lineHeight, spacing, typeScale } from '@/theme/tokens';
+import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
/** Full-screen management; confirmations stay compact, with native material on iOS. */
-export function SharedTaskScreen({ title, onClose, children }: {
- title: string; onClose(): void; children: ReactNode;
+export function SharedTaskScreen({ title, onClose, children, management = false }: {
+ title: string; onClose(): void; children: ReactNode; management?: boolean;
}) {
+ const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>
- <SimpleStackHeader title={title} onBack={onClose} />
+ {(!management || Platform.OS === 'ios') && <SimpleStackHeader title={management ? t('settings.title') : title} onBack={onClose} />}
<KeyboardAvoidingView style={styles.body} enabled={Platform.OS === 'ios'} behavior="padding">
- <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">{children}</ScrollView>
+ <ScrollView contentContainerStyle={[styles.content, management && styles.managementContent]} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">
+ {management && Platform.OS !== 'ios' && <View style={styles.managementNavigation}>
+ <ScreenBackButton onPress={onClose} style={styles.managementBack} testID="sharedTask.backToSettings" />
+ <Text style={styles.navigationLabel}>{t('settings.title')}</Text>
+ </View>}
+ {children}
+ </ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>;
}
@@ -28,6 +37,10 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
root: { flex: 1, backgroundColor: colors.surface },
body: { flex: 1 },
content: { padding: spacing.lg },
+ managementContent: { paddingHorizontal: spacing.lg + spacing.xs, paddingTop: 0, paddingBottom: spacing.xxl },
+ managementNavigation: { height: 48, flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginLeft: -spacing.sm, marginBottom: spacing.xl },
+ managementBack: { width: 44, height: 44, marginLeft: 0, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.pill },
+ navigationLabel: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
action: { minHeight: 44, paddingHorizontal: spacing.lg },
actionText: { fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular },
compactActionText: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular },
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 1f8a2015bd..ce8641e17f 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -12,7 +12,7 @@
## 用户流程
1. 房主在任务内点击“共享任务”,开启共享并复制邀请链接。
-2. 访客点击链接,通过网页唤起已安装的客户端;登录后直接加入并进入任务。也可在菜单“加入共享任务”粘贴链接或旧邀请码,无申请或批准步骤。
+2. 访客点击链接,通过网页唤起已安装的客户端;登录后直接加入并进入任务。桌面也可在“加入共享任务”中粘贴链接或旧邀请码。移动端启动或回到前台时自动识别剪贴板邀请链接,打开加入页面供用户确认,无申请或批准步骤。
3. 双方进入现有任务页面,查看全部历史、工具结果、上下文和附件,向同一个 Agent 发消息。
4. 房主可复制新邀请、移除访客、停止共享;访客可退出。
@@ -26,7 +26,10 @@
- 链接默认唤起 Cindy;发起客户端按自身构建身份在 fragment 追加 `?app=cindycn` 或 `?app=cindydev`,网页据此选择移动端已有 Scheme,不让用户选择版本。
- 客户端只向当前配置的服务提交邀请。链接中的 `server` 仅用于比较,不能覆盖请求目标;不同服务的邀请显示对应提示。仍接受旧的裸邀请码,REST 和 device-link 既有入参保持兼容。
- 访客加入时直接使用已登录用户的账号昵称,不再要求填写自定义昵称。昵称只作为展示信息,成员身份仍由服务端的账号与成员关系决定。
-- 移动端由用户主动点击粘贴入口读取剪贴板;iOS 可用时采用系统粘贴控件,不在启动或回前台时静默读取。收到的邀请只在内存中暂存,支持首次登录后继续,切换账号、关闭页面或过期后不自动沿用。
+- 移动端登录后在启动或从后台回到前台时自动读取剪贴板,只识别当前服务的有效邀请链接,普通内容与裸邀请码不触发跳转。同一链接在本次运行中不重复弹出,剪贴板结果不覆盖已打开的加入页面或更新的链接唤起;系统粘贴权限提示引起的短暂失焦不重复读取。菜单不暴露“加入共享任务”入口,页面也不提供独立粘贴按钮。自动识别只打开加入页面,由用户点击加入;显式点击邀请链接继续直接加入并进入任务。
+- 邀请与去重信息只在内存中暂存,不持久化剪贴板内容;链接邀请支持首次登录后继续,切换账号、关闭页面或过期后不自动沿用。系统拒绝剪贴板访问时保持当前页面可用,邀请链接唤起仍可使用。
+- 两端“设置 → 共享任务”提供独立管理页,分为“我发起的 / 我加入的”,有共享和空状态均保留“加入共享任务”次要按钮。手动加入使用紧凑弹框,接受邀请链接和旧裸邀请码;旧裸邀请码不进入自动识别。2026-09-28 用户已确认交互 HTML 并授权实现:Desktop 设置项位于远程控制之后;Mobile 沿用实际设置分组,在语音词典与外观之间增加“共享任务 → 共享管理”。顶部、主菜单和移动端首页共享分组不提供加入入口;桌面端侧栏“共享任务”分组右侧保留“+”加入入口(2026-09-28 用户确认)。
+- 自动识别邀请展示账号与加入确认,不暴露长链接或邀请输入框;手动加入和显式链接成功后进入任务。共享结束提示返回任务列表,并说明重新加入需要房主的新邀请。管理页的移除、退出、关闭当前、关闭全部使用紧凑确认;取消保留原页面、页签和滚动位置。加载失败提供重试,不当作空列表;关闭或退出成功回到对应管理列表。
- 本阶段不修改移动端原生配置或 runtime fingerprint;Universal Links / Android App Links 另行实施。先部署服务端页面,再发布客户端;旧客户端尚不能解析新链接,需更新。
## 权限与顺序
@@ -236,3 +239,10 @@
- 最后一轮未发现剩余确认的 P0/P1;最终生命周期与 dispatch 定向回归 51 项通过,Desktop/Mobile 类型检查与 device-link TypeScript 检查通过。
- 源码冻结后重新执行根目录 `pnpm test:unit:related`,退出码 0:Desktop、Mobile、device-link、lizi-mcps、maker-core、maker-shared、orca-workflow 均通过;测试调度器 534 项通过、8 项按条件跳过。
- 本次增补的实机登出测试未完成:隔离启动命令的最终检查报 `STARTUP_FAILED / Invalid array length`,定位到已有 `desktop-whoami` 进程子树遍历。未用模拟界面代替实机截图,也不将此轮自动化回归记为 UI 验收。
+
+### 设置共享管理 UI 验收(2026-09-28)
+
+- 按用户确认稿修正 Android 管理页:返回设置、大标题与右侧加入按钮、下划线页签、带内部分隔线的列表、列表下方说明和取消全部共享区;入口位于语音词典与外观之间。
+- CN Android 模拟器连接 dev 服务,使用真实跨账号共享验证:手动输入旧邀请码后直接进入任务;成员使用账号昵称;取消退出保留原页签;房主取消共享后显示结束态,返回任务列表。
+- 已目检浅色、深色的真实“我加入的”列表与浅色空状态;此模拟器账号无自己发起的共享,有内容的“我发起的”列表和 iOS 未实机目检,不能以组件测试替代。
+- Mobile 全量单测 7,525 项通过、11 项按条件跳过;后续空状态调整的定向回归 37 项通过。Desktop、Mobile 类型检查、i18n key 一致性和术语检查通过。测试共享已取消,原有其他共享保留。