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(mobile): 补齐伙伴与跨电脑远程控制 (#3912)

Chris Zhang96e1202e7319
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0a0401aced..2a3d1ac33a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -143,6 +143,11 @@ jobs:
# 通过 pnpm 启动 runner,保留当前 pnpm 入口与 workspace 解析语义。
run: pnpm exec node scripts/test-workspaces.mjs --tier unit
+ # localDb suites are outside the unit tier; exercise these DB boundaries on both OSes.
+ - name: Run companion database regressions
+ if: matrix.shard == 1
+ run: pnpm --filter desktop exec vitest run src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
+
# 保留原 required check 名 verify;检查 job 或任一 Linux 分片失败、取消都阻断。
verify:
name: verify
@@ -203,6 +208,11 @@ jobs:
- name: Run client and package unit tests
run: pnpm test:unit
+ # localDb suites are outside the unit tier; exercise these DB boundaries on both OSes.
+ - name: Run companion database regressions
+ if: matrix.shard == 1
+ run: pnpm --filter desktop exec vitest run src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
+
# 保留稳定的必需检查名,并确保任一分片失败或取消都会阻断汇总门禁。
windows-unit:
name: Windows unit tests
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index 6c47825a05..0654a72309 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -663,6 +663,38 @@ describe('remote companion Session visibility at the device-link boundary', () =
expect(handler).not.toHaveBeenCalled();
});
+ it.each(['hidden', 'missing'] as const)('rejects a private thread when the viewer Bot is %s, using Bot identity rather than the opaque thread ID', async (access) => {
+ const handler = vi.fn(() => ({ ok: true, thread: { messages: [{ content: 'private' }] } }));
+ registry.register('maker:bot-direct-message-thread:get', handler);
+ const lookup = vi.fn(async (id: string, kind?: 'session' | 'bot') =>
+ kind === 'bot' && id === 'viewer-bot' ? access : 'ordinary' as const);
+ setRemoteBotSessionLookup(lookup);
+ expect(await runInvoke('ctrl-1', { channel: 'maker:bot-direct-message-thread:get', args: ['opaque-thread', 'viewer-bot'] }))
+ .toMatchObject({ ok: false, error: { message: expect.stringContaining('[NOT_FOUND]') } });
+ expect(handler).not.toHaveBeenCalled();
+ expect(lookup).toHaveBeenCalledWith('viewer-bot', 'bot');
+ });
+
+ it('allows a visible private-thread viewer and rechecks that viewer before cached delivery', async () => {
+ let hidden = false;
+ setRemoteBotSessionLookup(async (id, kind) => kind === 'bot' && id === 'viewer-bot'
+ ? hidden ? 'hidden' : 'visible' : 'ordinary');
+ const handler = vi.fn(() => ({ ok: true, thread: { id: 'opaque-thread', messages: [{ content: 'private' }] } }));
+ registry.register('maker:bot-direct-message-thread:get', handler);
+ const client = mkClient();
+ wireInboundDispatch(client as never);
+ const frame = client.onFrame.mock.calls[0][0];
+ const request = { v: PROTOCOL_VERSION, kind: 'invoke', src: 'ctrl-1', id: 'cached-thread', payload: { channel: 'maker:bot-direct-message-thread:get', args: ['opaque-thread', 'viewer-bot'] } };
+ frame(request);
+ await vi.waitFor(() => expect(client.sendInvokeResult).toHaveBeenCalledTimes(1));
+ expect(client.sendInvokeResult.mock.calls[0][2]).toMatchObject({ ok: true, result: { ok: true } });
+ hidden = true;
+ frame(request);
+ await vi.waitFor(() => expect(client.sendInvokeResult).toHaveBeenCalledTimes(2));
+ expect(client.sendInvokeResult.mock.calls[1][2]).toMatchObject({ ok: false, error: { message: expect.stringContaining('[NOT_FOUND]') } });
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
it('rechecks visibility after an in-flight read and filters active task discovery', async () => {
let hidden = false;
setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index 5920fb5ecd..dc48237f00 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -15,9 +15,19 @@ function sessionIds(value: unknown): string[] {
.filter((id): id is string => typeof id === 'string' && id.length > 0);
}
-/** The first positional ID and explicit Session fields are checked against the host DB. */
+/** Resolve channel-specific Bot IDs before checking generic Session references. */
export async function assertRemoteBotInvocationAllowed(args: unknown[], channel = ''): Promise<void> {
if (!lookup) return;
+ if (channel === 'maker:bot-direct-message-thread:get') {
+ // The first argument is an opaque thread ID, not a Session. The local service
+ // still checks membership; remote access additionally requires a visible viewer.
+ // Dispatch calls this again for in-flight, cached and queued reply delivery.
+ const viewerBotId = args[1];
+ if (typeof viewerBotId !== 'string' || await lookup(viewerBotId, 'bot') !== 'visible') {
+ throw new Error('[NOT_FOUND] Resource does not exist');
+ }
+ return;
+ }
const ids = new Set(args.flatMap((arg, index) => [
...(index === 0 && typeof arg === 'string' ? [arg] : []), ...sessionIds(arg),
]));
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 2d7d8730e1..5dca3db23f 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -2133,6 +2133,20 @@ describe('Bots list unread projection', () => {
return rows.find((row) => row.id === botId)!.unreadCount;
}
+ it('remote reply watermark ignores user activity and private timeline traces', async () => {
+ const sessionId = await canonicalFor('bot-1');
+ insertMessage(sessionId, { id: 'reply', role: 'assistant', content: 'Visible result', createdAt: 1000 });
+ insertMessage(sessionId, { id: 'user', role: 'user', content: 'Another question', createdAt: 2000 });
+ insertMessage(sessionId, { id: 'private', role: 'assistant', content: 'Private result', createdAt: 3000, agentMeta: { botPrivateReply: true } });
+ insertMessage(sessionId, { id: 'trace', role: 'assistant', content: 'Private trace', createdAt: 4000, agentMeta: { botDirectMessage: { v: 1 } } });
+ insertMessage(sessionId, { id: 'rewound', role: 'assistant', content: 'Rewound', createdAt: 5000, rewindAt: 6000 });
+ const remote = await getBotRemoteResourceSource('bot-1');
+ expect(remote.lastReplyAt).toBe(1000);
+ expect(remote.lastMessagePreview).toBe('Another question');
+ h.sqlite!.prepare('UPDATE sessions SET cleared_at = 6000 WHERE id = ?').run(sessionId);
+ expect((await getBotRemoteResourceSource('bot-1')).lastReplyAt).toBe(0);
+ });
+
it('counts only replies that landed after the read position', async () => {
const sessionId = await canonicalFor('bot-1');
insertMessage(sessionId, {
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProjection.ts b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProjection.ts
index 5ce73bae84..a77db4643c 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProjection.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProjection.ts
@@ -83,6 +83,7 @@ function sourceRevision(source: BotRemoteResourceSource): string {
source.currentVersion,
source.updatedAt,
source.lastMessageAt ?? 0,
+ source.lastReplyAt ?? 0,
source.hiddenAt ?? 0,
source.pinnedAt ?? 0,
source.activityAt,
@@ -102,6 +103,7 @@ export function botRemoteCollectionItemFromSource(
ref: resourceRef(source.id),
display: {
title: source.name,
+ lastReplyAt: source.lastReplyAt ?? 0,
...(source.description ? { subtitle: source.description } : {}),
...(source.lastMessagePreview ? { preview: source.lastMessagePreview } : {}),
...(source.activityAt ? { timestamp: source.activityAt } : {}),
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 4a252167d9..e5fd37961c 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -384,6 +384,7 @@ async function readCanonicalChatPreview(
db: ReturnType<typeof getDbClient>['drizzle'],
canonicalSessionId: string | null,
clearedAt: number | null,
+ repliesOnly = false,
): Promise<{ preview: string | null; createdAt: number | null; role: BotChatRole | null }> {
if (!canonicalSessionId) return { preview: null, createdAt: null, role: null };
const rows = await db
@@ -396,9 +397,11 @@ async function readCanonicalChatPreview(
.where(
and(
eq(messages.sessionId, canonicalSessionId),
- inArray(messages.role, ['user', 'assistant']),
+ repliesOnly ? eq(messages.role, 'assistant') : inArray(messages.role, ['user', 'assistant']),
isNull(messages.rewindAt),
sql`(${messages.agentMeta} IS NULL OR json_extract(${messages.agentMeta}, '$.autoResume') IS NOT 1)`,
+ sql`(${messages.agentMeta} IS NULL OR json_type(${messages.agentMeta}, '$.botDirectMessage') IS NULL)`,
+ sql`(${messages.agentMeta} IS NULL OR json_extract(${messages.agentMeta}, '$.botPrivateReply') IS NOT 1)`,
...(clearedAt !== null ? [gt(messages.createdAt, clearedAt)] : []),
),
)
@@ -698,6 +701,7 @@ export interface BotRemoteResourceSource {
lastMessagePreview: string | null;
lastMessageAt: number | null;
lastMessageRole: BotChatRole | null;
+ lastReplyAt?: number;
needsAttention: boolean;
hiddenAt: number | null;
pinnedAt: number | null;
@@ -720,6 +724,7 @@ async function readBotRemoteResourceSource(
.select({ clearedAt: sessions.clearedAt, updatedAt: sessions.updatedAt })
.from(sessions).where(eq(sessions.id, canonicalSessionId)).limit(1) : [];
const latest = await readCanonicalChatPreview(db, canonicalSessionId, canonical?.clearedAt ?? null);
+ const reply = latest.role === 'assistant' ? latest : await readCanonicalChatPreview(db, canonicalSessionId, canonical?.clearedAt ?? null, true);
owner.assertCurrent();
return {
id: profile.id,
@@ -732,6 +737,7 @@ async function readBotRemoteResourceSource(
lastMessagePreview: latest.preview,
lastMessageAt: latest.createdAt,
lastMessageRole: latest.role,
+ lastReplyAt: reply.createdAt ?? 0,
needsAttention: profile.attentionAt !== null &&
BOT_FAILURE_REASONS.includes(profile.attentionReason as BotFailureReason) &&
isBotFailureAttentionWorthy(profile.attentionReason as BotFailureReason),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts
new file mode 100644
index 0000000000..83d665e952
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts
@@ -0,0 +1,28 @@
+import { expect, it } from 'vitest';
+import { REMOTE_INVOKE_ALLOWLIST, PUSH_FORWARD_ALLOWLIST } from '@cindy/device-link';
+import type { BotDelegationListResult } from '../../../shared/botDelegation';
+import { projectRemoteBotDelegations } from '../remoteBotDelegations';
+it('exports task controls while keeping profile mutations local', () => {
+ for (const channel of ['maker:bot-delegations:list', 'maker:bot-delegation:cancel', 'maker:bot-direct-message-thread:get']) expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);
+ expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:bots:update')).toBe(false);
+ expect(PUSH_FORWARD_ALLOWLIST.has('maker:bot-delegation:changed')).toBe(true);
+ expect(PUSH_FORWARD_ALLOWLIST.has('maker:bot-direct-message:changed')).toBe(true);
+});
+it('returns useful task results without leaking database or frozen runtime fields', () => {
+ const artifacts = [
+ { path: 'report.md', absolutePath: '/Users/owner/work/report.md', status: 'added' },
+ { path: 'chart.svg', absolutePath: 'C:\\Users\\owner\\work\\chart.svg', status: 'modified' },
+ ];
+ const input = { ok: true, delegations: [{ id: 'task', title: 'Report', status: 'completed', resultSummary: 'Done', artifacts, pendingInteraction: null, permissionSnapshotJson: 'private', permissionSnapshot: { identity: 'private' }, contextRefs: ['private'], runtimeSnapshotJson: 'private' }] } as unknown as BotDelegationListResult;
+ const result = projectRemoteBotDelegations(input);
+ expect(result).toMatchObject({ ok: true, delegations: [{ id: 'task', resultSummary: 'Done', permissionSnapshot: {}, contextRefs: [] }] });
+ if (!result.ok) throw new Error('expected successful projection');
+ expect(result.delegations[0].artifacts).toEqual([
+ { path: 'report.md', status: 'added' }, { path: 'chart.svg', status: 'modified' },
+ ]);
+ expect(JSON.stringify(result)).not.toContain('absolutePath');
+ for (const artifact of artifacts) expect(JSON.stringify(result)).not.toContain(JSON.stringify(artifact.absolutePath).slice(1, -1));
+ if (!input.ok) throw new Error('expected successful input');
+ expect(input.delegations[0].artifacts[0].absolutePath).toBe('/Users/owner/work/report.md');
+ expect(JSON.stringify(result)).not.toContain('private');
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 86f1f90b0f..c65fa4b24f 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,3 +1,4 @@
+import { projectRemoteBotDelegations } from './remoteBotDelegations.js';
/**
* registerMakerIpc — 把 Maker Core 的能力暴露为 maker:* IPC channel。
*
@@ -9053,17 +9054,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ipcMain.handle(
MAKER_INVOKE.BOT_DELEGATIONS_LIST,
async (event, parentSessionId: unknown) => {
- assertTrustedAppRendererEvent(event);
- if (typeof parentSessionId !== 'string' || parentSessionId.length === 0) {
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
+ if (typeof parentSessionId !== 'string' || (parentSessionId.length === 0 || parentSessionId.length > 128)) {
throwIpcError('INVALID_PARAMS', 'parentSessionId required');
}
- return delegationForRestore.listDelegations(parentSessionId);
+ const result = await delegationForRestore.listDelegations(parentSessionId);
+ return isDeviceLinkInvoke() ? projectRemoteBotDelegations(result) : result;
},
);
ipcMain.handle(
MAKER_INVOKE.BOT_DIRECT_MESSAGE_THREAD_GET,
async (event, threadId: unknown, viewerBotId: unknown) => {
- assertTrustedAppRendererEvent(event);
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
if (typeof threadId !== 'string' || !threadId || threadId.length > 128) {
throwIpcError('INVALID_PARAMS', 'threadId required');
}
@@ -9079,12 +9081,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ipcMain.handle(
MAKER_INVOKE.BOT_DELEGATION_CANCEL,
async (event, parentSessionId: unknown, delegationId: unknown) => {
- assertTrustedAppRendererEvent(event);
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
if (
typeof parentSessionId !== 'string'
- || parentSessionId.length === 0
+ || (parentSessionId.length === 0 || parentSessionId.length > 128)
|| typeof delegationId !== 'string'
- || delegationId.length === 0
+ || (delegationId.length === 0 || delegationId.length > 128)
) {
throwIpcError('INVALID_PARAMS', 'parentSessionId + delegationId required');
}
diff --git a/apps/desktop/src/main/maker-ipc/remoteBotDelegations.ts b/apps/desktop/src/main/maker-ipc/remoteBotDelegations.ts
new file mode 100644
index 0000000000..416e11297c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/remoteBotDelegations.ts
@@ -0,0 +1,20 @@
+import type { BotDelegationListResult } from '../../shared/botDelegation.js';
+
+/** Only the task-card view crosses device-link, never a database/runtime snapshot. */
+export function projectRemoteBotDelegations(result: BotDelegationListResult): BotDelegationListResult {
+ if (!result.ok) return result;
+ return { ok: true, delegations: result.delegations.map((row) => ({
+ id: row.id, requestingBotId: row.requestingBotId, targetBotId: row.targetBotId,
+ targetBotName: row.targetBotName, parentSessionId: row.parentSessionId,
+ childSessionId: row.childSessionId, title: row.title, objective: row.objective,
+ status: row.status, resultSummary: row.resultSummary, lastError: row.lastError,
+ createdAt: row.createdAt, acceptedAt: row.acceptedAt, completedAt: row.completedAt,
+ updatedAt: row.updatedAt, depth: row.depth, targetProfileVersion: row.targetProfileVersion,
+ contextRefs: [], lineage: [], permissionSnapshot: {},
+ pendingInteraction: row.pendingInteraction ? {
+ requestId: row.pendingInteraction.requestId, kind: row.pendingInteraction.kind,
+ summary: row.pendingInteraction.summary, raisedAt: row.pendingInteraction.raisedAt,
+ } : null,
+ artifacts: row.artifacts.map(({ path, status }) => ({ path, status })),
+ })) };
+}
diff --git a/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
index f89f4d566b..9943a1998e 100644
--- a/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
@@ -29,6 +29,9 @@ vi.mock('react-i18next', () => ({
}),
}));
+// These fixtures render other SystemCard variants; companion synchronization is tested separately.
+vi.mock('@/features/bots/useRemoteBots', () => ({ useRemoteBots: () => [] }));
+
vi.mock('@/features/learn/LearnStatusCard', () => ({
LearnStatusCard: () => null,
}));
diff --git a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
index 746b2c7b91..3ec018b244 100644
--- a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
@@ -12,6 +12,9 @@ vi.mock('react-i18next', () => ({
}),
}));
+// These fixtures render other SystemCard variants; companion synchronization is tested separately.
+vi.mock('@/features/bots/useRemoteBots', () => ({ useRemoteBots: () => [] }));
+
vi.mock('@/features/learn/LearnStatusCard', () => ({
LearnStatusCard: () => null,
}));
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 8aee278dcf..00b5b671b0 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1339,7 +1339,7 @@ export function SystemCard({
case 'bot-session-task':
return <BotSessionTaskCard data={data} sessionId={sessionId} />;
case 'bot-direct-message':
- return <BotDirectMessageCard data={data} />;
+ return <BotDirectMessageCard data={data} sessionId={sessionId} />;
default:
return null;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
index 8a06e1afae..c7304a5c29 100644
--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx
@@ -4,6 +4,9 @@ import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import type { BotCollaborationMeta } from '../../../shared/botCollaboration';
+import { makerApiForSticky } from '@/lib/makerTransport';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { useRemoteBots } from './useRemoteBots';
import { cn } from '@/lib/utils';
import { readBotCollaborationMeta } from '../../../shared/botCollaboration';
import { isActiveDelegationStatus, useBotDelegation } from './botDelegationLive';
@@ -79,7 +82,10 @@ function SessionTaskCardBody({
}) {
const { t } = useTranslation();
const navigate = useNavigate();
- const parentSessionId = meta.parentSessionId ?? sessionId ?? null;
+ const parentSessionId = sessionId ?? meta.parentSessionId ?? null;
+ const [sourceDeviceId] = useState(() => parentSessionId ? remoteProjectsStore.getSessionDeviceId(parentSessionId) : undefined);
+ const remoteBots = useRemoteBots();
+ const online = !sourceDeviceId || remoteBots.some((bot) => bot.deviceId === sourceDeviceId && bot.online);
const { row, resolved } = useBotDelegation(parentSessionId, meta.delegationId);
const [pending, setPending] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
@@ -98,6 +104,13 @@ function SessionTaskCardBody({
const openChildTask = (): void => {
if (!childSessionId) return;
+ const deviceId = sourceDeviceId;
+ const existingOrigin = remoteProjectsStore.getSessionDeviceId(childSessionId);
+ if (deviceId && existingOrigin && existingOrigin !== deviceId) {
+ setActionError(t('bots.collab.actionFailed'));
+ return;
+ }
+ if (deviceId) remoteProjectsStore.pinSessionOrigin(deviceId, childSessionId);
navigate(`/cc-agent/${encodeURIComponent(childSessionId)}`);
};
@@ -205,7 +218,7 @@ function SessionTaskCardBody({
{artifacts.length > 0 ? (
<ul className="mt-2 space-y-1 text-11 text-[var(--text-tertiary)]">
{artifacts.map((artifact) => (
- <li key={`${artifact.status}:${artifact.absolutePath}`} className="truncate">
+ <li key={`${artifact.status}:${artifact.path}`} className="truncate">
{artifact.path}
</li>
))}
@@ -216,11 +229,11 @@ function SessionTaskCardBody({
{active ? (
<button
type="button"
- disabled={pending || !parentSessionId}
+ disabled={pending || !parentSessionId || !online}
onClick={() => {
- if (!parentSessionId) return;
+ if (!parentSessionId || !online || pending) return;
void runAction(async () =>
- window.electronAPI.maker.cancelBotDelegation(parentSessionId, meta.delegationId),
+ makerApiForSticky(parentSessionId).cancelBotDelegation(parentSessionId, meta.delegationId),
);
}}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-default)] px-2.5 py-1 text-11 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] disabled:opacity-50"
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
index a45b8cb02e..633ce7c15d 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
@@ -1,24 +1,27 @@
-import { useMemo } from 'react';
+import { useMemo, useState } from 'react';
import { ArrowLeftRight, ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { cn } from '@/lib/utils';
import { readBotDirectMessageMeta, type BotDirectMessageMeta } from '../../../shared/botDirectMessage';
import { BotAvatar } from './BotAvatar';
import { useBotProfiles } from './botStore';
-export function BotDirectMessageCard({ data }: { data?: Record<string, unknown> }) {
+export function BotDirectMessageCard({ data, sessionId }: { data?: Record<string, unknown>; sessionId?: string }) {
const meta = readBotDirectMessageMeta(data);
if (!meta) return null;
- return <BotDirectMessageCardBody meta={meta} />;
+ return <BotDirectMessageCardBody meta={meta} sessionId={sessionId} />;
}
-function BotDirectMessageCardBody({ meta }: { meta: BotDirectMessageMeta }) {
+function BotDirectMessageCardBody({ meta, sessionId }: { meta: BotDirectMessageMeta; sessionId?: string }) {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
- const profiles = useBotProfiles();
+ const allProfiles = useBotProfiles();
+ const [deviceId] = useState(() => sessionId ? remoteProjectsStore.getSessionDeviceId(sessionId) : null);
+ const profiles = deviceId ? [] : allProfiles;
const peer = useMemo(() => {
const profile = profiles.find((item) => item.id === meta.peerBotId);
@@ -42,7 +45,7 @@ function BotDirectMessageCardBody({ meta }: { meta: BotDirectMessageMeta }) {
type="button"
onClick={() =>
navigate(
- `/bots/${encodeURIComponent(meta.viewerBotId)}/direct/${encodeURIComponent(meta.threadId)}`,
+ `/bots/${encodeURIComponent(meta.viewerBotId)}/direct/${encodeURIComponent(meta.threadId)}${deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : ''}`,
{
state: {
botDirectMessageReturnTo: `${location.pathname}${location.search}`,
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
index f2e5d81255..e9739443a1 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
@@ -3,6 +3,8 @@ import { ArrowLeftRight, CircleAlert, LockKeyhole } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
+import { makerApiForDevice } from '@/lib/makerTransport';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { Spinner } from '@/components/ui/spinner';
import {
getDataOwnerGeneration,
@@ -25,7 +27,9 @@ export function BotDirectMessageView() {
const navigate = useNavigate();
const location = useLocation();
const { botId, threadId } = useParams();
- const profiles = useBotProfiles();
+ const deviceId = new URLSearchParams(location.search).get('deviceId');
+ const allProfiles = useBotProfiles();
+ const profiles = deviceId ? [] : allProfiles;
const [state, setState] = useState<DirectMessageState>({ kind: 'loading' });
useEffect(() => {
@@ -40,7 +44,7 @@ export function BotDirectMessageView() {
return;
}
try {
- const result = await window.electronAPI.maker.getBotDirectMessageThread(threadId, botId);
+ const result = await (deviceId ? makerApiForDevice(deviceId) : window.electronAPI.maker).getBotDirectMessageThread(threadId, botId);
if (cancelled || version !== requestVersion || !isDataOwnerGenerationCurrent(owner)) return;
setState(result.ok ? { kind: 'ready', thread: result.thread } : { kind: 'unavailable' });
} catch {
@@ -50,16 +54,27 @@ export function BotDirectMessageView() {
}
};
void load();
- const unsubscribe = window.electronAPI.maker.onBotDirectMessageChanged((payload, ownerStamp) => {
- if (!isDataOwnerPushCurrent(ownerStamp) || payload.threadId !== threadId) return;
- void load();
- });
+ const unsubscribe = deviceId
+ ? window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
+ if (push.deviceId !== deviceId || push.channel !== 'maker:bot-direct-message:changed'
+ || !isDeviceLinkRemotePushCurrent(push, stamp)) return;
+ if ((push.payload as { threadId?: string })?.threadId === threadId) void load();
+ })
+ : window.electronAPI.maker.onBotDirectMessageChanged((payload, ownerStamp) => {
+ if (!isDataOwnerPushCurrent(ownerStamp) || payload.threadId !== threadId) return;
+ void load();
+ });
+ const offStatus = deviceId ? window.electronAPI.deviceLink.onStatusChanged((state) => {
+ if (state.status === 'online') void load();
+ else requestVersion += 1;
+ }) : () => {};
return () => {
+ offStatus();
cancelled = true;
requestVersion += 1;
unsubscribe();
};
- }, [botId, threadId]);
+ }, [botId, deviceId, threadId]);
const thread = state.kind === 'ready' ? state.thread : null;
const profileFor = useCallback(
@@ -103,7 +118,9 @@ export function BotDirectMessageView() {
candidate.startsWith('/bots/') &&
!candidate.includes('/direct/')
? candidate
- : botId
+ : deviceId && botId
+ ? `/bots/remote/${encodeURIComponent(deviceId)}/${encodeURIComponent(botId)}`
+ : botId
? `/bots/${encodeURIComponent(botId)}`
: '/bots';
navigate(returnTo, { replace: true });
diff --git a/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx b/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx
index 53f6aaa5c5..32f1fd5ff3 100644
--- a/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx
@@ -28,7 +28,7 @@ import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
import { sendSessionEventNotification } from '@/lib/sessionEventNotification';
import { useSidebarCollapsedState, useRegisterSidebarUpper } from '../feature-context';
import { useRemoteBots } from './useRemoteBots';
-import { remoteBotKey } from './remoteBotRoster';
+import { remoteBotKey, isRemoteBotUnread } from './remoteBotRoster';
import { BotConnectionStatus } from './BotConnectionStatus';
import { BotAvatar } from './BotAvatar';
import { BotCreateMenu } from './BotCreateMenu';
@@ -323,6 +323,7 @@ function BotsSidebarContent() {
<span className="truncate text-14 leading-5">{bot.name}</span>
<span className="truncate text-12 leading-4 text-[var(--sidebar-list-muted)]">{bot.preview || bot.description || t('bots.list.startChat')}</span>
</span>
+ {!selected && isRemoteBotUnread(bot) ? <span aria-label={t('bots.list.unread', { count: 1 })} className="size-[7px] shrink-0 rounded-full bg-[var(--bot-unread-bg)]" /> : null}
<span className="w-10 shrink-0 self-start pt-0.5 text-right text-11 tabular-nums text-[var(--sidebar-list-muted)]">{formatBotListTimestamp(bot.activityAt, now)}</span>
</button>
);
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index b6ac29f804..9c08a9b3aa 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@ -8,7 +8,7 @@ import type { Session } from '@/lib/ccAgent.types';
import { Spinner } from '@/components/ui/spinner';
import { BotAvatar } from './BotAvatar';
import { parseRemoteBots, type RemoteBot } from './remoteBotRoster';
-import { useRemoteBots } from './useRemoteBots';
+import { markRemoteBotRead, useRemoteBots } from './useRemoteBots';
/** The session id comes from the host's collection, never from an arbitrary URL. */
export function RemoteBotSessionView() {
@@ -17,6 +17,7 @@ export function RemoteBotSessionView() {
const bots = useRemoteBots();
const bot = bots.find((row) => row.id === botId && row.deviceId === deviceId);
const [ready, setReady] = useState<RemoteBot | null>(null);
+ const [validatedSessionId, setValidatedSessionId] = useState<string | null | undefined>(null);
const [failed, setFailed] = useState(false);
const [retry, setRetry] = useState(0);
const sessionId = bot?.sessionId;
@@ -56,6 +57,7 @@ export function RemoteBotSessionView() {
throw new Error('Invalid remote companion session');
remoteProjectsStore.mergeDeviceSessions(deviceId, bot.deviceName, [session]);
setReady(resolved);
+ setValidatedSessionId(sessionId);
})().catch(() => {
if (!disposed) setFailed(true);
});
@@ -64,14 +66,23 @@ export function RemoteBotSessionView() {
};
}, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry]);
- if (bot && ready?.sessionId && ready.id === botId && ready.deviceId === deviceId) {
+ useEffect(() => {
+ const read = () => {
+ if (document.visibilityState === 'visible' && bot && ready?.id === bot.id && ready.deviceId === bot.deviceId && validatedSessionId === bot.sessionId) markRemoteBotRead(bot.deviceId, bot.id, bot.lastReplyAt ?? 0);
+ };
+ read();
+ document.addEventListener('visibilitychange', read);
+ return () => document.removeEventListener('visibilitychange', read);
+ }, [bot?.deviceId, bot?.id, bot?.lastReplyAt, bot?.sessionId, ready?.sessionId, validatedSessionId]);
+
+ if (bot && !failed && ready?.sessionId && ready.id === botId && ready.deviceId === deviceId) {
return (
<CCAgentSessionView
key={`${deviceId}:${ready.sessionId}`}
sessionIdProp={ready.sessionId}
routeOwner
botIdentity={ready}
- readOnly={!bot.online}
+ readOnly={!bot.online || validatedSessionId !== bot.sessionId || failed}
/>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
index 0e8e5abf85..86edb8fbbd 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx
@@ -1,3 +1,5 @@
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { __resetStickySessionOriginForTest } from '@/features/device-link/stickySessionOrigin';
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
@@ -12,7 +14,7 @@ import type {
} from '../../../../shared/botDelegation';
import type { BotCollaborationMeta } from '../../../../shared/botCollaboration';
-const mocks = vi.hoisted(() => ({ navigate: vi.fn() }));
+const mocks = vi.hoisted(() => ({ navigate: vi.fn(), remoteBots: [] as any[] }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -21,6 +23,8 @@ vi.mock('react-i18next', () => ({
i18n: { language: 'en' },
}),
}));
+vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));
+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => mocks.remoteBots }));
vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));
const SESSION_ID = 'parent-session-1';
@@ -79,6 +83,7 @@ let cancelBotDelegation: ReturnType<typeof vi.fn>;
beforeEach(() => {
listeners = [];
+ mocks.remoteBots = [];
mocks.navigate.mockClear();
__resetBotDelegationLiveForTest();
listBotDelegations = vi.fn(async () => ({ ok: true as const, delegations: [] }));
@@ -109,6 +114,8 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ remoteProjectsStore.clear();
+ __resetStickySessionOriginForTest();
__resetBotDelegationLiveForTest();
});
@@ -331,3 +338,34 @@ describe('BotSessionTaskCard', () => {
expect(screen.queryByText(/bots\.collab\.status\.failed/)).toBeNull();
});
});
+
+
+it('routes remote task reads, stop, child navigation and push refresh to the same Mac', async () => {
+ mocks.remoteBots = [{ deviceId: 'home', online: true }];
+ remoteProjectsStore.pinSessionOrigin('home', SESSION_ID);
+ let push!: (value: any, stamp?: any) => void;
+ let status!: (value: any) => void;
+ const invoke = vi.fn(async (_device: string, channel: string) => channel === 'maker:bot-delegations:list'
+ ? { ok: true, delegations: [delegation('running')] } : { ok: true });
+ window.electronAPI.deviceLink = {
+ invoke, onRemotePush: (fn: any) => { push = fn; return () => {}; },
+ onStatusChanged: (fn: any) => { status = fn; return () => {}; },
+ } as any;
+ render(<BotSessionTaskCard sessionId={SESSION_ID} data={meta() as any} />);
+ const stop = await screen.findByRole('button', { name: 'bots.collab.stopTask' });
+ expect(invoke).toHaveBeenCalledWith('home', 'maker:bot-delegations:list', [SESSION_ID]);
+ expect(listBotDelegations).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.collab.watchWork' }));
+ expect(remoteProjectsStore.getSessionDeviceId('child-1')).toBe('home');
+ // Even when reconnect clears the transient registry, stop must never hit the local maker.
+ remoteProjectsStore.clear();
+ fireEvent.click(stop);
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('home', 'maker:bot-delegation:cancel', [SESSION_ID, DELEGATION_ID]));
+ expect(cancelBotDelegation).not.toHaveBeenCalled();
+ const reads = invoke.mock.calls.length;
+ act(() => push({ deviceId: 'office', channel: 'maker:bot-delegation:changed', payload: { parentSessionId: SESSION_ID } }));
+ expect(invoke).toHaveBeenCalledTimes(reads);
+ invoke.mockResolvedValue({ ok: true, delegations: [delegation('completed', { resultSummary: 'Remote done' })] });
+ act(() => status({ status: 'online' }));
+ await screen.findByText('Remote done');
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
index fac20cafb2..e41df5c51e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BotDirectMessageView } from '../BotDirectMessageView';
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
getThread: vi.fn(),
navigate: vi.fn(),
registerHeader: vi.fn(),
+ search: '',
}));
vi.mock('react-i18next', () => ({
@@ -16,11 +17,13 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('react-router-dom', () => ({
useLocation: () => ({
+ search: mocks.search,
state: { botDirectMessageReturnTo: '/bots/bot-a/session/a-main' },
}),
useNavigate: () => mocks.navigate,
useParams: () => ({ botId: 'bot-a', threadId: 'dm-1' }),
}));
+vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({
getDataOwnerGeneration: () => 1,
isDataOwnerGenerationCurrent: () => true,
@@ -40,6 +43,7 @@ vi.mock('../BotAvatar', () => ({
}));
beforeEach(() => {
+ mocks.search = '';
mocks.navigate.mockClear();
mocks.registerHeader.mockClear();
mocks.getThread.mockReset();
@@ -114,3 +118,23 @@ describe('BotDirectMessageView', () => {
expect(screen.queryByRole('textbox')).toBeNull();
});
});
+
+
+it('loads a remote private thread and refreshes it after reconnect without using local profiles', async () => {
+ mocks.search = '?deviceId=home';
+ let status!: (state: any) => void;
+ const response = await mocks.getThread(); mocks.getThread.mockClear();
+ response.thread.botAName = 'Remote Cindy';
+ response.thread.messages[0].senderBotName = 'Remote Cindy';
+ const invoke = vi.fn(async () => response);
+ window.electronAPI.deviceLink = {
+ invoke, onRemotePush: () => () => {}, onStatusChanged: (fn: any) => { status = fn; return () => {}; },
+ } as any;
+ render(<BotDirectMessageView />);
+ await screen.findByText('Can you check this?');
+ expect(invoke).toHaveBeenCalledWith('home', 'maker:bot-direct-message-thread:get', ['dm-1', 'bot-a']);
+ expect(mocks.getThread).not.toHaveBeenCalled();
+ expect(screen.getAllByText(/Remote Cindy/).length).toBeGreaterThan(0);
+ act(() => status({ status: 'online' }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index 6135e0274b..2494fb5e04 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@ -12,6 +12,7 @@ const h = vi.hoisted(() => ({
vi.mock('react-router-dom', () => ({ useParams: () => ({ deviceId: 'home', botId: 'writer' }) }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../useRemoteBots', () => ({
+ markRemoteBotRead: vi.fn(),
useRemoteBots: () => [
{
id: 'writer',
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx
index dc6a120b60..1b8cc5c89a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx
@@ -15,9 +15,9 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({
useDeviceLinkDeviceList: () => h.devices,
}));
vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));
-import { useRemoteBotSync, useRemoteBots } from '../useRemoteBots';
+import { useRemoteBotSync, useRemoteBots, markRemoteBotRead } from '../useRemoteBots';
import { parseRemoteCollectionListRequest } from '@cindy/device-link';
-import { parseRemoteBots, remoteBotKey } from '../remoteBotRoster';
+import { parseRemoteBots, remoteBotKey, isRemoteBotUnread } from '../remoteBotRoster';
const host = (deviceId: string, online = true) => ({
deviceId,
name: deviceId,
@@ -48,6 +48,7 @@ beforeEach(() => {
window.electronAPI = {
deviceLink: {
invoke: h.invoke,
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'online' }),
onStatusChanged: (fn: any) => {
h.status = fn;
return () => {};
@@ -88,6 +89,7 @@ describe('remote teammate roster', () => {
}),
);
const { result } = renderHook(useRoster);
+ await waitFor(() => expect(h.invoke).toHaveBeenCalled());
act(() => h.status({ status: 'stopped' }));
await act(async () => finish(collection()));
expect(result.current).toEqual([]);
@@ -101,6 +103,7 @@ describe('remote teammate roster', () => {
}),
);
const { result, rerender } = renderHook(useRoster);
+ await waitFor(() => expect(h.invoke).toHaveBeenCalled());
h.owner = 'new-account';
h.devices = [];
rerender();
@@ -121,3 +124,28 @@ describe('remote teammate roster', () => {
expect(() => parseRemoteBots(wrong, 'a', 'A')).toThrow();
});
});
+
+
+it('does not let a late initial online state undo a stopped relay push', async () => {
+ let finish!: (state: unknown) => void;
+ (window.electronAPI.deviceLink.getState as any).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ renderHook(useRoster);
+ act(() => h.status({ status: 'stopped' }));
+ await act(async () => finish({ linkStatus: 'online' }));
+ expect(h.invoke).not.toHaveBeenCalled();
+});
+it('keeps cached companions offline on reconnect and preserves device-qualified unread state', async () => {
+ const withReply = (at: number) => { const value = collection(); Object.assign(value.items[0].display, { lastReplyAt: at }); return value; };
+ h.invoke.mockResolvedValue(withReply(100));
+ const { result } = renderHook(useRoster);
+ await waitFor(() => expect(result.current).toHaveLength(2));
+ expect(result.current.some(isRemoteBotUnread)).toBe(false);
+ act(() => h.status({ status: 'reconnecting' }));
+ expect(result.current.every((bot) => !bot.online)).toBe(true);
+ h.invoke.mockResolvedValue(withReply(200));
+ act(() => h.status({ status: 'online' }));
+ await waitFor(() => expect(result.current.every(isRemoteBotUnread)).toBe(true));
+ act(() => markRemoteBotRead('a', 'same-bot', 200));
+ expect(isRemoteBotUnread(result.current.find((bot) => bot.deviceId === 'a')!)).toBe(false);
+ expect(isRemoteBotUnread(result.current.find((bot) => bot.deviceId === 'b')!)).toBe(true);
+});
diff --git a/apps/desktop/src/renderer/features/bots/botDelegationLive.ts b/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
index 8f7e313e51..f642b132c7 100644
--- a/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
+++ b/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
@@ -5,6 +5,9 @@ import {
isDataOwnerGenerationCurrent,
isDataOwnerPushCurrent,
} from '@/contexts/dataOwnerGeneration';
+import { makerApiForSticky } from '@/lib/makerTransport';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import type { BotDelegationStatus, BotDelegationView } from '../../../shared/botDelegation';
/** 未落终态的后台任务:任务卡按这个集合决定是否仍在执行。 */
@@ -64,7 +67,7 @@ async function reload(sessionId: string): Promise<void> {
const owner = getDataOwnerGeneration();
const generation = ++entry.reloadGeneration;
try {
- const result = await window.electronAPI.maker.listBotDelegations(sessionId);
+ const result = await makerApiForSticky(sessionId).listBotDelegations(sessionId);
if (!isDataOwnerGenerationCurrent(owner)) return;
if (sessions.get(sessionId) !== entry || entry.reloadGeneration !== generation) return;
// 短暂读取失败不能把已经显示的持久任务卡抹掉。成功时才替换快照;失败时
@@ -84,10 +87,23 @@ function subscribe(sessionId: string, listener: () => void): () => void {
const entry = ensureEntry(sessionId);
entry.listeners.add(listener);
if (!entry.unsubscribe) {
- entry.unsubscribe = window.electronAPI.maker.onBotDelegationChanged((payload, ownerStamp) => {
- if (!isDataOwnerPushCurrent(ownerStamp) || payload.parentSessionId !== sessionId) return;
- void reload(sessionId);
- });
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ const offPush = deviceId
+ ? window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
+ if (push.deviceId !== deviceId || push.channel !== 'maker:bot-delegation:changed'
+ || !isDeviceLinkRemotePushCurrent(push, stamp)) return;
+ const payload = push.payload as { parentSessionId?: string };
+ if (payload?.parentSessionId === sessionId) void reload(sessionId);
+ })
+ : window.electronAPI.maker.onBotDelegationChanged((payload, ownerStamp) => {
+ if (!isDataOwnerPushCurrent(ownerStamp) || payload.parentSessionId !== sessionId) return;
+ void reload(sessionId);
+ });
+ const offStatus = deviceId ? window.electronAPI.deviceLink.onStatusChanged((state) => {
+ if (state.status === 'online') void reload(sessionId);
+ else entry.reloadGeneration += 1;
+ }) : () => {};
+ entry.unsubscribe = () => { offPush(); offStatus(); };
void reload(sessionId);
}
return () => {
diff --git a/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts b/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts
index 273922f5f9..e10f5156ed 100644
--- a/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts
+++ b/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts
@@ -10,6 +10,8 @@ export interface RemoteBot {
activityAt: number;
sessionId: string | null;
online: boolean;
+ lastReplyAt?: number;
+ readAt?: number;
}
function record(value: unknown): Record<string, unknown> {
@@ -63,6 +65,7 @@ export function parseRemoteBots(value: unknown, deviceId: string, deviceName: st
preview: text(display.preview),
activityAt: typeof display.timestamp === 'number' ? display.timestamp : 0,
sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,
+ lastReplyAt: typeof display.lastReplyAt === 'number' && Number.isFinite(display.lastReplyAt) && display.lastReplyAt >= 0 ? display.lastReplyAt : undefined,
online: true,
};
});
@@ -71,3 +74,7 @@ export function parseRemoteBots(value: unknown, deviceId: string, deviceName: st
export function remoteBotKey(bot: Pick<RemoteBot, 'deviceId' | 'id'>): string {
return `${bot.deviceId}:${bot.id}`;
}
+
+export function isRemoteBotUnread(bot: RemoteBot): boolean {
+ return bot.lastReplyAt !== undefined && bot.readAt !== undefined && bot.lastReplyAt > bot.readAt;
+}
diff --git a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts b/apps/desktop/src/renderer/features/bots/useRemoteBots.ts
index 0a72c06c16..9c03311127 100644
--- a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts
+++ b/apps/desktop/src/renderer/features/bots/useRemoteBots.ts
@@ -10,11 +10,17 @@ import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDev
import { revokedDevicesStore } from '@/features/device-link/revokedDevicesStore';
import { parseRemoteBots, type RemoteBot } from './remoteBotRoster';
+const CACHE_PREFIX = 'cindy.remoteBots.v1.';
let owner: string | null = null;
let snapshot: RemoteBot[] = [];
const listeners = new Set<() => void>();
const publish = (next: RemoteBot[]) => {
snapshot = next;
+ if (owner) {
+ try { const value = JSON.stringify(next.map((bot) => ({ ...bot, online: false })));
+ if (value.length <= 256 * 1024) window.localStorage.setItem(CACHE_PREFIX + owner, value);
+ } catch { /* display cache may be unavailable */ }
+ }
listeners.forEach((fn) => fn());
};
const subscribe = (fn: () => void) => {
@@ -43,11 +49,31 @@ export function useRemoteBotSync(): void {
const nextOwner = isAuthenticated ? (dataOwnerId ?? null) : null;
if (owner !== nextOwner) {
owner = nextOwner;
- publish([]);
+ let cached: RemoteBot[] = [];
+ try {
+ if (!nextOwner) {
+ for (const key of Object.keys(window.localStorage)) if (key.startsWith(CACHE_PREFIX)) window.localStorage.removeItem(key);
+ } else {
+ const raw = window.localStorage.getItem(CACHE_PREFIX + nextOwner);
+ if (raw && raw.length <= 256 * 1024) {
+ const rows = JSON.parse(raw);
+ if (Array.isArray(rows)) cached = rows.slice(0, 200).filter((bot) => bot && ['id', 'deviceId', 'deviceName', 'name', 'avatar', 'avatarColor', 'description', 'preview'].every((key) => typeof bot[key] === 'string') && Number.isFinite(bot.activityAt)).map((bot) => ({
+ id: bot.id, deviceId: bot.deviceId, deviceName: bot.deviceName, name: bot.name,
+ avatar: bot.avatar, avatarColor: bot.avatarColor, description: bot.description, preview: bot.preview,
+ activityAt: bot.activityAt, sessionId: typeof bot.sessionId === 'string' ? bot.sessionId : null,
+ lastReplyAt: Number.isFinite(bot.lastReplyAt) ? bot.lastReplyAt : undefined,
+ readAt: Number.isFinite(bot.readAt) ? bot.readAt : undefined, online: false,
+ }));
+ }
+ }
+ } catch { /* missing/corrupt cache */ }
+ publish(cached);
}
- if (!nextOwner || !devices) return;
+ if (!nextOwner) return;
+ if (!devices) { publish(snapshot.map((bot) => ({ ...bot, online: false }))); return; }
let disposed = false;
- let relayAvailable = true;
+ let relayAvailable = false;
+ let statusRevision = 0;
const hosts = devices.filter(
(d) => !d.isSelf && d.controlEnabled && d.remoteControlEnabled && !revoked.has(d.deviceId),
);
@@ -77,7 +103,9 @@ export function useRemoteBotSync(): void {
[request],
);
if (!current() || generations.get(deviceId) !== epoch) return;
- const bots = parseRemoteBots(result, deviceId, host.name);
+ const bots = parseRemoteBots(result, deviceId, host.name).map((bot) => ({
+ ...bot, readAt: snapshot.find((old) => old.deviceId === deviceId && old.id === bot.id)?.readAt ?? bot.lastReplyAt ?? 0,
+ }));
publish([...snapshot.filter((bot) => bot.deviceId !== deviceId), ...bots]);
} catch {
if (!current() || generations.get(deviceId) !== epoch) return;
@@ -90,7 +118,8 @@ export function useRemoteBotSync(): void {
}
// The app's existing remote-session synchronizer owns the sessions topic.
// Sharing its pushes avoids competing subscribe/unsubscribe owners.
- for (const host of hosts) if (host.online) void refresh(host.deviceId);
+ // Subscribe before reading status: a stopped/connecting relay cannot inherit
+ // a stale device directory's online flag, and a late GET cannot undo a push.
const offPush = window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
if (
!current() ||
@@ -110,16 +139,27 @@ export function useRemoteBotSync(): void {
});
const offStatus = window.electronAPI.deviceLink.onStatusChanged((state) => {
if (!current()) return;
+ statusRevision += 1;
relayAvailable = state.status === 'online';
if (state.status === 'online') {
for (const host of hosts) if (host.online) void refresh(host.deviceId);
} else {
for (const id of byId.keys()) generations.set(id, (generations.get(id) ?? 0) + 1);
publish(
- state.status === 'stopped' ? [] : snapshot.map((bot) => ({ ...bot, online: false })),
+ snapshot.map((bot) => ({ ...bot, online: false })),
);
}
});
+ const revision = statusRevision;
+ void window.electronAPI.deviceLink.getState().then((state) => {
+ if (!current() || revision !== statusRevision) return;
+ relayAvailable = state.linkStatus === 'online';
+ if (relayAvailable) {
+ for (const host of hosts) if (host.online) void refresh(host.deviceId);
+ } else publish(snapshot.map((bot) => ({ ...bot, online: false })));
+ }).catch(() => {
+ if (current() && revision === statusRevision) publish(snapshot.map((bot) => ({ ...bot, online: false })));
+ });
return () => {
disposed = true;
offPush();
@@ -128,3 +168,9 @@ export function useRemoteBotSync(): void {
};
}, [dataOwnerId, isAuthenticated, devices, revoked]);
}
+
+export function markRemoteBotRead(deviceId: string, botId: string, at: number): void {
+ if (!Number.isFinite(at) || at < 0) return;
+ if (!snapshot.some((bot) => bot.deviceId === deviceId && bot.id === botId && (bot.readAt ?? -1) < at)) return;
+ publish(snapshot.map((bot) => bot.deviceId === deviceId && bot.id === botId ? { ...bot, readAt: Math.max(bot.readAt ?? 0, at) } : bot));
+}
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index 7d5adf382d..4d3a8f77ee 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -42,6 +42,9 @@ type FullMaker = typeof window.electronAPI.maker;
* REMOTE_INVOKE_ALLOWLIST 白名单内(被控端执行前还会再校验一层)。
*/
export interface RoutableMaker {
+ listBotDelegations: FullMaker['listBotDelegations'];
+ cancelBotDelegation: FullMaker['cancelBotDelegation'];
+ getBotDirectMessageThread: FullMaker['getBotDirectMessageThread'];
send: FullMaker['send'];
setModel: FullMaker['setModel'];
// session-agent-switch:跨引擎切换是**会话级**操作,数据真相(pending 意图注册表 +
@@ -141,6 +144,9 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
(...args: unknown[]): Promise<unknown> =>
invokeRemote(deviceId, channel, args);
return {
+ listBotDelegations: t('maker:bot-delegations:list') as FullMaker['listBotDelegations'],
+ cancelBotDelegation: t('maker:bot-delegation:cancel') as FullMaker['cancelBotDelegation'],
+ getBotDirectMessageThread: t('maker:bot-direct-message-thread:get') as FullMaker['getBotDirectMessageThread'],
send: t('maker:send') as FullMaker['send'],
setModel: (async (...args: SetModelArgs) =>
invokeRemote(
diff --git a/apps/desktop/src/shared/botCollaboration.ts b/apps/desktop/src/shared/botCollaboration.ts
index 37154e5f36..43479485f8 100644
--- a/apps/desktop/src/shared/botCollaboration.ts
+++ b/apps/desktop/src/shared/botCollaboration.ts
@@ -1,117 +1,2 @@
-/**
- * 伙伴发起的可追踪任务在消息流中的结构化标记。
- *
- * 事实源仍是 `bot_delegations` 行。这里是父任务消息流里的持久锚点,让 renderer 在原位
- * 投影唯一任务卡与补充消息留痕。字段名 `botCollaboration` 为 v1 持久化兼容保留。
- *
- * 设计约束:
- * - 只增不改。老数据(没有本标记的镜像消息)继续按普通文本渲染,不回填、不迁移。
- * - 写进 `messages.agent_meta`(JSON 列)的 `botCollaboration` 字段,不动 schema。
- * - 只承载呈现所需的**冻结快照**(当时的名字),不做权限判据:能不能打开对方任务
- * 仍由既有的会话可见性决定,本标记不放宽任何边界。
- */
-
-/** 后台任务标记在某条消息上的用途。后三种只用于读取旧数据,不再生成或展示。 */
-export type BotCollaborationRole =
- /** 父任务:启动时写下的任务卡锚点(空正文,只为承载卡片)。 */
- | 'delegation-request'
- /** 历史:父任务里的目标伙伴结果。 */
- | 'guest-result'
- /** 父任务:发起方给进行中任务追加消息的留痕。 */
- | 'interjection'
- /** 历史:目标伙伴主任务里的请求镜像。 */
- | 'guest-request'
- /** 历史:目标伙伴主任务里的终态镜像。 */
- | 'result-mirror';
-
-export interface BotCollaborationMeta {
- v: 1;
- role: BotCollaborationRole;
- delegationId: string;
- /** 发起后台任务的伙伴。 */
- fromBotId: string;
- fromBotName: string;
- /** 新数据恒为 null;非 null 只可能来自旧版具名伙伴任务。 */
- toBotId: string | null;
- toBotName: string;
- /** 发起方任务;目标侧镜像据此回跳,看得到「这活是谁派的」。 */
- parentSessionId: string | null;
- /** 目标执行用的子任务;发起方侧据此跳过去看 TA 的完整对话。 */
- childSessionId: string | null;
- /** 委派目标摘要,用于卡片折叠态文案。 */
- objective: string;
-}
-
-const ROLES = new Set<BotCollaborationRole>([
- 'delegation-request',
- 'guest-result',
- 'interjection',
- 'guest-request',
- 'result-mirror',
-]);
-
-function optionalId(value: unknown): string | null | undefined {
- if (value === null) return null;
- if (typeof value === 'string') return value;
- return undefined;
-}
-
-/**
- * 严格解析:形状不对一律当作「没有标记」,退回普通文本渲染。宁可少一张卡,
- * 也不要把无法核实的身份贴到别人的气泡上。
- */
-export function readBotCollaborationMeta(value: unknown): BotCollaborationMeta | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- const raw = value as Record<string, unknown>;
- if (raw.v !== 1) return null;
- if (typeof raw.role !== 'string' || !ROLES.has(raw.role as BotCollaborationRole)) return null;
- if (typeof raw.delegationId !== 'string' || !raw.delegationId) return null;
- if (typeof raw.fromBotId !== 'string' || !raw.fromBotId) return null;
- if (raw.toBotId !== null && (typeof raw.toBotId !== 'string' || !raw.toBotId)) return null;
- if (typeof raw.fromBotName !== 'string' || typeof raw.toBotName !== 'string') return null;
- if (typeof raw.objective !== 'string') return null;
- const parentSessionId = optionalId(raw.parentSessionId);
- const childSessionId = optionalId(raw.childSessionId);
- if (parentSessionId === undefined || childSessionId === undefined) return null;
- return {
- v: 1,
- role: raw.role as BotCollaborationRole,
- delegationId: raw.delegationId,
- fromBotId: raw.fromBotId,
- fromBotName: raw.fromBotName,
- toBotId: raw.toBotId,
- toBotName: raw.toBotName,
- parentSessionId,
- childSessionId,
- objective: raw.objective,
- };
-}
-
-/** 委派相关消息的幂等 clientId 前缀,main 与测试共用同一份常量。 */
-export const BOT_DELEGATION_CLIENT_ID = {
- /** 父任务里的任务卡锚点。 */
- parentRequest: (delegationId: string) => `bot-delegation-request:${delegationId}`,
- /** 父任务里的结果回传(历史值,不可改)。 */
- completion: (delegationId: string) => `bot-delegation-completion:${delegationId}`,
- /** 同一任务结束后继续执行时,每一轮必须有独立的完成回执。首轮保持历史值兼容。 */
- completionRun: (delegationId: string, runSequence: number) =>
- runSequence <= 1
- ? `bot-delegation-completion:${delegationId}`
- : `bot-delegation-completion:${delegationId}:${runSequence}`,
- /** 插话:投进子任务的那条。 */
- interjection: (delegationId: string, token: string) =>
- `bot-delegation-interject:${delegationId}:${token}`,
- /** 插话:留在父任务里的留痕。 */
- interjectionMirror: (delegationId: string, token: string) =>
- `bot-delegation-interject-mirror:${delegationId}:${token}`,
-} as const;
-
-export type BotDelegationInterjectResult =
- | {
- ok: true;
- delegationId: string;
- childSessionId: string;
- /** 子任务当时是否正忙:忙则本条进它的输入队列,当前回合结束后被读到。 */
- queued: boolean;
- }
- | { ok: false; errorCode: string; message: string };
+/** Shared wire and presentation contract; legacy Desktop import path. */
+export * from '@cindy/maker-shared/botCollaboration';
diff --git a/apps/desktop/src/shared/botDelegation.ts b/apps/desktop/src/shared/botDelegation.ts
index 1cb979c09f..efcf3cd4e5 100644
--- a/apps/desktop/src/shared/botDelegation.ts
+++ b/apps/desktop/src/shared/botDelegation.ts
@@ -1,221 +1,2 @@
-/**
- * 一条伙伴发起的后台 Session 任务状态机:
- *
- * queued → running ⇄ waiting → completed | failed | cancelled
- *
- * - queued: 已发起,对方还没接手(含首句没送进去、正在退避重试)。
- * - running: 对方正在做。
- * - waiting: 对方停在一个要人拍板的地方(权限确认 / 提问 / 计划审核),
- * `pendingInteraction` 里是具体在等什么;发起方伙伴替用户答,
- * 或用户直接在子任务里答,任一侧答了就回到 running。
- * - completed / failed / cancelled: 终态。超时归入 failed(lastError 以 TIMEOUT 开头)。
- */
-export const BOT_DELEGATION_STATUSES = [
- 'queued',
- 'running',
- 'waiting',
- 'completed',
- 'failed',
- 'cancelled',
- /** Legacy terminal rows remain readable; new timeouts are stored as failed + TIMEOUT. */
- 'timed-out',
-] as const;
-
-export type BotDelegationStatus = (typeof BOT_DELEGATION_STATUSES)[number];
-
-export type BotDelegationInteractionKind = 'permission' | 'ask_user_question' | 'plan_review';
-
-/** waiting 状态下对方正在等的那件事,给卡片与发起方伙伴看的同一份摘要。 */
-export interface BotDelegationPendingInteraction {
- requestId: string;
- kind: BotDelegationInteractionKind;
- /** 人话摘要:要批的是什么 / 问的是什么 / 计划标题。 */
- summary: string;
- raisedAt: number;
-}
-
-/** 子任务交出的文件(相对子任务工作目录的路径 + 绝对路径)。 */
-export interface BotDelegationArtifact {
- path: string;
- absolutePath: string;
- status: 'added' | 'modified' | 'deleted' | 'renamed';
-}
-
-export interface BotDelegationCapabilitySnapshot {
- profileVersion: number;
- agentKind: 'cc' | 'codex' | 'pi';
- model: string;
- capabilitiesSha256: string;
- identitySha256: string;
- skills: string[];
- skillMode: 'inherit' | 'allowlist';
- mcpServers: string[];
- mcpMode: 'inherit' | 'allowlist';
- toolsets: string[];
- toolsetMode: 'inherit' | 'allowlist';
- memoryEnabled: boolean;
-}
-
-/**
- * Execution plan captured before a child task is made visible.
- *
- * Bot Profile versions freeze identity, but capability catalogs are mutable.
- * Delegations therefore persist the exact authorization facts approved at
- * creation time. Runtime startup and restart recovery must consume this
- * snapshot instead of re-reading the Bot's current configuration. Authorization and
- * destination facts remain immutable; only `limits.deadlineAt` may move forward by the
- * measured time spent waiting for a user decision.
- *
- * `targetBotId === null` means the child is a plain Cindy task (not another
- * Bot): no target Profile freeze, no target-side timeline mirror — the child
- * session itself is the user-visible workspace.
- */
-export interface BotDelegationPlanSnapshot {
- version: 1;
- createdAt: number;
- targetBotId: string | null;
- /**
- * The target Bot task that received the human-visible delegation transcript.
- * Frozen at creation so an abnormal canonical recovery never splits the request and result
- * across two tasks. Absent for plain-Cindy delegations.
- */
- targetCanonicalSessionId?: string;
- /** Frozen target capability facts. Absent for plain-Cindy delegations. */
- target?: BotDelegationCapabilitySnapshot;
- access: {
- contextRefs: string[];
- };
- /** Frozen destination for the completion signal. */
- completionTarget: {
- parentSessionId: string;
- };
- limits: {
- maxDepth: number;
- timeoutMs: number;
- deadlineAt: number;
- };
- permission: {
- /** 子任务实际运行的权限档;Cindy 任务目标从 ask 开始并把交互回调给发起伙伴。 */
- mode: string;
- requesterMode: string | null;
- targetConfigured: 'ask' | 'trusted';
- };
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return !!value && typeof value === 'object' && !Array.isArray(value);
-}
-
-function isStringArray(value: unknown): value is string[] {
- return Array.isArray(value) && value.every((item) => typeof item === 'string');
-}
-
-function isCapabilitySnapshot(target: unknown): target is BotDelegationCapabilitySnapshot {
- if (!isRecord(target)) return false;
- return (
- typeof target.profileVersion === 'number'
- && (target.agentKind === 'cc' || target.agentKind === 'codex' || target.agentKind === 'pi')
- && typeof target.model === 'string'
- && typeof target.capabilitiesSha256 === 'string'
- && typeof target.identitySha256 === 'string'
- && isStringArray(target.skills)
- && (target.skillMode === 'inherit' || target.skillMode === 'allowlist')
- && isStringArray(target.mcpServers)
- && (target.mcpMode === 'inherit' || target.mcpMode === 'allowlist')
- && isStringArray(target.toolsets)
- && (target.toolsetMode === 'inherit' || target.toolsetMode === 'allowlist')
- && typeof target.memoryEnabled === 'boolean'
- );
-}
-
-/** Strict parser: malformed or pre-v1 plans are never silently reinterpreted. */
-export function parseBotDelegationPlanSnapshot(
- value: string | Record<string, unknown> | null | undefined,
-): BotDelegationPlanSnapshot | null {
- let parsed: unknown = value;
- if (typeof value === 'string') {
- try {
- parsed = JSON.parse(value) as unknown;
- } catch {
- return null;
- }
- }
- if (!isRecord(parsed) || parsed.version !== 1) return null;
- const access = parsed.access;
- const limits = parsed.limits;
- const permission = parsed.permission;
- const completionTarget = parsed.completionTarget;
- if (
- typeof parsed.createdAt !== 'number'
- || (parsed.targetBotId !== null && typeof parsed.targetBotId !== 'string')
- || !isRecord(access)
- || !isRecord(limits)
- || !isRecord(permission)
- || !isRecord(completionTarget)
- || typeof completionTarget.parentSessionId !== 'string'
- ) return null;
- if (
- parsed.targetCanonicalSessionId !== undefined
- && (
- typeof parsed.targetCanonicalSessionId !== 'string'
- || parsed.targetCanonicalSessionId.length === 0
- )
- ) return null;
- if (parsed.targetBotId !== null && !isCapabilitySnapshot(parsed.target)) return null;
- if (parsed.targetBotId === null && parsed.target !== undefined) return null;
- if (!isStringArray(access.contextRefs)) return null;
- if (
- typeof limits.maxDepth !== 'number'
- || typeof limits.timeoutMs !== 'number'
- || typeof limits.deadlineAt !== 'number'
- || typeof permission.mode !== 'string'
- || permission.mode.length === 0
- || (permission.requesterMode !== null && typeof permission.requesterMode !== 'string')
- || (permission.targetConfigured !== 'ask' && permission.targetConfigured !== 'trusted')
- ) return null;
- return parsed as unknown as BotDelegationPlanSnapshot;
-}
-
-export interface BotDelegationView {
- id: string;
- requestingBotId: string;
- /** null = 委派给一条普通 Cindy 任务。 */
- targetBotId: string | null;
- targetBotName: string;
- parentSessionId: string | null;
- childSessionId: string | null;
- /** The actual child Session title, including a caller-supplied task name. */
- title: string;
- objective: string;
- contextRefs: string[];
- permissionSnapshot: Record<string, unknown>;
- lineage: string[];
- targetProfileVersion: number | null;
- depth: number;
- status: BotDelegationStatus;
- /** 只在 waiting 时非空。 */
- pendingInteraction: BotDelegationPendingInteraction | null;
- resultSummary: string | null;
- artifacts: BotDelegationArtifact[];
- lastError: string | null;
- createdAt: number;
- acceptedAt: number | null;
- completedAt: number | null;
- updatedAt: number;
-}
-
-export interface BotDelegationChangedPayload {
- delegationId: string;
- parentSessionId: string | null;
- childSessionId: string | null;
- status: BotDelegationStatus;
- pendingInteraction?: BotDelegationPendingInteraction | null;
-}
-
-export type BotDelegationListResult =
- | { ok: true; delegations: BotDelegationView[] }
- | { ok: false; errorCode: string; message: string };
-
-export type BotDelegationCancelResult =
- | { ok: true; delegationId: string; childSessionId: string | null }
- | { ok: false; errorCode: string; message: string };
+/** Shared wire and presentation contract; legacy Desktop import path. */
+export * from '@cindy/maker-shared/botDelegation';
diff --git a/apps/desktop/src/shared/botDirectMessage.ts b/apps/desktop/src/shared/botDirectMessage.ts
index ed16eeba4b..47afca01f8 100644
--- a/apps/desktop/src/shared/botDirectMessage.ts
+++ b/apps/desktop/src/shared/botDirectMessage.ts
@@ -1,79 +1,2 @@
-export type BotDirectMessageThreadStatus = 'active' | 'closed';
-export type BotDirectMessageCloseReason = 'message-limit' | 'idle-timeout' | null;
-
-export interface BotDirectMessageMeta {
- v: 1;
- threadId: string;
- viewerBotId: string;
- peerBotId: string;
- peerBotName: string;
- direction: 'sent' | 'received';
- sequence: number;
- preview: string;
-}
-
-export interface BotDirectMessageItem {
- id: string;
- sequence: number;
- senderBotId: string;
- senderBotName: string;
- recipientBotId: string;
- recipientBotName: string;
- content: string;
- createdAt: number;
-}
-
-export interface BotDirectMessageThreadView {
- id: string;
- botAId: string;
- botAName: string;
- botBId: string;
- botBName: string;
- status: BotDirectMessageThreadStatus;
- closeReason: BotDirectMessageCloseReason;
- messageCount: number;
- maxMessages: number;
- createdAt: number;
- updatedAt: number;
- closedAt: number | null;
- messages: BotDirectMessageItem[];
-}
-
-export type BotDirectMessageThreadResult =
- | { ok: true; thread: BotDirectMessageThreadView }
- | { ok: false; errorCode: string; message: string };
-
-export interface BotDirectMessageChangedPayload {
- threadId: string;
- participantBotIds: [string, string];
-}
-
-export function readBotDirectMessageMeta(value: unknown): BotDirectMessageMeta | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- const raw = value as Record<string, unknown>;
- if (raw.v !== 1) return null;
- if (typeof raw.threadId !== 'string' || !raw.threadId) return null;
- if (typeof raw.viewerBotId !== 'string' || !raw.viewerBotId) return null;
- if (typeof raw.peerBotId !== 'string' || !raw.peerBotId) return null;
- if (typeof raw.peerBotName !== 'string') return null;
- if (raw.direction !== 'sent' && raw.direction !== 'received') return null;
- if (typeof raw.sequence !== 'number' || !Number.isInteger(raw.sequence) || raw.sequence < 1) {
- return null;
- }
- if (typeof raw.preview !== 'string') return null;
- return {
- v: 1,
- threadId: raw.threadId,
- viewerBotId: raw.viewerBotId,
- peerBotId: raw.peerBotId,
- peerBotName: raw.peerBotName,
- direction: raw.direction,
- sequence: raw.sequence,
- preview: raw.preview,
- };
-}
-
-export const BOT_DIRECT_MESSAGE_CLIENT_ID = {
- timelineAnchor: (threadId: string, deliveryId: string, sessionId: string) =>
- `bot-dm-thread:${threadId}:${deliveryId}:${sessionId}`,
-} as const;
+/** Shared wire and presentation contract; legacy Desktop import path. */
+export * from '@cindy/maker-shared/botDirectMessage';
diff --git a/apps/mobile/app/companions/direct/[threadId].tsx b/apps/mobile/app/companions/direct/[threadId].tsx
new file mode 100644
index 0000000000..33ee4e07d7
--- /dev/null
+++ b/apps/mobile/app/companions/direct/[threadId].tsx
@@ -0,0 +1,44 @@
+import { useCallback } from 'react';
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { ScrollView, StyleSheet } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { useTranslation } from 'react-i18next';
+import type { BotDirectMessageThreadResult } from '@cindy/maker-shared/botDirectMessage';
+import { Text } from '@/components/AppText';
+import { MainWindowActionButton } from '@/components/MobilePrimitives';
+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
+import { useRemoteCompanionQuery } from '@/session/useRemoteCompanionQuery';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { spacing, typeScale } from '@/theme/tokens';
+import { goBackGuarded } from '@/utils/backGuard';
+
+export default function CompanionDirectMessages() {
+ const params = useLocalSearchParams<{ deviceId: string; botId: string; threadId: string }>();
+ const deviceId = typeof params.deviceId === 'string' ? params.deviceId : '';
+ const botId = typeof params.botId === 'string' ? params.botId : '';
+ const threadId = typeof params.threadId === 'string' ? params.threadId : '';
+ const { t } = useTranslation();
+ const router = useRouter();
+ const styles = useThemedStyles(makeStyles);
+ const { subscribe, unsubscribe } = useDeviceLink();
+ const { value, error, online, refresh } = useRemoteCompanionQuery<BotDirectMessageThreadResult>(deviceId, 'maker:bot-direct-message-thread:get', [threadId, botId]);
+ useFocusEffect(useCallback(() => startFocusedTopicSubscription({ deviceId, owner: `companion-direct:${threadId}`, topic: 'sessions', subscribe, unsubscribe }), [deviceId, threadId, subscribe, unsubscribe]));
+ const thread = value?.ok ? value.thread : null;
+ return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.screen}>
+ <SimpleStackHeader title={thread ? `${thread.botAName} · ${thread.botBName}` : t('devices.companions.messages')} subtitle={t('devices.companions.readOnly')} onBack={() => goBackGuarded(router)} />
+ <ScrollView contentContainerStyle={styles.content}>
+ {!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text> : null}
+ {thread?.messages.map((message) => <Text selectable key={message.id} style={styles.message}>{`${message.senderBotName}\n${message.content}`}</Text>)}
+ {!thread && online ? <Text style={styles.note}>{error || value?.ok === false ? t('devices.companions.actionFailed') : t('devices.resources.loading')}</Text> : null}
+ {error || value?.ok === false ? <MainWindowActionButton action={{ label: t('devices.resources.retry'), onPress: refresh }} /> : null}
+ </ScrollView>
+ </SafeAreaView>;
+}
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ screen: { flex: 1, backgroundColor: colors.surface },
+ content: { padding: spacing.lg, gap: spacing.lg },
+ message: { color: colors.textPrimary, fontSize: typeScale.body, backgroundColor: colors.surfaceElevated, padding: spacing.md },
+ note: { color: colors.textSecondary, fontSize: typeScale.footnote },
+});
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 0fd729a0cf..aaec681d4e 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -1,3 +1,4 @@
+import { cacheRemoteResourceHome, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';
import { useFocusEffect, useIsFocused } from 'expo-router';
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react';
import {
@@ -74,6 +75,7 @@ import {
import {
buildHomeDisplayPullDownActions,
buildHomeScopePullDownActions,
+ parseHomeScopePullDownAction,
homeDisplayMenuPatch,
type HomeDisplayMenuKey,
} from '@/session/homeChromeMenus';
@@ -82,6 +84,12 @@ import { buildMainWindowLayout } from '@/components/mainWindowLayout';
import { useScreenEdgePadding } from '@/components/screenEdgeInsets';
import { isAccessRevokedError } from '@/device-link/accessRevoked';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import {
+ discoverRemoteHomeCollections,
+ remoteResourceDiscoveryTargets,
+ serializeRemoteResourceTargets,
+ type RemoteHomeCollection,
+} from '@/device-link/remoteResources';
import {
createEmptyDeviceIdentityCache,
loadDeviceIdentityCache,
@@ -424,6 +432,10 @@ function HomeScreenContent() {
const [error, setError] = useState<string | null>(null);
const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(null);
+ const [remoteHomeCollections, setRemoteHomeCollections] = useState<RemoteHomeCollection[]>([]);
+ const [resourceCacheAccount, setResourceCacheAccount] = useState<number | null>(null);
+ const remoteHomeCollectionsRef = useRef<RemoteHomeCollection[]>([]);
+ remoteHomeCollectionsRef.current = remoteHomeCollections;
const selectedDeviceIdRef = useRef<string | null>(selectedDeviceId);
selectedDeviceIdRef.current = selectedDeviceId;
const [searchOpen, setSearchOpen] = useState(false);
@@ -1446,6 +1458,57 @@ function HomeScreenContent() {
statusDetail: item.statusDetail,
statusLabel: item.statusLabel,
})), [deviceRows]);
+ useEffect(() => {
+ let cancelled = false;
+ remoteHomeCollectionsRef.current = [];
+ setRemoteHomeCollections([]);
+ setResourceCacheAccount(null);
+ void readRemoteResourceSnapshot(homeCacheUserId).then((snapshot) => {
+ if (cancelled) return;
+ remoteHomeCollectionsRef.current = snapshot.home;
+ setRemoteHomeCollections(snapshot.home);
+ setResourceCacheAccount(accountGeneration);
+ });
+ return () => { cancelled = true; };
+ }, [accountGeneration, homeCacheUserId]);
+ useEffect(() => {
+ if (resourceCacheAccount !== accountGeneration || !homeListCacheHydrated || (deviceModels.length === 0 && lastSyncedAt === null)) return;
+ let cancelled = false;
+ const targets = remoteResourceDiscoveryTargets(deviceModels, remoteHomeCollectionsRef.current);
+ if (targets.length === 0) {
+ remoteHomeCollectionsRef.current = [];
+ setRemoteHomeCollections([]);
+ return () => { cancelled = true; };
+ }
+ void discoverRemoteHomeCollections(
+ invoke,
+ targets,
+ i18nInstance.language,
+ remoteHomeCollectionsRef.current,
+ )
+ .then((collections) => {
+ if (!cancelled && homeAccountGenerationRef.current === accountGeneration) {
+ remoteHomeCollectionsRef.current = collections;
+ setRemoteHomeCollections(collections);
+ void cacheRemoteResourceHome(homeCacheUserId, collections);
+ }
+ })
+ .catch(() => {
+ // Optional capability discovery must not turn a healthy Sessions home into an error page.
+ // Keep the last same-account manifest during transient link failures.
+ });
+ return () => { cancelled = true; };
+ }, [
+ accountGeneration,
+ connectionEpoch,
+ resourceCacheAccount,
+ lastSyncedAt,
+ homeListCacheHydrated,
+ homeCacheUserId,
+ deviceModels,
+ i18nInstance.language,
+ invoke,
+ ]);
useEffect(() => {
remoteSessionStore.setConversationSearchDeviceModels(deviceModels.map((item) => ({
canOpen: item.canOpen,
@@ -2302,13 +2365,31 @@ function HomeScreenContent() {
() => buildHomeScopePullDownActions(
home.deviceFilters,
t('devices.list.allConversations'),
+ remoteHomeCollections.map((collection) => ({
+ id: collection.id,
+ title: collection.title,
+ })),
),
- [home.deviceFilters, t],
+ [home.deviceFilters, remoteHomeCollections, t],
);
const handleHomeScopeAction = useCallback((id: string) => {
- const item = home.deviceFilters.find((filter) => filter.id === id);
+ const parsed = parseHomeScopePullDownAction(id);
+ if (parsed.kind === 'collection') {
+ const collection = remoteHomeCollections.find((item) => item.id === parsed.collectionId);
+ if (!collection) return;
+ guardedPush({
+ pathname: '/resources/[collectionId]',
+ params: {
+ collectionId: collection.id,
+ title: collection.title,
+ targets: serializeRemoteResourceTargets(collection.targets),
+ },
+ });
+ return;
+ }
+ const item = home.deviceFilters.find((filter) => filter.id === parsed.filterId);
if (item) selectHomeScope(item);
- }, [home.deviceFilters, selectHomeScope]);
+ }, [guardedPush, home.deviceFilters, remoteHomeCollections, selectHomeScope]);
const homeDisplayPullDownActions = useMemo(
() => buildHomeDisplayPullDownActions({
groupByProject,
@@ -2623,10 +2704,22 @@ function HomeScreenContent() {
}}
/>
<DeviceMenuModal
+ collections={remoteHomeCollections}
connectionStates={deviceConnectionStates}
filters={home.deviceFilters}
onClose={() => setDeviceMenuOpen(false)}
onClosed={handleDeviceMenuClosed}
+ onSelectCollection={(collection) => {
+ setDeviceMenuOpen(false);
+ guardedPush({
+ pathname: '/resources/[collectionId]',
+ params: {
+ collectionId: collection.id,
+ title: collection.title,
+ targets: serializeRemoteResourceTargets(collection.targets),
+ },
+ });
+ }}
onSelect={(item) => {
if (item.deviceId && item.state === 'access_revoked') {
// 撤销授权提示同样是兄弟 Modal,必须等菜单卸载后再挂(见 pendingMenuActionRef 注释)。
@@ -2765,24 +2858,29 @@ function HomeInitialLoadingState({ style }: { style?: StyleProp<ViewStyle> }) {
}
function DeviceMenuModal({
+ collections,
connectionStates,
filters,
onClose,
onClosed,
onSelect,
+ onSelectCollection,
topOffset,
visible,
}: {
+ collections: readonly RemoteHomeCollection[];
connectionStates: Record<string, HomeDeviceConnectionState>;
filters: readonly MobileHomeDeviceFilterItem[];
onClose(): void;
/** 淡出动画完成、Modal 真正卸载后触发;父级用它把「打开第二个 Modal」延后到菜单卸载之后。 */
onClosed?(): void;
onSelect(item: MobileHomeDeviceFilterItem): void;
+ onSelectCollection(item: RemoteHomeCollection): void;
topOffset: number;
visible: boolean;
}) {
const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
const { t } = useTranslation();
const { height: screenHeight } = useWindowDimensions();
const insets = useSafeAreaInsets();
@@ -2822,6 +2920,18 @@ function DeviceMenuModal({
testID="home.deviceChip.all"
/>
) : null}
+ {collections.map((collection) => (
+ <DeviceMenuItem
+ icon={collection.iconName === 'users'
+ ? <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ : undefined}
+ key={`collection:${collection.id}`}
+ label={collection.title}
+ onPress={() => onSelectCollection(collection)}
+ selected={false}
+ testID={`home.remoteCollection.${collection.id}`}
+ />
+ ))}
{deviceFilters.map((item) => (
<DeviceMenuItem
connectionState={item.deviceId ? connectionStates[item.deviceId] ?? 'idle' : 'idle'}
diff --git a/apps/mobile/app/resources/[collectionId].tsx b/apps/mobile/app/resources/[collectionId].tsx
new file mode 100644
index 0000000000..a2442db292
--- /dev/null
+++ b/apps/mobile/app/resources/[collectionId].tsx
@@ -0,0 +1,321 @@
+import { cacheRemoteResourceItems, readRemoteResourceSnapshot, isRemoteResourceUnread, subscribeRemoteResourceCache, remoteResourceCacheRevision } from '@/device-link/remoteResourceCache';
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import {
+ ActivityIndicator,
+ AppState,
+ FlatList,
+ Pressable,
+ RefreshControl,
+ StyleSheet,
+ View,
+} from 'react-native';
+import { ChevronRight } from 'lucide-react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { useTranslation } from 'react-i18next';
+import {
+ resolveRemoteText,
+} from '@cindy/device-link';
+
+import { Text } from '@/components/AppText';
+import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
+import { MainWindowEmptyState, StatusDot } from '@/components/MobilePrimitives';
+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';
+import { useAuth } from '@/auth/AuthContext';
+import { isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import {
+ type HostedRemoteCollectionItem,
+ listRemoteCollection,
+ mergeRemoteCollectionHostShards,
+ normalizeRemoteCollectionItems,
+ parseRemoteResourceTargets,
+} from '@/device-link/remoteResources';
+import { formatRemoteError } from '@/device-link/remoteStatus';
+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
+import { goBackGuarded } from '@/utils/backGuard';
+import { useGuardedPush } from '@/utils/useGuardedPush';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, iconSize, iconStroke, radius, spacing, typeScale } from '@/theme/tokens';
+
+type HostedResourceItem = HostedRemoteCollectionItem;
+
+function timestampLabel(value: number | undefined, locale: string): string | null {
+ if (!value || !Number.isFinite(value) || !Number.isFinite(new Date(value).getTime())) return null;
+ return new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ }).format(new Date(value));
+}
+
+export default function RemoteCollectionScreen() {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t, i18n } = useTranslation();
+ const router = useRouter();
+ const guardedPush = useGuardedPush();
+ const params = useLocalSearchParams<{
+ collectionId?: string;
+ title?: string;
+ targets?: string;
+ }>();
+ const collectionId = Array.isArray(params.collectionId)
+ ? params.collectionId[0] ?? ''
+ : params.collectionId ?? '';
+ const title = Array.isArray(params.title) ? params.title[0] : params.title;
+ const targets = useMemo(() => parseRemoteResourceTargets(params.targets), [params.targets]);
+ const {
+ connectionEpoch,
+ status: relayStatus,
+ presenceVersion,
+ getPresenceAvailability,
+ invoke,
+ onRemoteResourceChanged,
+ subscribe,
+ unsubscribe,
+ } = useDeviceLink();
+ const { accountGeneration, user } = useAuth();
+ useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);
+ const [hydratedOwner, setHydratedOwner] = useState('');
+ const cacheOwner = `${user?.id ?? ''}:${accountGeneration}`;
+ const accountRef = useRef(accountGeneration);
+ accountRef.current = accountGeneration;
+ const [replyEpochs, setReplyEpochs] = useState<Record<string, number>>({});
+ const presenceKey = targets.map((host) => `${host.deviceId}:${getPresenceAvailability(host.deviceId)}`).join('|');
+ // Reading presenceVersion makes the authoritative availability projection reactive.
+ void presenceVersion;
+ const [itemsAccount, setItemsAccount] = useState(accountGeneration);
+ const [items, setItems] = useState<HostedResourceItem[]>(() => readRemoteCollectionCache(cacheOwner, collectionId));
+ const loadGenerationRef = useRef(0);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(async (visible: boolean) => {
+ if (hydratedOwner !== cacheOwner) return;
+ const generation = ++loadGenerationRef.current;
+ const expectedAccount = accountGeneration;
+ if (!collectionId || targets.length === 0) {
+ setItems([]);
+ setError(t('devices.resources.noHosts'));
+ setLoading(false);
+ return;
+ }
+ if (visible) setRefreshing(true);
+ else setLoading(true);
+ const results = await Promise.allSettled(targets.map(async (host) => {
+ if (relayStatus !== 'online' || getPresenceAvailability(host.deviceId) === false) throw new Error(t('devices.resources.hostOffline'));
+ return { host, response: await listRemoteCollection(invoke, host, collectionId, i18n.language) };
+ }));
+ if (loadGenerationRef.current !== generation || accountRef.current !== expectedAccount) return;
+ const next: HostedResourceItem[] = [];
+ const failures: string[] = [];
+ const successfulDeviceIds = new Set<string>();
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ failures.push(formatRemoteError(result.reason));
+ continue;
+ }
+ successfulDeviceIds.add(result.value.host.deviceId);
+ const rawItems = normalizeRemoteCollectionItems(result.value.response, collectionId);
+ for (const item of rawItems) {
+ next.push({
+ key: `${result.value.host.deviceId}:${item.ref.kind}:${item.ref.id}`,
+ host: result.value.host,
+ item,
+ });
+ }
+ }
+ setReplyEpochs(Object.fromEntries([...successfulDeviceIds].map((id) => [id, connectionEpoch])));
+ const allHostsFailed = failures.length === targets.length;
+ setItemsAccount(expectedAccount);
+ setItems((current) => {
+ const merged = mergeRemoteCollectionHostShards(current, next, successfulDeviceIds, targets);
+ writeRemoteCollectionCache(cacheOwner, collectionId, merged);
+ void cacheRemoteResourceItems(user?.id ?? '', collectionId, merged);
+ return merged;
+ });
+ setError(allHostsFailed ? failures.slice(0, 2).join('\n') : null);
+ setLoading(false);
+ setRefreshing(false);
+ }, [accountGeneration, cacheOwner, collectionId, connectionEpoch, getPresenceAvailability, hydratedOwner, i18n.language, invoke, relayStatus, t, targets, presenceKey, user?.id]);
+
+ useEffect(() => {
+ loadGenerationRef.current += 1;
+ setItems(readRemoteCollectionCache(cacheOwner, collectionId));
+ setItemsAccount(accountGeneration);
+ setReplyEpochs({});
+ let cancelled = false;
+ void readRemoteResourceSnapshot(user?.id ?? '').then((snapshot) => {
+ if (cancelled) return;
+ setItems((current) => current.length ? current : snapshot.items[collectionId] ?? []);
+ setHydratedOwner(cacheOwner);
+ });
+ return () => { cancelled = true; };
+ }, [accountGeneration, cacheOwner, collectionId, user?.id]);
+
+ useFocusEffect(useCallback(() => {
+ void load(false);
+ return () => { loadGenerationRef.current += 1; };
+ }, [connectionEpoch, load]));
+ useFocusEffect(useCallback(() => {
+ const subscription = AppState.addEventListener('change', (state) => {
+ if (state === 'active') void load(false);
+ });
+ return () => subscription.remove();
+ }, [load]));
+ useFocusEffect(useCallback(() => {
+ if (!collectionId) return undefined;
+ const cleanups = targets.map((target) => startFocusedTopicSubscription({
+ deviceId: target.deviceId,
+ owner: `remote-collection:${collectionId}:${target.deviceId}`,
+ subscribe,
+ topic: 'sessions',
+ unsubscribe,
+ }));
+ return () => {
+ for (const cleanup of cleanups) cleanup();
+ };
+ }, [collectionId, subscribe, targets, unsubscribe]));
+ useEffect(() => onRemoteResourceChanged((deviceId, payload) => {
+ if (
+ payload.collectionId === collectionId
+ && targets.some((target) => target.deviceId === deviceId)
+ ) {
+ void load(false);
+ }
+ }), [collectionId, load, onRemoteResourceChanged, targets]);
+
+ const openItem = useCallback((hosted: HostedResourceItem) => {
+ if (!isRemoteResourceHostOnline(relayStatus, getPresenceAvailability(hosted.host.deviceId), replyEpochs[hosted.host.deviceId], connectionEpoch)) return;
+ guardedPush({
+ pathname: '/resources/[collectionId]/[resourceId]',
+ params: {
+ collectionId,
+ deviceId: hosted.host.deviceId,
+ deviceName: hosted.host.deviceName,
+ resourceId: hosted.item.ref.id,
+ resourceKind: hosted.item.ref.kind,
+ title: resolveRemoteText(hosted.item.display.title, i18n.language),
+ },
+ });
+ }, [collectionId, connectionEpoch, getPresenceAvailability, guardedPush, i18n.language, relayStatus, replyEpochs]);
+
+ return (
+ <SafeAreaView
+ edges={simpleScreenSafeAreaEdges()}
+ style={styles.safeArea}
+ testID="remoteResources.screen"
+ >
+ <SimpleStackHeader
+ backTestID="remoteResources.backButton"
+ onBack={() => goBackGuarded(router)}
+ subtitle={targets.length > 1 ? t('devices.resources.hostCount', { count: targets.length }) : targets[0]?.deviceName}
+ title={title || t('devices.resources.titleFallback')}
+ titleTestID="remoteResources.title"
+ />
+ {loading && items.length === 0 ? (
+ <View style={styles.center}>
+ <ActivityIndicator color={colors.textSecondary} />
+ <Text style={styles.muted}>{t('devices.resources.loading')}</Text>
+ </View>
+ ) : (
+ <FlatList
+ contentContainerStyle={items.length === 0 ? styles.emptyContent : styles.listContent}
+ data={itemsAccount === accountGeneration ? items : []}
+ keyExtractor={(item) => item.key}
+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => void load(true)} />}
+ renderItem={({ item: hosted }) => {
+ const display = hosted.item.display;
+ const titleText = resolveRemoteText(display.title, i18n.language);
+ const subtitle = display.preview
+ ? resolveRemoteText(display.preview, i18n.language)
+ : display.subtitle
+ ? resolveRemoteText(display.subtitle, i18n.language)
+ : '';
+ const online = isRemoteResourceHostOnline(relayStatus, getPresenceAvailability(hosted.host.deviceId), replyEpochs[hosted.host.deviceId], connectionEpoch);
+ const status = !online ? t('devices.resources.hostOffline') : display.status
+ ? resolveRemoteText(display.status.label, i18n.language)
+ : '';
+ const unread = hosted.item.ref.kind === 'bot' && isRemoteResourceUnread(user?.id ?? '', hosted.host.deviceId, hosted.item.ref.id, display.lastReplyAt);
+ const time = timestampLabel(display.timestamp, i18n.language);
+ return (
+ <Pressable
+ accessibilityLabel={[titleText, subtitle, status].filter(Boolean).join(', ')}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: !online }}
+ disabled={!online}
+ onPress={() => openItem(hosted)}
+ style={({ pressed }) => [styles.row, pressed && styles.pressed]}
+ testID={`remoteResources.item.${hosted.item.ref.id}`}
+ >
+ <View style={styles.avatar}>
+ <RemoteCompanionAvatar avatar={display.avatar} deviceId={hosted.host.deviceId} name={titleText} online={online} />
+ <View style={styles.connectionDot}><StatusDot tone={online ? 'ready' : 'off'} /></View>
+ </View>
+ <View style={styles.body}>
+ <View style={styles.titleRow}>
+ <Text numberOfLines={1} style={styles.title}>{titleText}</Text>
+ {unread ? <View accessibilityLabel={t('devices.companions.unread')} style={styles.unread} /> : null}
+ {time ? <Text numberOfLines={1} style={styles.time}>{time}</Text> : null}
+ </View>
+ {subtitle ? <Text numberOfLines={1} style={styles.subtitle}>{subtitle}</Text> : null}
+ <Text numberOfLines={1} style={styles.meta}>
+ {[status, targets.length > 1 ? hosted.host.deviceName : ''].filter(Boolean).join(' · ')}
+ </Text>
+ </View>
+ <ChevronRight color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ );
+ }}
+ ListEmptyComponent={(
+ <MainWindowEmptyState
+ copy={error ?? t('devices.resources.emptyCopy')}
+ testID={error ? 'remoteResources.error' : 'remoteResources.empty'}
+ title={error ? t('devices.resources.loadFailed') : t('devices.resources.emptyTitle')}
+ />
+ )}
+ />
+ )}
+ </SafeAreaView>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ safeArea: { backgroundColor: colors.surface, flex: 1 },
+ center: { alignItems: 'center', flex: 1, gap: spacing.sm, justifyContent: 'center' },
+ muted: { color: colors.textSecondary, fontSize: typeScale.footnote },
+ listContent: { gap: spacing.sm, padding: spacing.md },
+ emptyContent: { flexGrow: 1, justifyContent: 'center', padding: spacing.xl },
+ row: {
+ alignItems: 'center',
+ backgroundColor: colors.surfaceListRow,
+ borderColor: colors.border,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ flexDirection: 'row',
+ gap: spacing.md,
+ minHeight: 78,
+ paddingHorizontal: spacing.md,
+ paddingVertical: spacing.sm,
+ },
+ pressed: { opacity: 0.72 },
+ unread: { width: 7, height: 7, borderRadius: radius.pill, backgroundColor: colors.statusAwaiting },
+ connectionDot: { position: 'absolute', bottom: 0, right: 0 },
+ avatar: {
+ alignItems: 'center',
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.pill,
+ height: 44,
+ justifyContent: 'center',
+ width: 44,
+ },
+ body: { flex: 1, gap: spacing.xs, minWidth: 0 },
+ titleRow: { alignItems: 'baseline', flexDirection: 'row', gap: spacing.sm },
+ title: { color: colors.textPrimary, flex: 1, fontSize: typeScale.listTitle, fontWeight: fontWeight.semibold },
+ time: { color: colors.textTertiary, fontSize: typeScale.footnote },
+ subtitle: { color: colors.textSecondary, fontSize: typeScale.body },
+ meta: { color: colors.textTertiary, fontSize: typeScale.footnote },
+});
diff --git a/apps/mobile/app/resources/[collectionId]/[resourceId].tsx b/apps/mobile/app/resources/[collectionId]/[resourceId].tsx
new file mode 100644
index 0000000000..0d1cf94a5c
--- /dev/null
+++ b/apps/mobile/app/resources/[collectionId]/[resourceId].tsx
@@ -0,0 +1,144 @@
+import { useAuth } from '@/auth/AuthContext';
+import { useLocalSearchParams, useRouter } from 'expo-router';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { ActivityIndicator, StyleSheet, View } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { useTranslation } from 'react-i18next';
+import type { RemoteSessionLinkTarget } from '@cindy/device-link';
+
+import { Text } from '@/components/AppText';
+import { MainWindowActionButton, MainWindowEmptyState } from '@/components/MobilePrimitives';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { getRemoteResource, type RemoteResourceHostTarget } from '@/device-link/remoteResources';
+import { formatRemoteError } from '@/device-link/remoteStatus';
+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { RemoteSession } from '@/session/types';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { spacing, typeScale } from '@/theme/tokens';
+import { goBackGuarded } from '@/utils/backGuard';
+
+function firstParam(value: string | string[] | undefined): string {
+ return Array.isArray(value) ? value[0] ?? '' : value ?? '';
+}
+
+export default function RemoteResourceResolverScreen() {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t, i18n } = useTranslation();
+ const router = useRouter();
+ const { invoke, connectionEpoch } = useDeviceLink();
+ const { accountGeneration } = useAuth();
+ const binding = `${accountGeneration}:${connectionEpoch}`;
+ const currentBinding = useRef(binding); currentBinding.current = binding;
+ const params = useLocalSearchParams<{
+ collectionId?: string;
+ resourceId?: string;
+ resourceKind?: string;
+ deviceId?: string;
+ deviceName?: string;
+ title?: string;
+ }>();
+ const collectionId = firstParam(params.collectionId);
+ const resourceId = firstParam(params.resourceId);
+ const resourceKind = firstParam(params.resourceKind);
+ const deviceId = firstParam(params.deviceId);
+ const deviceName = firstParam(params.deviceName) || deviceId;
+ const title = firstParam(params.title) || t('devices.resources.titleFallback');
+ const host = useMemo<RemoteResourceHostTarget>(
+ () => ({ deviceId, deviceName }),
+ [deviceId, deviceName],
+ );
+ const [error, setError] = useState<string | null>(null);
+ const [attempt, setAttempt] = useState(0);
+ const resolveGenerationRef = useRef(0);
+
+ const resolveConversation = useCallback(async () => {
+ const generation = ++resolveGenerationRef.current;
+ setError(null);
+ if (!collectionId || !resourceId || !resourceKind || !deviceId) {
+ setError(t('devices.resources.noHosts'));
+ return;
+ }
+ try {
+ // Resolve the opaque resource again on every open. A desktop module may
+ // roll its canonical Session without invalidating the permanent route.
+ const response = await getRemoteResource(invoke, host, {
+ collectionId,
+ id: resourceId,
+ kind: resourceKind,
+ }, i18n.language);
+ if (resolveGenerationRef.current !== generation || currentBinding.current !== binding) return;
+ const link = response.links.find((item) => item.rel === 'conversation');
+ const target = link?.target as RemoteSessionLinkTarget | undefined;
+ if (!target || target.kind !== 'session' || typeof target.sessionId !== 'string') {
+ setError(t('devices.resources.noConversation'));
+ return;
+ }
+ const session = await invoke<RemoteSession>(deviceId, 'local-db:sessions:get', [target.sessionId]);
+ if (resolveGenerationRef.current !== generation || currentBinding.current !== binding) return;
+ if (!session || session.id !== target.sessionId || (resourceKind === 'bot' && session.source !== 'bot')) throw new Error(t('devices.resources.noConversation'));
+ const existingOrigin = remoteSessionStore.getSessionDeviceId(session.id);
+ if (existingOrigin && existingOrigin !== deviceId) throw new Error(t('devices.resources.noConversation'));
+ remoteSessionStore.upsertDeviceSession(deviceId, deviceName, session);
+ router.replace({
+ pathname: '/sessions/[sessionId]',
+ params: {
+ deviceId,
+ deviceName,
+ sessionId: target.sessionId,
+ resourceCollectionId: collectionId,
+ resourceId,
+ resourceKind,
+ },
+ });
+ } catch (cause) {
+ if (resolveGenerationRef.current === generation) setError(formatRemoteError(cause));
+ }
+ }, [binding, collectionId, deviceId, deviceName, host, i18n.language, invoke, resourceId, resourceKind, router, t]);
+
+ useEffect(() => {
+ void resolveConversation();
+ return () => { resolveGenerationRef.current += 1; };
+ }, [attempt, resolveConversation]);
+
+ return (
+ <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="remoteResourceResolver.screen">
+ <SimpleStackHeader
+ backTestID="remoteResourceResolver.backButton"
+ onBack={() => goBackGuarded(router)}
+ subtitle={deviceName}
+ title={title}
+ titleTestID="remoteResourceResolver.title"
+ />
+ {error ? (
+ <View style={styles.content}>
+ <MainWindowEmptyState
+ copy={error}
+ testID="remoteResourceResolver.error"
+ title={t('devices.resources.openFailed')}
+ />
+ <MainWindowActionButton
+ action={{
+ label: t('devices.resources.retry'),
+ onPress: () => setAttempt((value) => value + 1),
+ testID: 'remoteResourceResolver.retry',
+ }}
+ />
+ </View>
+ ) : (
+ <View style={styles.center}>
+ <ActivityIndicator color={colors.textSecondary} />
+ <Text style={styles.muted}>{t('devices.resources.resolving')}</Text>
+ </View>
+ )}
+ </SafeAreaView>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ safeArea: { backgroundColor: colors.surface, flex: 1 },
+ center: { alignItems: 'center', flex: 1, gap: spacing.sm, justifyContent: 'center' },
+ content: { flex: 1, gap: spacing.lg, justifyContent: 'center', padding: spacing.xl },
+ muted: { color: colors.textSecondary, fontSize: typeScale.footnote },
+});
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 18b6350654..83dd046d48 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
import { isInFlightDeviceLinkError } from '@cindy/device-link';
import { takeRefinementContextTail, truncateRefinementReply } from '@cindy/voice-input-core';
import {
@@ -165,6 +166,7 @@ import {
type SessionExtraDirBrowserState,
} from '@/session/SessionMenuSheet';
import type { SessionMenuView } from '@/session/sessionMenu';
+import { isHostManagedSession } from '@/session/hostManagedSession';
import {
interactionKind,
isPendingInteractionCollapsed,
@@ -1936,6 +1938,7 @@ export default function SessionScreen() {
() => sessions.find((item) => item.id === sessionId) ?? null,
[sessionId, sessions],
);
+ const sessionManagedByHost = isHostManagedSession(currentSession);
const localCodexRateLimitControl = canUseLocalCodexRateLimitControl(currentSession);
const isDeviceAccessRevoked = !!deviceId && revokedDevices.has(deviceId);
// 熔断 open:被控电脑「进程活着但不回包」的半死态;relay status 恒 online,必须单独入参。
@@ -2098,6 +2101,12 @@ export default function SessionScreen() {
() => remoteSessionStore.getSessionLiveActivity(sessionId)?.attention === true,
);
const hasRenderedMessages = messages.length > 0;
+ useRemoteResourceSession(deviceId, deviceName, sessionId,
+ currentSession?.id === sessionId && hasRenderedMessages
+ && readAckSyncedKey === `${sessionId}:${connectionEpoch}`
+ // A pre-ACK snapshot may omit replies sent before the subscription took effect.
+ && contentRecoveryKey !== null && contentSyncedKey === contentRecoveryKey
+ && !outboxRecoverySyncHeld && !loading);
const lastAckKeyRef = useRef<string | null>(null);
// AppState 门槛:锁屏 / 切后台时导航焦点不变,useFocusEffect 的 cleanup 不会跑,
// 驻留计时器可能在没有真实前台展示的情况下(甚至后台恢复补跑时)发出 explicit
@@ -2857,6 +2866,18 @@ export default function SessionScreen() {
setPermissionSheetOpen(false);
}, [canUseRemoteSessionControls]);
+ useEffect(() => {
+ if (!sessionManagedByHost) return;
+ setSettingsOpen(false);
+ setModelSheetOpen(false);
+ setSessionTreeOpen(false);
+ setSessionTreePendingOpen(false);
+ if (contextSheetView !== 'main') {
+ setContextSheetView('main');
+ setContextSheetOpen(false);
+ }
+ }, [contextSheetView, sessionManagedByHost]);
+
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextState) => {
if (nextState !== 'active') void flushComposerDraftWrites();
@@ -6564,7 +6585,7 @@ export default function SessionScreen() {
<ComposerToolbarLeftGroup testID="session.composerToolbarLeft">
{renderComposerAttachmentButton()}
{renderSessionPermissionButton()}
- {planModeOn ? (
+ {!sessionManagedByHost && planModeOn ? (
<PlanModeChip
disabled={controlBusy || !canUseRemoteSessionControls}
onExit={() => togglePlanMode(false)}
@@ -6573,7 +6594,7 @@ export default function SessionScreen() {
) : null}
{composerRuntimeSummary ? (
<ComposerRuntimePill
- disabled={controlBusy || !canUseRemoteSessionControls}
+ disabled={sessionManagedByHost || controlBusy || !canUseRemoteSessionControls}
fastOn={composerPillFastOn}
label={composerRuntimeLabel}
leading={agentSwitchIntent && composerSwitchesAgent ? (
@@ -7923,7 +7944,7 @@ export default function SessionScreen() {
}
}, [agentSwitchIntent, maker, modelSheetAgentKind, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);
const toggleComposerModelPicker = useCallback(() => {
- if (!canUseRemoteSessionControls) {
+ if (sessionManagedByHost || !canUseRemoteSessionControls) {
setModelSheetOpen(false);
return;
}
@@ -7933,7 +7954,7 @@ export default function SessionScreen() {
}
setModelSheetAgentKind(agentSwitchIntent?.targetAgentKind ?? sessionAgentKind);
setModelSheetOpen(true);
- }, [agentSwitchIntent, canUseRemoteSessionControls, modelSheetOpen, sessionAgentKind]);
+ }, [agentSwitchIntent, canUseRemoteSessionControls, modelSheetOpen, sessionAgentKind, sessionManagedByHost]);
// 账号限额按需拉取(会话信息面板打开时):优先走 Codex app-server 权威控制面,
// 同时拿窗口和 reset credits。老被控端没有新通道时回退既有只读 usage channel;
@@ -8696,6 +8717,7 @@ export default function SessionScreen() {
) : undefined}
syncing={showSyncingIndicator}
messageCount={Math.max(messages.length, currentSession?._count?.messages ?? 0)}
+ messageOnly={sessionManagedByHost}
onBack={goBackToHome}
onOpenSessionList={wideSessionNav.enabled ? openSessionListDrawer : undefined}
sessionListButtonRef={sessionListButtonRef}
@@ -8746,7 +8768,7 @@ export default function SessionScreen() {
) : null}
</View>
</View>
- {currentSession ? (
+ {currentSession && !sessionManagedByHost ? (
<SessionMenuSheet
usageReader={maker}
accountUsage={localCodexRateLimitControl ? accountUsage : null}
@@ -8857,7 +8879,7 @@ export default function SessionScreen() {
testID="session.contextSheetPhotos"
/>
) : null}
- <ContextSheetGroup label={t('session.common.groupMode')}>
+ {!sessionManagedByHost ? <ContextSheetGroup label={t('session.common.groupMode')}>
{planModeSupported ? (
// 点击即切换计划模式并关面板(产品决策,不做开关);已开启时显示 ✓,再点退出。
<ContextSheetRow
@@ -8887,7 +8909,7 @@ export default function SessionScreen() {
</>
) : 'chevron'}
/>
- </ContextSheetGroup>
+ </ContextSheetGroup> : null}
<ContextSheetGroup label={t('session.common.groupAdd')}>
<ContextSheetRow
accessibilityHint={composerSendUnavailableReason ?? undefined}
@@ -8962,7 +8984,7 @@ export default function SessionScreen() {
/>
)}
</ContextSheet>
- {currentSession && runtimeOptions && modelSheetSelection && modelSheetRuntimeOptions ? (
+ {currentSession && !sessionManagedByHost && runtimeOptions && modelSheetSelection && modelSheetRuntimeOptions ? (
<ModelPickerSheet
activeModelId={modelSheetSelection.model}
existingSessionRoute
@@ -9469,6 +9491,7 @@ function SessionHeaderBar({
shareSelectAllNode,
syncing,
messageCount,
+ messageOnly,
onBack,
onOpenFiles,
onOpenSessionList,
@@ -9493,6 +9516,8 @@ function SessionHeaderBar({
shareSelectAllNode?: ReactNode;
syncing: boolean;
messageCount: number;
+ /** Host-managed canonical Sessions expose conversation controls only. */
+ messageOnly: boolean;
onBack(): void;
/** 宽屏导航形态下提供:左上角改为三条杠,点击拉出任务列表抽屉(替代返回)。 */
onOpenSessionList?: () => void;
@@ -9529,7 +9554,9 @@ function SessionHeaderBar({
const actionProjection = overview ? projectMobileSessionActions(overview.actions) : null;
// queue 入口已退役:排队消息 inline 到消息流(InlineQueueSection),不再有独立面板。
const headerActions = (actionProjection?.primaryActions ?? [])
- .filter((action) => action.id !== 'settings' && action.id !== 'queue');
+ .filter((action) => action.id !== 'settings'
+ && action.id !== 'queue'
+ && (!messageOnly || action.id === 'search' || action.id === 'files'));
const actionHandlers = {
files: onOpenFiles,
queue: () => undefined,
@@ -9585,7 +9612,7 @@ function SessionHeaderBar({
<View style={styles.sessionHeaderTextBlock}>
<View style={styles.sessionHeaderTitleRow}>
- {currentSession?.pinnedAt ? (
+ {!messageOnly && currentSession?.pinnedAt ? (
<Pin
color={colors.textTertiary}
size={iconSize.sm}
@@ -9617,14 +9644,14 @@ function SessionHeaderBar({
testID={SESSION_ACTION_TEST_IDS[action.id]}
/>
))}
- <SessionHeaderIconButton
+ {!messageOnly ? <SessionHeaderIconButton
accessibilityLabel={t('session.screen.openSessionMenu')}
active={false}
disabled={!currentSession}
icon={Ellipsis}
onPress={currentSession ? onOpenSettings : undefined}
testID="session.controlsToggle"
- />
+ /> : null}
</View>
</View>
);
diff --git a/apps/mobile/assets/bot-presets/cindy.png b/apps/mobile/assets/bot-presets/cindy.png
new file mode 100644
index 0000000000..18c2d2a0ae
Binary files /dev/null and b/apps/mobile/assets/bot-presets/cindy.png differ
diff --git a/apps/mobile/assets/bot-presets/dash.png b/apps/mobile/assets/bot-presets/dash.png
new file mode 100644
index 0000000000..24a4a3986c
Binary files /dev/null and b/apps/mobile/assets/bot-presets/dash.png differ
diff --git a/apps/mobile/assets/bot-presets/lizi.png b/apps/mobile/assets/bot-presets/lizi.png
new file mode 100644
index 0000000000..bbdbbb4138
Binary files /dev/null and b/apps/mobile/assets/bot-presets/lizi.png differ
diff --git a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx
new file mode 100644
index 0000000000..41da2ef9cd
--- /dev/null
+++ b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+import { act, createElement, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({ invoke: vi.fn(), push: vi.fn(), changed: null as any, status: 'online', accountGeneration: 1, epoch: 1 }));
+vi.mock('react-native', () => ({
+ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
+ View: ({ children }: any) => createElement('div', {}, children),
+ Pressable: ({ children, onPress, disabled }: any) => createElement('button', { onClick: onPress, disabled }, children),
+ StyleSheet: { create: (v: any) => v, hairlineWidth: 1 },
+}));
+vi.mock('expo-router', () => ({ useFocusEffect: (cb: () => void) => useEffect(cb, [cb]), useLocalSearchParams: () => ({ deviceId: 'home' }), useRouter: () => ({ push: h.push }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/components/AppText', () => ({ Text: ({ children }: any) => createElement('span', {}, children) }));
+vi.mock('@/theme', () => ({ useThemedStyles: () => ({}) }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: h.accountGeneration }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({ invoke: h.invoke, status: h.status, connectionEpoch: h.epoch, getPresenceAvailability: () => true }),
+ subscribeRemoteBotChanges: (fn: any) => { h.changed = fn; return () => { h.changed = null; }; },
+}));
+import { CompanionMessageCard } from '@/session/CompanionMessageCard';
+import type { NormalizedRemoteMessage } from '@/session/messageNormalize';
+const message = { source: { sessionId: 'parent' }, companion: { kind: 'task', meta: { role: 'delegation-request', delegationId: 'job', childSessionId: 'child', objective: 'Report' } } } as NormalizedRemoteMessage;
+let root: Root;
+let node: HTMLDivElement;
+const render = async () => { await act(async () => root.render(createElement(CompanionMessageCard, { message }))); };
+beforeEach(() => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ node = document.createElement('div'); document.body.append(node); root = createRoot(node);
+ h.accountGeneration = 1; h.epoch = 1; h.status = 'online'; h.invoke.mockReset(); h.push.mockReset();
+ h.invoke.mockResolvedValue({ ok: true, delegations: [{ id: 'job', status: 'running', title: 'Report', childSessionId: 'child' }] });
+});
+afterEach(async () => { await act(async () => root.unmount()); node.remove(); vi.useRealTimers(); });
+it('reads, opens and stops the task on its source computer, then disables stop offline', async () => {
+ await render();
+ expect(h.invoke).toHaveBeenCalledWith('home', 'maker:bot-delegations:list', ['parent']);
+ const button = (label: string) => [...node.querySelectorAll('button')].find((b) => b.textContent === label)!;
+ await act(async () => button('devices.companions.openTask').click());
+ expect(h.push).toHaveBeenCalledWith({ pathname: '/sessions/[sessionId]', params: { deviceId: 'home', sessionId: 'child' } });
+ await act(async () => button('devices.companions.stopTask').click());
+ expect(h.invoke).toHaveBeenCalledWith('home', 'maker:bot-delegation:cancel', ['parent', 'job']);
+ h.status = 'reconnecting'; await render();
+ expect(button('devices.companions.stopTask').disabled).toBe(true);
+});
+it('ignores another peer push and refreshes the actual task to completed', async () => {
+ await render(); vi.useFakeTimers();
+ h.invoke.mockResolvedValue({ ok: true, delegations: [{ id: 'job', status: 'completed', title: 'Report', resultSummary: 'Report finished' }] });
+ await act(async () => { h.changed('office', 'maker:bot-delegation:changed', { parentSessionId: 'parent' }); await vi.advanceTimersByTimeAsync(400); });
+ expect(h.invoke).toHaveBeenCalledTimes(1);
+ await act(async () => { h.changed('home', 'maker:bot-delegation:changed', { parentSessionId: 'parent' }); await vi.advanceTimersByTimeAsync(400); });
+ expect(node.textContent).toContain('Report finished');
+ expect(node.textContent).not.toContain('devices.companions.stopTask');
+});
+it('does not render an old account response after account and connection change', async () => {
+ let finish!: (value: unknown) => void;
+ h.invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ await render(); h.accountGeneration = 2; h.epoch = 2; h.status = 'offline'; await render();
+ await act(async () => finish({ ok: true, delegations: [{ id: 'job', title: 'Old private account', status: 'running' }] }));
+ expect(node.textContent).not.toContain('Old private account');
+});
diff --git a/apps/mobile/src/__tests__/homeChromeMenus.test.ts b/apps/mobile/src/__tests__/homeChromeMenus.test.ts
index 53f7599994..5ee5cbe2fc 100644
--- a/apps/mobile/src/__tests__/homeChromeMenus.test.ts
+++ b/apps/mobile/src/__tests__/homeChromeMenus.test.ts
@@ -4,6 +4,7 @@ import {
buildHomeDisplayPullDownActions,
buildHomeScopeMenuItems,
buildHomeScopePullDownActions,
+ parseHomeScopePullDownAction,
homeDisplayMenuPatch,
} from "@/session/homeChromeMenus";
import type { MobileHomeDeviceFilterItem } from "@/session/mobileHome";
@@ -39,6 +40,29 @@ describe("home chrome menus", () => {
expect(actions.every((item) => !item.subactions)).toBe(true);
});
+ it("places host-advertised collections beside All Sessions", () => {
+ const actions = buildHomeScopePullDownActions(
+ [
+ filter({ id: "all", label: "全部任务", selected: true }),
+ filter({ id: "mac", label: "MacBook", deviceId: "d1" }),
+ ],
+ "所有任务",
+ [{ id: "teammates", title: "所有伙伴" }],
+ );
+
+ expect(actions.map((item) => item.id)).toEqual([
+ "all",
+ "scope.collection:teammates",
+ "mac",
+ ]);
+ expect(parseHomeScopePullDownAction("scope.collection:teammates")).toEqual({
+ kind: "collection",
+ collectionId: "teammates",
+ });
+ expect(actions[2]).toEqual({ id: "mac", title: "MacBook", state: "off" });
+ expect(parseHomeScopePullDownAction("mac")).toEqual({ kind: "select", filterId: "mac" });
+ });
+
it("lists all-conversations and available devices, marking the selected one", () => {
const items = buildHomeScopeMenuItems(
[
diff --git a/apps/mobile/src/__tests__/hostManagedSession.test.ts b/apps/mobile/src/__tests__/hostManagedSession.test.ts
new file mode 100644
index 0000000000..5dc786a0ec
--- /dev/null
+++ b/apps/mobile/src/__tests__/hostManagedSession.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { isHostManagedSession } from '@/session/hostManagedSession';
+
+describe('host-managed Session presentation', () => {
+ it('trusts the authoritative Session source instead of route metadata', () => {
+ expect(isHostManagedSession({ source: 'bot' })).toBe(true);
+ expect(isHostManagedSession({ source: 'desktop' })).toBe(false);
+ expect(isHostManagedSession(null)).toBe(false);
+ });
+
+ it('hides host-owned settings while preserving permission controls and the composer', () => {
+ const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+ expect(source).toContain('const sessionManagedByHost = isHostManagedSession(currentSession);');
+ expect(source).toContain('messageOnly={sessionManagedByHost}');
+ expect(source).toContain('currentSession && !sessionManagedByHost ? (');
+ expect(source).toContain('{renderSessionPermissionButton()}');
+ expect(source).toContain('currentSession && runtimeOptions ? (');
+ expect(source).not.toContain('!sessionManagedByHost ? renderSessionPermissionButton() : null');
+ expect(source).toContain('{composerRuntimeSummary ? (');
+ expect(source).toContain('if (sessionManagedByHost || !canUseRemoteSessionControls)');
+ expect(source).toContain('{renderComposerAttachmentButton()}');
+ expect(source).toContain('{renderComposerInlineStop()}');
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 74ec780ad7..6be623bab8 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -1336,3 +1336,20 @@ describe('normalizeRemoteMessages — /goal 持久记录与 plan_review 状态',
expect(items[0].label).toBe('plan_review:cancelled');
});
});
+
+
+describe('companion timeline', () => {
+ it('preserves empty task anchors and private thread links for the mobile renderer', () => {
+ const task = { v: 1, role: 'delegation-request', delegationId: 'job', fromBotId: 'bot', fromBotName: 'Writer', toBotId: null, toBotName: 'Cindy', parentSessionId: 's1', childSessionId: 'child', objective: 'Write report' };
+ const direct = { v: 1, threadId: 'private', viewerBotId: 'bot', peerBotId: 'peer', peerBotName: 'Dash', direction: 'sent', sequence: 1, preview: 'Discuss report' };
+ const rows = normalizeRemoteMessages([
+ message({ id: 'task', role: 'assistant', content: '', agentMeta: { botCollaboration: task } }),
+ message({ id: 'direct', role: 'assistant', content: '', agentMeta: { botDirectMessage: direct } }),
+ message({ id: 'invalid', role: 'assistant', content: 'Regular reply', agentMeta: { botDirectMessage: { ...direct, v: 2 } } }),
+ ]);
+ expect(rows[0]).toMatchObject({ kind: 'system', companion: { kind: 'task', meta: task }, source: { sessionId: 's1' } });
+ expect(rows[1]).toMatchObject({ kind: 'system', companion: { kind: 'direct', meta: direct } });
+ expect(rows[2]).toMatchObject({ kind: 'assistant', body: 'Regular reply' });
+ expect(rows[2].companion).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx b/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx
new file mode 100644
index 0000000000..a1cd8a5c9b
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ push: vi.fn(), markRead: vi.fn(),
+ params: { collectionId: 'teammates', targets: JSON.stringify([{ deviceId: 'mac', deviceName: 'My Mac' }]) },
+ translation: { t: (key: string) => key, i18n: { language: 'en' } },
+ link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: () => true, invoke: vi.fn(), onRemoteResourceChanged: () => () => {}, subscribe: vi.fn(), unsubscribe: vi.fn() },
+ item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' }, revision: '1', display: { title: 'Writer', preview: 'Unread reply', lastReplyAt: 200 } },
+}));
+vi.mock('react-native', async () => {
+ const { createElement: el, Fragment } = await import('react');
+ const view = ({ children, testID }: any) => el('div', { 'data-testid': testID }, children);
+ return {
+ View: view, ActivityIndicator: view, RefreshControl: () => null,
+ Pressable: ({ children, testID, onPress, disabled }: any) => el('button', { 'data-testid': testID, onClick: onPress, disabled }, children),
+ FlatList: ({ data, renderItem, ListEmptyComponent }: any) => data.length ? el(Fragment, {}, ...data.map((item: any) => el(Fragment, { key: item.key }, renderItem({ item })))) : ListEmptyComponent,
+ StyleSheet: { create: (styles: unknown) => styles },
+ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
+ };
+});
+vi.mock('expo-router', async () => {
+ const { useEffect } = await import('react');
+ return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]), useLocalSearchParams: () => h.params, useRouter: () => ({}) };
+});
+vi.mock('react-i18next', () => ({ useTranslation: () => h.translation }));
+vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: 'div' }));
+vi.mock('lucide-react-native', () => ({ ChevronRight: () => null }));
+vi.mock('@/components/AppText', () => ({ Text: 'span' }));
+vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
+vi.mock('@/components/MobilePrimitives', () => ({ MainWindowEmptyState: () => null, StatusDot: () => null }));
+vi.mock('@/platform/chrome', () => ({ SimpleStackHeader: () => null, simpleScreenSafeAreaEdges: () => [] }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: 1 }) }));
+vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));
+vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => h.push }));
+vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));
+vi.mock('@/device-link/remoteResourceAvailability', () => ({ isRemoteResourceHostOnline: () => true, readRemoteCollectionCache: () => [], writeRemoteCollectionCache: () => {} }));
+vi.mock('@/device-link/remoteResourceCache', () => ({
+ cacheRemoteResourceItems: vi.fn(), readRemoteResourceSnapshot: async () => ({ items: {} }),
+ isRemoteResourceUnread: () => true, markRemoteResourceRead: h.markRead,
+ subscribeRemoteResourceCache: () => () => {}, remoteResourceCacheRevision: () => 0,
+}));
+vi.mock('@/device-link/remoteResources', async (original) => ({
+ ...await original<typeof import('@/device-link/remoteResources')>(),
+ listRemoteCollection: async () => ({ collectionId: 'teammates', revision: '1', items: [h.item] }),
+}));
+import RemoteCollectionScreen from '../../app/resources/[collectionId]';
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+it('opening a companion only navigates; unread survives until the destination confirms content display', async () => {
+ const container = document.createElement('div');
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(createElement(RemoteCollectionScreen)));
+ const button = container.querySelector<HTMLButtonElement>('[data-testid="remoteResources.item.bot-1"]');
+ expect(button).not.toBeNull();
+ await act(async () => button!.click());
+ expect(h.push).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/resources/[collectionId]/[resourceId]' }));
+ expect(h.markRead).not.toHaveBeenCalled();
+ } finally { act(() => root.unmount()); }
+});
diff --git a/apps/mobile/src/__tests__/remoteResourceAvailability.test.ts b/apps/mobile/src/__tests__/remoteResourceAvailability.test.ts
new file mode 100644
index 0000000000..ae332d096b
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteResourceAvailability.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';
+
+describe('remote resource availability', () => {
+ it('one offline host does not disconnect other hosts', () => {
+ expect(isRemoteResourceHostOnline('online', false, 4, 4)).toBe(false);
+ expect(isRemoteResourceHostOnline('online', true, 4, 4)).toBe(true);
+ });
+ it('does not reuse a reply from an earlier connection or fabricate first-contact availability', () => {
+ expect(isRemoteResourceHostOnline('online', null, 3, 4)).toBe(false);
+ expect(isRemoteResourceHostOnline('online', null, undefined, 4)).toBe(false);
+ expect(isRemoteResourceHostOnline('online', null, 4, 4)).toBe(true);
+ });
+ it('relay disconnect takes all hosted resources offline', () => {
+ expect(isRemoteResourceHostOnline('reconnecting', true, 4, 4)).toBe(false);
+ expect(isRemoteResourceHostOnline('stopped', true, 4, 4)).toBe(false);
+ });
+});
+
+it('retains a roster across navigation but never across account generations', () => {
+ const rows = [{ key: 'a:bot:writer' }] as Parameters<typeof writeRemoteCollectionCache>[2];
+ readRemoteCollectionCache('account:1', 'teammates');
+ writeRemoteCollectionCache('account:1', 'teammates', rows);
+ expect(readRemoteCollectionCache('account:1', 'teammates')).toEqual(rows);
+ expect(readRemoteCollectionCache('account:2', 'teammates')).toEqual([]);
+ writeRemoteCollectionCache('account:1', 'teammates', rows);
+ expect(readRemoteCollectionCache('account:2', 'teammates')).toEqual([]);
+});
diff --git a/apps/mobile/src/__tests__/remoteResourceCache.test.ts b/apps/mobile/src/__tests__/remoteResourceCache.test.ts
new file mode 100644
index 0000000000..7f8f88c51b
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteResourceCache.test.ts
@@ -0,0 +1,41 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+const disk = vi.hoisted(() => new Map<string, string>());
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {
+ getItem: vi.fn(async (key: string) => disk.get(key) ?? null),
+ setItem: vi.fn(async (key: string, value: string) => { disk.set(key, value); }),
+ removeItem: vi.fn(async (key: string) => { disk.delete(key); }),
+ getAllKeys: vi.fn(async () => [...disk.keys()]),
+ multiRemove: vi.fn(async (keys: string[]) => { keys.forEach((key) => disk.delete(key)); }),
+} }));
+import { cacheRemoteResourceHome, cacheRemoteResourceItems, clearRemoteResourceCache, isRemoteResourceUnread, markRemoteResourceRead, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';
+const rows = (deviceId: string, lastReplyAt: number) => [{
+ key: `${deviceId}:bot:writer`, host: { deviceId, deviceName: deviceId },
+ item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt }, revision: '1', links: [] },
+}];
+beforeEach(async () => { await clearRemoteResourceCache(); disk.clear(); });
+it('keeps device-qualified read positions and treats only later host replies as unread', async () => {
+ await cacheRemoteResourceItems('alice', 'teammates', [...rows('home', 100), ...rows('office', 100)]);
+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 100)).toBe(false);
+ await cacheRemoteResourceItems('alice', 'teammates', [...rows('home', 200), ...rows('office', 100)]);
+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(true);
+ expect(isRemoteResourceUnread('alice', 'office', 'writer', 100)).toBe(false);
+ await markRemoteResourceRead('alice', 'home', 'writer', 200);
+ await markRemoteResourceRead('alice', 'home', 'writer', 100);
+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(false);
+ expect((await readRemoteResourceSnapshot('bob')).items).toEqual({});
+});
+it('restores portable roster data after process restart and never persists runtime facts', async () => {
+ await cacheRemoteResourceHome('alice', [{ id: 'teammates', title: 'Companions', resourceKind: 'bot', targets: [{ deviceId: 'home', deviceName: 'Home' }] }]);
+ const items = rows('home', 100);
+ Object.assign(items[0].item, { permissionSnapshot: { secret: 'private' }, online: true });
+ await cacheRemoteResourceItems('alice', 'teammates', items);
+ vi.resetModules();
+ const fresh = await import('@/device-link/remoteResourceCache');
+ const restored = await fresh.readRemoteResourceSnapshot('alice');
+ expect(restored.home[0].targets[0].deviceId).toBe('home');
+ expect(restored.items.teammates[0].item.display.title).toBe('Writer');
+ expect(JSON.stringify(restored)).not.toContain('permissionSnapshot');
+ expect(JSON.stringify(restored)).not.toContain('online');
+ await fresh.clearRemoteResourceCache();
+ expect(disk.size).toBe(0);
+});
diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.ts
new file mode 100644
index 0000000000..110fb9894a
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteResources.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it, vi } from 'vitest';
+import { DeviceLinkError } from '@cindy/device-link';
+
+import {
+ MOBILE_REMOTE_RESOURCE_PRIMITIVES,
+ discoverRemoteHomeCollections,
+ remoteResourceDiscoveryTargets,
+ isRemoteResourcesUnsupported,
+ mergeRemoteCollectionHostShards,
+ normalizeRemoteCollectionItems,
+ parseRemoteResourceTargets,
+ serializeRemoteResourceTargets,
+} from '@/device-link/remoteResources';
+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';
+
+const targets = [
+ { deviceId: 'mac-1', deviceName: 'Studio' },
+ { deviceId: 'mac-2', deviceName: 'Laptop' },
+];
+
+describe('remote resource discovery', () => {
+ it('keeps a discovered offline host while excluding revoked and disabled hosts', async () => {
+ const previous = [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', targets }];
+ const selected = remoteResourceDiscoveryTargets([
+ { deviceId: 'mac-1', name: 'Studio', canOpen: false, state: 'offline' },
+ { deviceId: 'mac-2', name: 'Laptop', canOpen: false, state: 'access_revoked' },
+ { deviceId: 'mac-3', name: 'Disabled', canOpen: false, state: 'remote_disabled' },
+ ], previous);
+ expect(selected).toEqual([targets[0]]);
+ const invoke = vi.fn(async () => { throw new Error('offline'); }) as RemoteInvoke;
+ const collections = await discoverRemoteHomeCollections(invoke, selected, 'en', previous);
+ expect(collections[0]?.targets).toEqual([targets[0]]);
+ });
+
+ it('advertises only primitives implemented by the current mobile shell', () => {
+ expect(MOBILE_REMOTE_RESOURCE_PRIMITIVES).toEqual(['status', 'session-link']);
+ });
+
+ it('merges host-advertised home collections without knowing their feature module', async () => {
+ const invoke = vi.fn(async (deviceId: string) => ({
+ protocolVersion: 1,
+ collections: [{
+ id: 'teammates',
+ resourceKind: 'bot',
+ placement: 'home-scope',
+ title: {
+ fallback: 'Teammates',
+ translations: { 'zh-CN': '所有伙伴' },
+ },
+ futureField: deviceId,
+ }],
+ })) as RemoteInvoke;
+
+ await expect(discoverRemoteHomeCollections(invoke, targets, 'zh-CN')).resolves.toEqual([{
+ id: 'teammates',
+ title: '所有伙伴',
+ resourceKind: 'bot',
+ placement: 'home-scope',
+ iconName: undefined,
+ targets,
+ }]);
+ });
+
+ it('surfaces an all-host transient failure so callers can retain their last manifest', async () => {
+ const invoke = vi.fn(async () => {
+ throw new Error('temporarily offline');
+ }) as RemoteInvoke;
+
+ await expect(discoverRemoteHomeCollections(invoke, targets, 'en'))
+ .rejects.toThrow('temporarily offline');
+ });
+
+ it('treats an old host as unsupported while retaining collections from newer hosts', async () => {
+ const invoke = vi.fn(async (deviceId: string) => {
+ if (deviceId === 'mac-1') throw new DeviceLinkError('CHANNEL_NOT_ALLOWED', 'old desktop');
+ return {
+ protocolVersion: 1,
+ collections: [{
+ id: 'future-module',
+ resourceKind: 'future-resource',
+ placement: 'home-scope',
+ title: 'Future module',
+ }],
+ };
+ }) as RemoteInvoke;
+
+ await expect(discoverRemoteHomeCollections(invoke, targets, 'en')).resolves.toMatchObject([{
+ id: 'future-module',
+ targets: [{ deviceId: 'mac-2' }],
+ }]);
+ expect(isRemoteResourcesUnsupported(
+ Object.assign(new Error('wrapped'), { code: 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' }),
+ )).toBe(true);
+ });
+
+ it('keeps the last manifest when unsupported hosts are mixed with a transient failure', async () => {
+ const invoke = vi.fn(async (deviceId: string) => {
+ if (deviceId === 'mac-1') throw new DeviceLinkError('CHANNEL_NOT_ALLOWED', 'old desktop');
+ throw new Error('temporarily offline');
+ }) as RemoteInvoke;
+
+ await expect(discoverRemoteHomeCollections(invoke, targets, 'en'))
+ .rejects.toThrow('temporarily offline');
+ });
+
+ it('retains a failed host manifest shard when another supported host returns empty', async () => {
+ const invoke = vi.fn(async (deviceId: string) => {
+ if (deviceId === 'mac-1') throw new Error('temporarily offline');
+ return { protocolVersion: 1, collections: [] };
+ }) as RemoteInvoke;
+ const previous = [{
+ id: 'teammates',
+ title: 'Teammates',
+ resourceKind: 'bot',
+ placement: 'home-scope',
+ targets: [targets[0]],
+ }];
+
+ await expect(discoverRemoteHomeCollections(invoke, targets, 'en', previous))
+ .resolves.toEqual(previous);
+ });
+});
+
+describe('remote resource response boundaries', () => {
+ it('keeps valid additive items and drops malformed or cross-collection items', () => {
+ expect(normalizeRemoteCollectionItems({ items: [
+ {
+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' },
+ display: { title: 'Cindy', futureDisplay: true },
+ links: [],
+ revision: '1',
+ futureField: true,
+ },
+ {
+ ref: { collectionId: 'other', kind: 'bot', id: 'bot-2' },
+ display: { title: 'Wrong scope' },
+ links: [],
+ revision: '1',
+ },
+ { display: null },
+ ] }, 'teammates')).toHaveLength(1);
+ });
+
+ it('normalizes hostile optional display and link fields before rendering', () => {
+ const [item] = normalizeRemoteCollectionItems({ items: [{
+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' },
+ display: {
+ title: 'Cindy',
+ timestamp: 9e15,
+ avatar: { kind: 'emoji', value: { boom: true }, fallbackText: 'C' },
+ status: { label: 42 },
+ },
+ links: [
+ { rel: 'conversation', target: { kind: 'session', sessionId: 42 } },
+ { rel: 'conversation', target: { kind: 'session', sessionId: 'session-1' } },
+ ],
+ revision: '1',
+ }] }, 'teammates');
+
+ expect(item).toEqual({
+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' },
+ display: { title: 'Cindy' },
+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'session-1' } }],
+ revision: '1',
+ });
+ });
+
+ it('replaces only successful host shards and preserves provider order', () => {
+ const item = (deviceId: string, id: string) => ({
+ key: `${deviceId}:${id}`,
+ host: targets.find((target) => target.deviceId === deviceId)!,
+ item: {
+ ref: { collectionId: 'teammates', kind: 'bot', id },
+ display: { title: id },
+ links: [],
+ revision: '1',
+ },
+ });
+ const current = [item('mac-1', 'stale-1'), item('mac-2', 'old-2')];
+ const next = [item('mac-2', 'provider-first'), item('mac-2', 'provider-second')];
+
+ expect(mergeRemoteCollectionHostShards(
+ current,
+ next,
+ new Set(['mac-2']),
+ targets,
+ ).map((entry) => entry.item.ref.id)).toEqual([
+ 'stale-1',
+ 'provider-first',
+ 'provider-second',
+ ]);
+ });
+});
+
+describe('remote resource route targets', () => {
+ it('round-trips bounded host identities and rejects malformed params', () => {
+ expect(parseRemoteResourceTargets(serializeRemoteResourceTargets(targets))).toEqual(targets);
+ expect(parseRemoteResourceTargets('{broken')).toEqual([]);
+ expect(parseRemoteResourceTargets(JSON.stringify([{ deviceId: '', deviceName: 'Nope' }])))
+ .toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
new file mode 100644
index 0000000000..504791b300
--- /dev/null
+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ get: vi.fn(),
+ markRead: vi.fn(),
+ store: { getSessionDeviceId: vi.fn(), upsertDeviceSession: vi.fn() },
+ router: { replace: vi.fn(), setParams: vi.fn() },
+ auth: { user: { id: 'owner' }, accountGeneration: 1 },
+ link: { invoke: vi.fn(), connectionEpoch: 1, status: 'online', onRemoteResourceChanged: vi.fn(() => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },
+}));
+vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));
+vi.mock('expo-router', async () => {
+ const { useEffect } = await import('react');
+ return {
+ useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]),
+ useLocalSearchParams: () => ({ resourceCollectionId: 'teammates', resourceId: 'bot-1', resourceKind: 'bot' }),
+ useRouter: () => h.router,
+ };
+});
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/device-link/remoteResources', () => ({ getRemoteResource: h.get }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ markRemoteResourceRead: h.markRead }));
+vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: h.store }));
+import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
+// Evaluate the real screen's hook argument so this regression also catches a
+// missing recovery fence at the call site, rather than testing a copied gate.
+const screen = ts.createSourceFile('screen.tsx', readFileSync(
+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8',
+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+function screenReadGate(contentRecoveryKey: string | null, contentSyncedKey: string | null): boolean {
+ let argument: ts.Expression | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node) && node.expression.getText(screen) === 'useRemoteResourceSession') argument = node.arguments[3];
+ ts.forEachChild(node, visit);
+ };
+ visit(screen);
+ if (!argument) throw new Error('Missing production companion read gate');
+ const compiled = ts.transpileModule(`const gate = ${argument.getText(screen)};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return new Function('contentRecoveryKey', 'contentSyncedKey', `
+ const currentSession = { id: 'task-1' }, sessionId = 'task-1', connectionEpoch = 1;
+ const hasRenderedMessages = true, readAckSyncedKey = 'task-1:1', outboxRecoverySyncHeld = false, loading = false;
+ ${compiled}
+ return gate;
+ `)(contentRecoveryKey, contentSyncedKey);
+}
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+function Probe({ canMarkRead }: { canMarkRead: boolean }) { useRemoteResourceSession('mac', 'My Mac', 'task-1', canMarkRead); return null; }
+async function render(canMarkRead = false) {
+ root ??= createRoot(document.createElement('div'));
+ await act(async () => root!.render(createElement(Probe, { canMarkRead })));
+}
+beforeEach(() => { vi.clearAllMocks(); h.auth.accountGeneration = 1; h.store.getSessionDeviceId.mockReturnValue(undefined); });
+afterEach(() => { act(() => root?.unmount()); root = undefined; });
+
+describe('companion task visibility refresh', () => {
+ it('does not mark read until the entered task has rendered its synchronized history', async () => {
+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { lastReplyAt: 200 } });
+ await render(false);
+ expect(h.markRead).not.toHaveBeenCalled();
+ await render(true);
+ expect(h.markRead).toHaveBeenCalledWith('owner', 'mac', 'bot-1', 200);
+ });
+ it('keeps the gap reply unread until the snapshot after the exact subscription ACK is applied', async () => {
+ // Old history has rendered and the ordinary read ACK gate is open, but the
+ // resource already advertises a reply produced in the subscription gap.
+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { lastReplyAt: 200 } });
+ await render(screenReadGate(null, null));
+ expect(h.markRead).not.toHaveBeenCalled();
+ const ack = JSON.stringify(['mac', 'task-1', 1, 7]);
+ await render(screenReadGate(ack, null)); // ACK arrived; recovery read pending.
+ expect(h.markRead).not.toHaveBeenCalled();
+ await render(screenReadGate(ack, JSON.stringify(['mac', 'task-1', 1, 6])));
+ expect(h.markRead).not.toHaveBeenCalled(); // A prior ACK snapshot is insufficient.
+ await render(screenReadGate(ack, ack)); // Gap reply has now been applied.
+ expect(h.markRead).toHaveBeenCalledExactlyOnceWith('owner', 'mac', 'bot-1', 200);
+ });
+ it.each(['resource', 'link', 'session', 'disconnect'])('preserves unread when opening fails at %s', async (stage) => {
+ h.get.mockResolvedValue({ links: stage === 'link' ? [] : [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-2' } }], display: { lastReplyAt: 200 } });
+ if (stage === 'resource') h.get.mockRejectedValue(new Error('[NOT_FOUND] missing'));
+ h.link.invoke.mockRejectedValue(new Error(stage === 'disconnect' ? 'NOT_CONNECTED' : '[NOT_FOUND] missing task'));
+ await render(true);
+ expect(h.markRead).not.toHaveBeenCalled();
+ });
+ it('waits for the replacement task to enter instead of clearing unread on navigation', async () => {
+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-2' } }], display: { lastReplyAt: 200 } });
+ h.link.invoke.mockResolvedValue({ id: 'task-2', source: 'bot' });
+ await render(true);
+ expect(h.router.setParams).toHaveBeenCalledWith({ sessionId: 'task-2' });
+ expect(h.markRead).not.toHaveBeenCalled();
+ });
+ it.each([Object.assign(new Error('gone'), { code: 'NOT_FOUND' }), new Error('[NOT_FOUND] resource missing')])('leaves the cached task when the host rejects the resource', async (error) => {
+ h.get.mockRejectedValue(error);
+ await render();
+ expect(h.router.replace).toHaveBeenCalledWith({ pathname: '/resources/[collectionId]/[resourceId]', params: {
+ collectionId: 'teammates', resourceId: 'bot-1', resourceKind: 'bot', deviceId: 'mac', deviceName: 'My Mac',
+ } });
+ });
+ it('retains recovery for a transient connection failure', async () => {
+ h.get.mockRejectedValue(new Error('NOT_CONNECTED'));
+ await render();
+ expect(h.router.replace).not.toHaveBeenCalled();
+ });
+ it('ignores a visibility rejection belonging to the previous account', async () => {
+ let reject!: (error: Error) => void;
+ h.get.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail; }));
+ await render();
+ h.get.mockReturnValueOnce(new Promise(() => {}));
+ h.auth.accountGeneration = 2;
+ await render();
+ await act(async () => reject(new Error('[NOT_FOUND] old owner')));
+ expect(h.router.replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 6761a91c31..e6e9d95102 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -116,6 +116,7 @@ import {
import { unregisterPushTokenBestEffort } from '@/notifications/pushNotifications';
import { resetAgentCapabilitiesCache } from '@/session/agentCapabilitiesCache';
import { resetComposerPaletteCache } from '@/session/composerPaletteCache';
+import { clearRemoteResourceCache } from '@/device-link/remoteResourceCache';
import { clearCachedHomeListSnapshot } from '@/session/mobileHomeListCache';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { clearCachedSessionMessages } from '@/session/mobileSessionMessageCache';
@@ -849,6 +850,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
clearAllMobileVoiceInputHistories().catch(() => undefined),
clearAllMobileVoiceDictionaryCaches().catch(() => undefined),
clearCachedSessionMessages().catch(() => undefined),
+ clearRemoteResourceCache().catch(() => undefined),
clearCachedHomeListSnapshot().catch(() => undefined),
]);
resetComposerPaletteCache();
@@ -2579,6 +2581,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
await clearAllMobileVoiceDictionaryCaches().catch(() => undefined);
await clearCachedSessionMessages().catch(() => undefined);
// 首页设备+会话快照与消息缓存一样属于账号数据,登出必须清掉。
+ await clearRemoteResourceCache().catch(() => undefined);
await clearCachedHomeListSnapshot().catch(() => undefined);
resetComposerPaletteCache();
resetAgentCapabilitiesCache();
diff --git a/apps/mobile/src/components/RemoteCompanionAvatar.tsx b/apps/mobile/src/components/RemoteCompanionAvatar.tsx
new file mode 100644
index 0000000000..3081dc8057
--- /dev/null
+++ b/apps/mobile/src/components/RemoteCompanionAvatar.tsx
@@ -0,0 +1,44 @@
+import { useEffect, useState } from 'react';
+import { Image, StyleSheet } from 'react-native';
+import type { RemoteResourceAvatar } from '@cindy/device-link';
+import { Text } from '@/components/AppText';
+import { useAuth } from '@/auth/AuthContext';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';
+import { resolveMobileRemoteMedia, type MobileRemoteMediaPresignResult } from '@/session/remoteMedia';
+import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
+import { useTheme } from '@/theme';
+import { radius, typeScale } from '@/theme/tokens';
+
+const presets: Record<string, number> = {
+ 'cindy://avatar/preset/cindy': require('../../assets/bot-presets/cindy.png'),
+ 'cindy://avatar/preset/dash': require('../../assets/bot-presets/dash.png'),
+ 'cindy://avatar/preset/lizi': require('../../assets/bot-presets/lizi.png'),
+};
+
+export function RemoteCompanionAvatar({ avatar, deviceId, name, online }: { avatar?: RemoteResourceAvatar; deviceId: string; name: string; online: boolean }) {
+ const { colors } = useTheme();
+ const auth = useAuth();
+ const { invoke } = useDeviceLink();
+ const value = avatar?.value || '';
+ const binding = `${auth.accountGeneration}:${deviceId}:${value}`;
+ const [image, setImage] = useState<{ binding: string; uri: string } | null>(null);
+ const [failed, setFailed] = useState(false);
+ useEffect(() => {
+ let cancelled = false;
+ setFailed(false);
+ if (avatar?.kind !== 'media' || !online) return;
+ const maker = createMobileMakerTransport({ deviceId, invoke });
+ void resolveMobileRemoteMedia({ kind: 'image', url: value }, {
+ fetchRemoteMedia: maker.fetchRemoteMedia,
+ presignGet: (key) => auth.apiFetch<MobileRemoteMediaPresignResult>('/api/device-link/media/presign-get', { baseUrl: DEVICE_LINK_API_BASE_URL, method: 'POST', body: { key } }),
+ }, { thumbnail: true }).then((result) => {
+ if (!cancelled && result.previewable && result.mimeType.startsWith('image/')) setImage({ binding, uri: result.url });
+ }).catch(() => undefined);
+ return () => { cancelled = true; };
+ }, [auth.apiFetch, avatar?.kind, binding, deviceId, invoke, online, value]);
+ const source = presets[value] || (image?.binding === binding ? { uri: image.uri } : null);
+ if (source && !failed) return <Image source={source} onError={() => setFailed(true)} style={styles.image} />;
+ return <Text style={{ color: colors.textPrimary, fontSize: typeScale.body }}>{avatar?.kind === 'emoji' ? value : avatar?.fallbackText || Array.from(name)[0]}</Text>;
+}
+const styles = StyleSheet.create({ image: { width: 40, height: 40, borderRadius: radius.pill } });
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 3a669efe28..1c4a3f200a 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -181,6 +181,7 @@ export function createVisualMockDeviceLinkContext(): DeviceLinkContextValue {
subscribe: async () => undefined,
unsubscribe: async () => undefined,
onAgentsChanged: () => () => undefined,
+ onRemoteResourceChanged: () => () => undefined,
};
}
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index e7a8e576d1..14d4ddc2a7 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -13,6 +13,8 @@ import {
DL_UNSUBSCRIBE_CHANNEL,
FILE_BROWSER_EVENT_CHANNEL,
PROTOCOL_VERSION,
+ REMOTE_RESOURCE_CHANGED_CHANNEL,
+ parseRemoteResourceChangedPayload,
type DeviceLinkConnectionIssue,
type DeviceLinkStatus,
type Envelope,
@@ -20,6 +22,7 @@ import {
type LinkAcceptPayload,
type PresenceSnapshot,
type PushPayload,
+ type RemoteResourceChangedPayload,
type Topic,
} from '@cindy/device-link';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
@@ -175,6 +178,10 @@ export interface DeviceLinkContextValue {
unsubscribe(owner: string, deviceId: string, topics: string[]): Promise<void>;
/** 被控端 runtime Agent roster 发生变化时通知当前控制端页面。 */
onAgentsChanged: (listener: (deviceId: string) => void) => () => void;
+ /** 模块中立的远程资源失效事件;页面收到后按 collection/ref 重拉。 */
+ onRemoteResourceChanged: (
+ listener: (deviceId: string, payload: RemoteResourceChangedPayload) => void,
+ ) => () => void;
}
const DeviceLinkContext = createContext<DeviceLinkContextValue | null>(null);
@@ -197,6 +204,16 @@ const CONTROLLER_CAPABILITIES = [
const remoteResponseEvidenceEpochs = createPresenceAvailabilityEpochs();
const remoteResponseEvidenceListeners = new Set<(deviceId: string) => void>();
const remoteAgentRosterListeners = new Set<(deviceId: string) => void>();
+const remoteBotChangedListeners = new Set<(deviceId: string, channel: string, payload: unknown) => void>();
+export function subscribeRemoteBotChanges(listener: (deviceId: string, channel: string, payload: unknown) => void): () => void {
+ remoteBotChangedListeners.add(listener);
+ return () => { remoteBotChangedListeners.delete(listener); };
+}
+
+const remoteResourceChangedListeners = new Set<(
+ deviceId: string,
+ payload: RemoteResourceChangedPayload,
+) => void>();
// 永久 link-close 后被抑制后台重建的设备(见 updateRehydrateSuppressionOnLinkClose)。
// 模块级(与 remoteResponseEvidenceEpochs 同模式):sendOpenLink 等模块级函数也需要
@@ -223,6 +240,13 @@ function subscribeRemoteAgentRoster(
return () => remoteAgentRosterListeners.delete(listener);
}
+function subscribeRemoteResourceChanged(
+ listener: (deviceId: string, payload: RemoteResourceChangedPayload) => void,
+): () => void {
+ remoteResourceChangedListeners.add(listener);
+ return () => remoteResourceChangedListeners.delete(listener);
+}
+
/**
* 退后台断开连接前的宽限:几秒内切回前台的快速 App 切换不触发整套
* 断连 → 重连 → 补齐,弱网下这套循环的代价远高于让 socket 多活两秒。
@@ -1255,6 +1279,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
subscribe,
unsubscribe,
onAgentsChanged: subscribeRemoteAgentRoster,
+ onRemoteResourceChanged: subscribeRemoteResourceChanged,
}), [
closeLink,
connectionEpoch,
@@ -1269,6 +1294,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
subscribe,
unsubscribe,
subscribeRemoteAgentRoster,
+ subscribeRemoteResourceChanged,
subscriptionVersion,
]);
@@ -1309,6 +1335,16 @@ export function routeFrame(env: Envelope, handlers: {
handlers.onAgentsChanged?.(env.src);
return;
}
+ if (push.channel === 'maker:bot-delegation:changed' || push.channel === 'maker:bot-direct-message:changed') {
+ for (const listener of remoteBotChangedListeners) listener(env.src, push.channel, push.payload);
+ return;
+ }
+ if (push.channel === REMOTE_RESOURCE_CHANGED_CHANNEL) {
+ const payload = parseRemoteResourceChangedPayload(push.payload);
+ if (!payload) return;
+ for (const listener of remoteResourceChangedListeners) listener(env.src, payload);
+ return;
+ }
if (push.channel === 'maker:schedule:event') {
remoteScheduleEventStore.apply(env.src, push.payload);
}
diff --git a/apps/mobile/src/device-link/remoteResourceAvailability.ts b/apps/mobile/src/device-link/remoteResourceAvailability.ts
new file mode 100644
index 0000000000..52e07d33e1
--- /dev/null
+++ b/apps/mobile/src/device-link/remoteResourceAvailability.ts
@@ -0,0 +1,25 @@
+import type { HostedRemoteCollectionItem } from './remoteResources';
+
+/** A host reply is evidence only for the connection in which it arrived. */
+export function isRemoteResourceHostOnline(
+ relayStatus: string,
+ presence: boolean | null,
+ replyEpoch: number | undefined,
+ connectionEpoch: number,
+): boolean {
+ return relayStatus === 'online' && presence !== false && replyEpoch === connectionEpoch;
+}
+
+let cacheOwner = '';
+const collections = new Map<string, HostedRemoteCollectionItem[]>();
+
+/** Keep the last roster across navigation, isolated to the current account generation. */
+export function readRemoteCollectionCache(owner: string, collectionId: string): HostedRemoteCollectionItem[] {
+ if (owner !== cacheOwner) { cacheOwner = owner; collections.clear(); }
+ return collections.get(collectionId) ?? [];
+}
+
+export function writeRemoteCollectionCache(owner: string, collectionId: string, items: HostedRemoteCollectionItem[]): void {
+ if (owner !== cacheOwner) return;
+ collections.set(collectionId, items);
+}
diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.ts
new file mode 100644
index 0000000000..cc652ab38f
--- /dev/null
+++ b/apps/mobile/src/device-link/remoteResourceCache.ts
@@ -0,0 +1,94 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { normalizeRemoteCollectionItems, parseRemoteResourceTargets, type HostedRemoteCollectionItem, type RemoteHomeCollection } from './remoteResources';
+
+const PREFIX = 'cindy.remoteResources.v1.';
+const MAX_CHARS = 256 * 1024;
+type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number> };
+const empty = (): Snapshot => ({ home: [], items: {}, read: {} });
+let epoch = 0;
+const writes = new Map<string, Promise<void>>();
+const snapshots = new Map<string, Snapshot>();
+const listeners = new Set<() => void>();
+let revision = 0;
+export const subscribeRemoteResourceCache = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
+export const remoteResourceCacheRevision = () => revision;
+const emit = () => { revision += 1; listeners.forEach((fn) => fn()); };
+
+/** Cache only portable display/link fields; availability is always live. */
+function normalize(raw: unknown): Snapshot {
+ const out = empty();
+ if (!raw || typeof raw !== 'object') return out;
+ const value = raw as Partial<Snapshot>;
+ if (Array.isArray(value.home)) for (const row of value.home.slice(0, 32)) {
+ if (!row || typeof row.id !== 'string' || row.id.length > 160 || typeof row.title !== 'string' || typeof row.resourceKind !== 'string') continue;
+ out.home.push({ id: row.id, title: row.title.slice(0, 512), resourceKind: row.resourceKind.slice(0,160), placement: 'home-scope', targets: parseRemoteResourceTargets(JSON.stringify(row.targets)) });
+ }
+ if (value.items && typeof value.items === 'object') for (const [id, rows] of Object.entries(value.items).slice(0, 32)) {
+ if (id.length > 160 || !Array.isArray(rows)) continue;
+ out.items[id] = rows.slice(0, 200).flatMap((row) => {
+ if (!row) return [];
+ const [host] = parseRemoteResourceTargets(JSON.stringify([row.host]));
+ const [item] = normalizeRemoteCollectionItems({ items: [row.item] }, id);
+ return host && item ? [{ host, item, key: JSON.stringify([host.deviceId, item.ref.kind, item.ref.id]) }] : [];
+ });
+ }
+ if (value.read && typeof value.read === 'object') for (const [key, at] of Object.entries(value.read).slice(-2000)) {
+ if (key.length <= 600 && typeof at === 'number' && Number.isFinite(at) && at >= 0) out.read[key] = at;
+ }
+ return out;
+}
+
+export async function readRemoteResourceSnapshot(userId: string): Promise<Snapshot> {
+ if (!userId) return empty();
+ const cached = snapshots.get(userId);
+ if (cached) return cached;
+ const expected = epoch;
+ const raw = await AsyncStorage.getItem(PREFIX + userId).catch(() => null);
+ let value = empty();
+ try { if (raw && raw.length <= MAX_CHARS) value = normalize(JSON.parse(raw)); } catch { /* cache miss */ }
+ if (epoch !== expected) return empty();
+ if (!snapshots.has(userId)) snapshots.set(userId, value);
+ return snapshots.get(userId)!;
+}
+
+async function update(userId: string, change: (snapshot: Snapshot) => void): Promise<void> {
+ if (!userId) return;
+ const expected = epoch;
+ const previous = writes.get(userId) ?? Promise.resolve();
+ const next = previous.then(async () => {
+ const snapshot = await readRemoteResourceSnapshot(userId);
+ if (expected !== epoch) return;
+ change(snapshot);
+ const cleaned = normalize(snapshot);
+ snapshots.set(userId, cleaned); emit();
+ const raw = JSON.stringify(cleaned);
+ if (raw.length > MAX_CHARS) return;
+ await AsyncStorage.setItem(PREFIX + userId, raw).catch(() => undefined);
+ if (expected !== epoch) await AsyncStorage.removeItem(PREFIX + userId).catch(() => undefined);
+ });
+ writes.set(userId, next);
+ await next.finally(() => { if (writes.get(userId) === next) writes.delete(userId); });
+}
+export const cacheRemoteResourceHome = (userId: string, home: RemoteHomeCollection[]) => update(userId, (s) => { s.home = home; });
+export const remoteResourceReadKey = (deviceId: string, resourceId: string) => JSON.stringify([deviceId, resourceId]);
+export const cacheRemoteResourceItems = (userId: string, collectionId: string, items: HostedRemoteCollectionItem[]) => update(userId, (s) => {
+ s.items[collectionId] = items;
+ for (const row of items) {
+ const key = remoteResourceReadKey(row.host.deviceId, row.item.ref.id);
+ if (row.item.ref.kind === 'bot' && s.read[key] === undefined) s.read[key] = row.item.display.lastReplyAt ?? 0;
+ }
+});
+export const markRemoteResourceRead = (userId: string, deviceId: string, resourceId: string, at: number) => update(userId, (s) => {
+ const key = remoteResourceReadKey(deviceId, resourceId);
+ if (Number.isFinite(at) && at >= 0) s.read[key] = Math.max(s.read[key] ?? 0, at);
+});
+export function isRemoteResourceUnread(userId: string, deviceId: string, resourceId: string, at?: number): boolean {
+ const read = snapshots.get(userId)?.read[remoteResourceReadKey(deviceId, resourceId)];
+ return at !== undefined && read !== undefined && at > read;
+}
+export async function clearRemoteResourceCache(): Promise<void> {
+ epoch += 1; snapshots.clear(); emit();
+ await Promise.allSettled([...writes.values()]);
+ const keys = await AsyncStorage.getAllKeys().catch(() => []);
+ await AsyncStorage.multiRemove(keys.filter((key) => key.startsWith(PREFIX))).catch(() => undefined);
+}
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
new file mode 100644
index 0000000000..ae2467a013
--- /dev/null
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -0,0 +1,433 @@
+import {
+ REMOTE_RESOURCE_GET_CHANNEL,
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ REMOTE_RESOURCE_LIST_CHANNEL,
+ REMOTE_RESOURCE_MANIFEST_CHANNEL,
+ REMOTE_RESOURCE_PROTOCOL_VERSION,
+ resolveRemoteText,
+ type RemoteActionInvokeResponse,
+ type RemoteCollectionDescriptor,
+ type RemoteCollectionItem,
+ type RemoteCollectionListResponse,
+ type RemoteResourceAvatar,
+ type RemoteResourceDisplay,
+ type RemoteResourceLink,
+ type RemoteResourceClientDescriptor,
+ type RemoteResource,
+ type RemoteResourceManifestResponse,
+ type RemoteResourceRef,
+ type RemoteResourceStatus,
+ type RemoteText,
+} from '@cindy/device-link';
+
+import type { RemoteInvoke } from './mobileMakerTransport';
+
+export const MOBILE_REMOTE_RESOURCE_PRIMITIVES = [
+ 'status',
+ 'session-link',
+] as const;
+
+export interface RemoteResourceHostTarget {
+ deviceId: string;
+ deviceName: string;
+}
+
+export interface RemoteHomeCollection {
+ id: string;
+ title: string;
+ resourceKind: string;
+ placement?: string;
+ iconName?: string;
+ targets: RemoteResourceHostTarget[];
+}
+
+/** Offline hosts keep an already discovered entry; revoked/disabled hosts do not. */
+export function remoteResourceDiscoveryTargets(
+ devices: readonly { canOpen: boolean; state: string; deviceId: string; name: string }[],
+ previous: readonly RemoteHomeCollection[],
+): RemoteResourceHostTarget[] {
+ const known = new Set(previous.flatMap((collection) => collection.targets.map((host) => host.deviceId)));
+ return devices
+ .filter((device) => device.canOpen || (device.state === 'offline' && known.has(device.deviceId)))
+ .map((device) => ({ deviceId: device.deviceId, deviceName: device.name }));
+}
+
+function clientDescriptor(locale?: string): RemoteResourceClientDescriptor {
+ return {
+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,
+ primitives: [...MOBILE_REMOTE_RESOURCE_PRIMITIVES],
+ ...(locale ? { locale } : {}),
+ };
+}
+
+function recordOf(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+const MAX_REMOTE_ID_CHARS = 160;
+const MAX_REMOTE_TEXT_CHARS = 20_000;
+const MAX_REMOTE_TRANSLATIONS = 32;
+
+function boundedString(value: unknown, max: number, allowEmpty = false): string | null {
+ return typeof value === 'string'
+ && value.length <= max
+ && (allowEmpty || value.length > 0)
+ ? value
+ : null;
+}
+
+function normalizeRemoteText(value: unknown, max = MAX_REMOTE_TEXT_CHARS): RemoteText | null {
+ const direct = boundedString(value, max);
+ if (direct) return direct;
+ const record = recordOf(value);
+ const fallback = boundedString(record?.fallback, max);
+ if (!record || !fallback) return null;
+ const translationsRecord = recordOf(record.translations);
+ if (!translationsRecord) return { fallback };
+ const translations: Record<string, string> = {};
+ for (const [locale, text] of Object.entries(translationsRecord)) {
+ if (Object.keys(translations).length >= MAX_REMOTE_TRANSLATIONS) break;
+ const normalizedLocale = boundedString(locale, 64);
+ const normalizedText = boundedString(text, max);
+ if (normalizedLocale && normalizedText) translations[normalizedLocale] = normalizedText;
+ }
+ return Object.keys(translations).length > 0 ? { fallback, translations } : { fallback };
+}
+
+function normalizeRemoteRef(value: unknown): RemoteResourceRef | null {
+ const record = recordOf(value);
+ const collectionId = boundedString(record?.collectionId, MAX_REMOTE_ID_CHARS);
+ const kind = boundedString(record?.kind, MAX_REMOTE_ID_CHARS);
+ const id = boundedString(record?.id, MAX_REMOTE_ID_CHARS);
+ return collectionId && kind && id ? { collectionId, kind, id } : null;
+}
+
+function normalizeRemoteStatus(value: unknown): RemoteResourceStatus | null {
+ const record = recordOf(value);
+ const label = normalizeRemoteText(record?.label, 512);
+ if (!record || !label) return null;
+ const tone = boundedString(record.tone, 64);
+ return { label, ...(tone ? { tone } : {}) };
+}
+
+function normalizeRemoteAvatar(value: unknown): RemoteResourceAvatar | null {
+ const record = recordOf(value);
+ const kind = boundedString(record?.kind, 64);
+ const avatarValue = boundedString(record?.value, 4_096, true);
+ const fallbackText = boundedString(record?.fallbackText, 64, true);
+ if (!record || !kind || avatarValue === null || fallbackText === null) return null;
+ const color = boundedString(record.color, 64);
+ return {
+ kind,
+ value: avatarValue,
+ fallbackText,
+ ...(color ? { color } : {}),
+ };
+}
+
+function normalizeRemoteTimestamp(value: unknown): number | undefined {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined;
+ return Number.isFinite(new Date(value).getTime()) ? value : undefined;
+}
+
+function normalizeRemoteDisplay(value: unknown): RemoteResourceDisplay | null {
+ const record = recordOf(value);
+ const title = normalizeRemoteText(record?.title, 512);
+ if (!record || !title) return null;
+ const subtitle = normalizeRemoteText(record.subtitle, 4_096);
+ const preview = normalizeRemoteText(record.preview, 4_096);
+ const timestamp = normalizeRemoteTimestamp(record.timestamp);
+ const avatar = normalizeRemoteAvatar(record.avatar);
+ const status = normalizeRemoteStatus(record.status);
+ return {
+ title,
+ ...(subtitle ? { subtitle } : {}),
+ ...(preview ? { preview } : {}),
+ ...(timestamp !== undefined ? { timestamp } : {}),
+ ...(normalizeRemoteTimestamp(record.lastReplyAt) !== undefined ? { lastReplyAt: record.lastReplyAt as number } : {}),
+ ...(avatar ? { avatar } : {}),
+ ...(status ? { status } : {}),
+ };
+}
+
+function normalizeRemoteLink(value: unknown): RemoteResourceLink | null {
+ const record = recordOf(value);
+ const rel = boundedString(record?.rel, MAX_REMOTE_ID_CHARS);
+ const target = recordOf(record?.target);
+ if (!record || !rel || !target) return null;
+ let normalizedTarget: RemoteResourceLink['target'] | null = null;
+ if (target.kind === 'session') {
+ const sessionId = boundedString(target.sessionId, MAX_REMOTE_ID_CHARS);
+ if (sessionId) normalizedTarget = { kind: 'session', sessionId };
+ } else if (target.kind === 'resource') {
+ const ref = normalizeRemoteRef(target.ref);
+ if (ref) normalizedTarget = { kind: 'resource', ref };
+ }
+ if (!normalizedTarget) return null;
+ const label = normalizeRemoteText(record.label, 512);
+ return { rel, target: normalizedTarget, ...(label ? { label } : {}) };
+}
+
+function validDescriptor(value: unknown): RemoteCollectionDescriptor | null {
+ const record = recordOf(value);
+ if (!record) return null;
+ const id = boundedString(record.id, MAX_REMOTE_ID_CHARS);
+ const resourceKind = boundedString(record.resourceKind, MAX_REMOTE_ID_CHARS);
+ const title = normalizeRemoteText(record.title, 512);
+ if (!id || !resourceKind || !title) return null;
+ const placement = boundedString(record.placement, MAX_REMOTE_ID_CHARS);
+ const iconRecord = recordOf(record.icon);
+ const iconName = boundedString(iconRecord?.name, MAX_REMOTE_ID_CHARS);
+ const iconFallbackText = boundedString(iconRecord?.fallbackText, 64, true);
+ return {
+ id,
+ resourceKind,
+ title,
+ ...(placement ? { placement } : {}),
+ ...(iconName && iconFallbackText !== null
+ ? { icon: { name: iconName, fallbackText: iconFallbackText } }
+ : {}),
+ };
+}
+
+function normalizeManifest(value: unknown): RemoteResourceManifestResponse | null {
+ const record = recordOf(value);
+ if (!record || !Array.isArray(record.collections)) return null;
+ const collections = record.collections.flatMap((item) => {
+ const descriptor = validDescriptor(item);
+ return descriptor ? [descriptor] : [];
+ });
+ const protocolVersion = typeof record.protocolVersion === 'number'
+ ? record.protocolVersion
+ : REMOTE_RESOURCE_PROTOCOL_VERSION;
+ return { protocolVersion, collections };
+}
+
+function errorCode(error: unknown): string {
+ if (error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string') {
+ return (error as { code: string }).code;
+ }
+ return '';
+}
+
+export function isRemoteResourcesUnsupported(error: unknown): boolean {
+ const code = errorCode(error);
+ if (code === 'CHANNEL_NOT_ALLOWED' || code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return true;
+ const message = error instanceof Error ? error.message : String(error);
+ return message.includes('CHANNEL_NOT_ALLOWED');
+}
+
+export async function loadRemoteResourceManifest(
+ invoke: RemoteInvoke,
+ target: RemoteResourceHostTarget,
+ locale?: string,
+): Promise<RemoteResourceManifestResponse | null> {
+ try {
+ const raw = await invoke(target.deviceId, REMOTE_RESOURCE_MANIFEST_CHANNEL, [{
+ client: clientDescriptor(locale),
+ }]);
+ return normalizeManifest(raw);
+ } catch (error) {
+ if (isRemoteResourcesUnsupported(error)) return null;
+ throw error;
+ }
+}
+
+/**
+ * Merge the same host-advertised collection across computers. The mobile shell
+ * only understands placement and portable display primitives, not module ids.
+ */
+export async function discoverRemoteHomeCollections(
+ invoke: RemoteInvoke,
+ targets: readonly RemoteResourceHostTarget[],
+ locale?: string,
+ previous: readonly RemoteHomeCollection[] = [],
+): Promise<RemoteHomeCollection[]> {
+ const settled = await Promise.allSettled(targets.map(async (target) => ({
+ target,
+ manifest: await loadRemoteResourceManifest(invoke, target, locale),
+ })));
+ const discovered = settled.flatMap((result, index) => {
+ if (result.status === 'fulfilled') {
+ return result.value.manifest ? [result.value] : [];
+ }
+ const target = targets[index];
+ if (!target) return [];
+ return previous.flatMap((collection) => collection.targets.some(
+ (candidate) => candidate.deviceId === target.deviceId,
+ ) ? [{
+ target,
+ manifest: {
+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,
+ collections: [{
+ id: collection.id,
+ resourceKind: collection.resourceKind,
+ title: collection.title,
+ ...(collection.placement ? { placement: collection.placement } : {}),
+ ...(collection.iconName
+ ? { icon: { name: collection.iconName, fallbackText: '' } }
+ : {}),
+ }],
+ },
+ }] : []);
+ });
+ if (targets.length > 0 && discovered.length === 0) {
+ const failure = settled.find((result) => result.status === 'rejected');
+ if (failure && failure.status === 'rejected') throw failure.reason;
+ }
+ const byId = new Map<string, RemoteHomeCollection>();
+ for (const { target, manifest } of discovered) {
+ for (const collection of manifest?.collections ?? []) {
+ if (collection.placement !== 'home-scope') continue;
+ const existing = byId.get(collection.id);
+ if (existing && existing.resourceKind === collection.resourceKind) {
+ existing.targets.push(target);
+ continue;
+ }
+ if (existing) continue;
+ byId.set(collection.id, {
+ id: collection.id,
+ title: resolveRemoteText(collection.title, locale),
+ resourceKind: collection.resourceKind,
+ placement: collection.placement,
+ iconName: collection.icon?.name,
+ targets: [target],
+ });
+ }
+ }
+ return [...byId.values()];
+}
+
+export async function invokeRemoteResourceAction(
+ invoke: RemoteInvoke,
+ target: RemoteResourceHostTarget,
+ request: {
+ collectionId: string;
+ actionId: string;
+ resourceRef?: RemoteResourceRef;
+ input?: Record<string, unknown>;
+ },
+ locale?: string,
+): Promise<RemoteActionInvokeResponse> {
+ return invoke<RemoteActionInvokeResponse>(target.deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, [{
+ client: clientDescriptor(locale),
+ ...request,
+ }]);
+}
+
+export async function getRemoteResource(
+ invoke: RemoteInvoke,
+ target: RemoteResourceHostTarget,
+ ref: RemoteResourceRef,
+ locale?: string,
+): Promise<RemoteResource> {
+ const raw = await invoke<unknown>(target.deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{
+ client: clientDescriptor(locale),
+ ref,
+ }]);
+ const normalized = normalizeRemoteCollectionItem(raw, ref.collectionId);
+ if (!normalized || normalized.ref.kind !== ref.kind || normalized.ref.id !== ref.id) {
+ throw new Error('invalid remote resource response');
+ }
+ return normalized;
+}
+
+function normalizeRemoteCollectionItem(
+ candidate: unknown,
+ collectionId: string,
+): RemoteCollectionItem | null {
+ const item = recordOf(candidate);
+ const ref = normalizeRemoteRef(item?.ref);
+ const display = normalizeRemoteDisplay(item?.display);
+ const revision = boundedString(item?.revision, 1_024);
+ if (!item || !ref || ref.collectionId !== collectionId || !display || !revision) return null;
+ const links = Array.isArray(item.links)
+ ? item.links.slice(0, 64).flatMap((link) => {
+ const normalized = normalizeRemoteLink(link);
+ return normalized ? [normalized] : [];
+ })
+ : [];
+ return { ref, display, links, revision };
+}
+
+export function normalizeRemoteCollectionItems(
+ value: unknown,
+ collectionId: string,
+): RemoteCollectionItem[] {
+ const record = recordOf(value);
+ if (!record || !Array.isArray(record.items)) return [];
+ return record.items.slice(0, 200).flatMap((candidate) => {
+ const item = normalizeRemoteCollectionItem(candidate, collectionId);
+ return item ? [item] : [];
+ });
+}
+
+export interface HostedRemoteCollectionItem {
+ key: string;
+ host: RemoteResourceHostTarget;
+ item: RemoteCollectionItem;
+}
+
+/** Replace successful host shards while retaining stale rows for transiently failed hosts. */
+export function mergeRemoteCollectionHostShards(
+ current: readonly HostedRemoteCollectionItem[],
+ next: readonly HostedRemoteCollectionItem[],
+ successfulDeviceIds: ReadonlySet<string>,
+ targets: readonly RemoteResourceHostTarget[],
+): HostedRemoteCollectionItem[] {
+ const sourceFor = (deviceId: string) => (successfulDeviceIds.has(deviceId) ? next : current)
+ .filter((entry) => entry.host.deviceId === deviceId);
+ return targets.flatMap((target) => sourceFor(target.deviceId));
+}
+
+export async function listRemoteCollection(
+ invoke: RemoteInvoke,
+ target: RemoteResourceHostTarget,
+ collectionId: string,
+ locale?: string,
+): Promise<RemoteCollectionListResponse> {
+ return invoke<RemoteCollectionListResponse>(target.deviceId, REMOTE_RESOURCE_LIST_CHANNEL, [{
+ client: clientDescriptor(locale),
+ collectionId,
+ limit: 200,
+ }]);
+}
+
+const MAX_TARGETS = 32;
+const MAX_TARGET_FIELD_CHARS = 256;
+
+export function serializeRemoteResourceTargets(
+ targets: readonly RemoteResourceHostTarget[],
+): string {
+ return JSON.stringify(targets.slice(0, MAX_TARGETS).map((target) => ({
+ deviceId: target.deviceId.slice(0, MAX_TARGET_FIELD_CHARS),
+ deviceName: target.deviceName.slice(0, MAX_TARGET_FIELD_CHARS),
+ })));
+}
+
+export function parseRemoteResourceTargets(value: unknown): RemoteResourceHostTarget[] {
+ const raw = Array.isArray(value) ? value[0] : value;
+ if (typeof raw !== 'string' || raw.length > 32_000) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.slice(0, MAX_TARGETS).flatMap((item) => {
+ const record = recordOf(item);
+ if (!record) return [];
+ const deviceId = typeof record.deviceId === 'string' ? record.deviceId : '';
+ const deviceName = typeof record.deviceName === 'string' ? record.deviceName : '';
+ if (
+ !deviceId
+ || deviceId.length > MAX_TARGET_FIELD_CHARS
+ || deviceName.length > MAX_TARGET_FIELD_CHARS
+ ) {
+ return [];
+ }
+ return [{ deviceId, deviceName: deviceName || deviceId }];
+ });
+ } catch {
+ return [];
+ }
+}
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index ee017174a8..4eebefa885 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -34,6 +34,20 @@
"deleting": "Deleting",
"create": "New"
},
+ "resources": {
+ "hostOffline": "Offline",
+ "titleFallback": "Resources",
+ "loading": "Loading…",
+ "emptyTitle": "Nothing here yet",
+ "emptyCopy": "This computer has not provided any items here yet.",
+ "loadFailed": "Couldn’t load these items",
+ "noHosts": "No compatible computer is available.",
+ "noConversation": "This item does not currently have a session to open.",
+ "openFailed": "Couldn’t open the session",
+ "resolving": "Opening the latest session…",
+ "retry": "Try again",
+ "hostCount": "{{count}} computers"
+ },
"presentation": {
"deviceList": {
"headerAvailable": "{{count}} controllable computers",
@@ -692,5 +706,26 @@
"daysAgo": "{{count}} days ago"
}
}
+ },
+ "companions": {
+ "messageSent": "Message sent",
+ "privateChat": "Private chat with {{name}}",
+ "backgroundTask": "Background task",
+ "openTask": "Open task",
+ "stopTask": "Stop task",
+ "actionFailed": "Unable to load or complete this action",
+ "messages": "Messages",
+ "readOnly": "Read only",
+ "unread": "New reply",
+ "status": {
+ "queued": "Queued",
+ "running": "Running",
+ "waiting": "Waiting for reply",
+ "completed": "Completed",
+ "failed": "Failed",
+ "cancelled": "Cancelled",
+ "timed-out": "Timed out",
+ "unknown": "Status unavailable"
+ }
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index 4783584937..e0a8d96353 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -34,6 +34,20 @@
"deleting": "削除中",
"create": "新規"
},
+ "resources": {
+ "hostOffline": "オフライン",
+ "titleFallback": "リソース",
+ "loading": "読み込み中…",
+ "emptyTitle": "まだ項目がありません",
+ "emptyCopy": "このコンピュータには、ここに表示する項目がまだありません。",
+ "loadFailed": "項目を読み込めませんでした",
+ "noHosts": "対応するコンピュータを利用できません。",
+ "noConversation": "この項目には現在、開けるセッションがありません。",
+ "openFailed": "セッションを開けませんでした",
+ "resolving": "最新のセッションを開いています…",
+ "retry": "もう一度試す",
+ "hostCount": "{{count}} 台のコンピュータ"
+ },
"presentation": {
"deviceList": {
"headerAvailable": "操作可能なコンピューター {{count}} 台",
@@ -692,5 +706,26 @@
"daysAgo": "{{count}} 日前"
}
}
+ },
+ "companions": {
+ "messageSent": "追加メッセージを送信しました",
+ "privateChat": "{{name}} との会話",
+ "backgroundTask": "バックグラウンドタスク",
+ "openTask": "タスクを開く",
+ "stopTask": "タスクを停止",
+ "actionFailed": "読み込みまたは操作を完了できません",
+ "messages": "メッセージ",
+ "readOnly": "閲覧のみ",
+ "unread": "新しい返信",
+ "status": {
+ "queued": "開始待ち",
+ "running": "実行中",
+ "waiting": "返信待ち",
+ "completed": "完了",
+ "failed": "失敗",
+ "cancelled": "キャンセル済み",
+ "timed-out": "タイムアウト",
+ "unknown": "状態を確認できません"
+ }
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index e25fdf9345..57b7168873 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -34,6 +34,20 @@
"deleting": "삭제 중",
"create": "새로 만들기"
},
+ "resources": {
+ "hostOffline": "오프라인",
+ "titleFallback": "리소스",
+ "loading": "불러오는 중…",
+ "emptyTitle": "아직 항목이 없습니다",
+ "emptyCopy": "이 컴퓨터에는 아직 여기에 표시할 항목이 없습니다.",
+ "loadFailed": "항목을 불러올 수 없습니다",
+ "noHosts": "사용 가능한 호환 컴퓨터가 없습니다.",
+ "noConversation": "이 항목에는 현재 열 수 있는 세션이 없습니다.",
+ "openFailed": "세션을 열 수 없습니다",
+ "resolving": "최신 세션을 여는 중…",
+ "retry": "다시 시도",
+ "hostCount": "컴퓨터 {{count}}대"
+ },
"presentation": {
"deviceList": {
"headerAvailable": "제어 가능한 컴퓨터 {{count}}대",
@@ -693,5 +707,26 @@
"daysAgo": "{{count}}일 전"
}
}
+ },
+ "companions": {
+ "messageSent": "추가 메시지를 보냈습니다",
+ "privateChat": "{{name}} 님과의 대화",
+ "backgroundTask": "백그라운드 작업",
+ "openTask": "작업 열기",
+ "stopTask": "작업 중지",
+ "actionFailed": "읽거나 작업을 완료할 수 없습니다",
+ "messages": "메시지",
+ "readOnly": "읽기 전용",
+ "unread": "새 답변",
+ "status": {
+ "queued": "시작 대기",
+ "running": "실행 중",
+ "waiting": "답변 대기",
+ "completed": "완료",
+ "failed": "실패",
+ "cancelled": "취소됨",
+ "timed-out": "시간 초과",
+ "unknown": "상태를 확인할 수 없습니다"
+ }
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 4f90ce9813..a2e86d4ae7 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -34,6 +34,20 @@
"deleting": "删除中",
"create": "新建"
},
+ "resources": {
+ "hostOffline": "离线",
+ "titleFallback": "资源",
+ "loading": "正在加载…",
+ "emptyTitle": "这里暂时没有内容",
+ "emptyCopy": "电脑目前还没有提供这里的内容。",
+ "loadFailed": "无法加载内容",
+ "noHosts": "当前没有可用的兼容电脑。",
+ "noConversation": "这个项目目前没有可打开的任务。",
+ "openFailed": "无法打开任务",
+ "resolving": "正在打开最新任务…",
+ "retry": "重试",
+ "hostCount": "{{count}} 台电脑"
+ },
"presentation": {
"deviceList": {
"headerAvailable": "{{count}} 台电脑可控制",
@@ -692,5 +706,26 @@
"daysAgo": "{{count}} 天前"
}
}
+ },
+ "companions": {
+ "messageSent": "已发送补充消息",
+ "privateChat": "与 {{name}} 的私聊",
+ "backgroundTask": "后台任务",
+ "openTask": "查看任务",
+ "stopTask": "停止任务",
+ "actionFailed": "暂时无法读取或完成操作",
+ "messages": "消息往来",
+ "readOnly": "仅供查看",
+ "unread": "有新回复",
+ "status": {
+ "queued": "等待开始",
+ "running": "运行中",
+ "waiting": "等待回复",
+ "completed": "已完成",
+ "failed": "失败",
+ "cancelled": "已取消",
+ "timed-out": "已超时",
+ "unknown": "暂时无法确认状态"
+ }
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index 206d52b5c6..4f53d49a2b 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -34,6 +34,20 @@
"deleting": "刪除中",
"create": "新建"
},
+ "resources": {
+ "hostOffline": "離線",
+ "titleFallback": "資源",
+ "loading": "正在載入…",
+ "emptyTitle": "這裡暫時沒有內容",
+ "emptyCopy": "電腦目前還沒有提供這裡的內容。",
+ "loadFailed": "無法載入內容",
+ "noHosts": "目前沒有可用的相容電腦。",
+ "noConversation": "這個項目目前沒有可開啟的任務。",
+ "openFailed": "無法開啟任務",
+ "resolving": "正在開啟最新任務…",
+ "retry": "重試",
+ "hostCount": "{{count}} 台電腦"
+ },
"presentation": {
"deviceList": {
"headerAvailable": "{{count}} 臺電腦可控制",
@@ -692,5 +706,26 @@
"daysAgo": "{{count}} 天前"
}
}
+ },
+ "companions": {
+ "messageSent": "已傳送補充訊息",
+ "privateChat": "與 {{name}} 的私聊",
+ "backgroundTask": "背景任務",
+ "openTask": "查看任務",
+ "stopTask": "停止任務",
+ "actionFailed": "暫時無法讀取或完成操作",
+ "messages": "訊息往來",
+ "readOnly": "僅供檢視",
+ "unread": "有新回覆",
+ "status": {
+ "queued": "等待開始",
+ "running": "執行中",
+ "waiting": "等待回覆",
+ "completed": "已完成",
+ "failed": "失敗",
+ "cancelled": "已取消",
+ "timed-out": "已逾時",
+ "unknown": "暫時無法確認狀態"
+ }
}
}
diff --git a/apps/mobile/src/session/CompanionMessageCard.tsx b/apps/mobile/src/session/CompanionMessageCard.tsx
new file mode 100644
index 0000000000..982948ce67
--- /dev/null
+++ b/apps/mobile/src/session/CompanionMessageCard.tsx
@@ -0,0 +1,83 @@
+import { useState } from 'react';
+import { useLocalSearchParams, useRouter } from 'expo-router';
+import { Pressable, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import type { BotDelegationListResult, BotDelegationCancelResult } from '@cindy/maker-shared/botDelegation';
+import type { BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';
+import { Text } from '@/components/AppText';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { spacing, radius, typeScale } from '@/theme/tokens';
+import type { NormalizedRemoteMessage } from './messageNormalize';
+import { useRemoteCompanionQuery } from './useRemoteCompanionQuery';
+
+export function CompanionMessageCard({ message }: { message: NormalizedRemoteMessage }) {
+ const { t } = useTranslation();
+ const router = useRouter();
+ const params = useLocalSearchParams<{ deviceId?: string }>();
+ const deviceId = typeof params.deviceId === 'string' ? params.deviceId : '';
+ const styles = useThemedStyles(makeStyles);
+ const card = message.companion;
+ if (!card) return null;
+ if (card.kind === 'task' && card.meta.role === 'delegation-request') {
+ return <CompanionTaskCard deviceId={deviceId} parentSessionId={message.source.sessionId} meta={card.meta} />;
+ }
+ if (card.kind === 'task') return <Text style={styles.note}>{t('devices.companions.messageSent')}{message.body ? ` · ${message.body}` : ''}</Text>;
+ const meta = card.meta;
+ return <Pressable accessibilityRole="button" style={styles.card} onPress={() => router.push({
+ pathname: '/companions/direct/[threadId]',
+ params: { deviceId, threadId: meta.threadId, botId: meta.viewerBotId },
+ })}>
+ <Text style={styles.title}>{t('devices.companions.privateChat', { name: meta.peerBotName })}</Text>
+ <Text numberOfLines={2} style={styles.note}>{meta.preview}</Text>
+ </Pressable>;
+}
+
+function CompanionTaskCard({ deviceId, parentSessionId, meta }: { deviceId: string; parentSessionId: string; meta: BotCollaborationMeta }) {
+ const { t } = useTranslation();
+ const router = useRouter();
+ const { invoke } = useDeviceLink();
+ const styles = useThemedStyles(makeStyles);
+ const { value, online, error, refresh } = useRemoteCompanionQuery<BotDelegationListResult>(deviceId, 'maker:bot-delegations:list', [parentSessionId]);
+ const row = value?.ok ? value.delegations.find((item) => item.id === meta.delegationId) : null;
+ const [pending, setPending] = useState(false);
+ const [actionFailed, setActionFailed] = useState(false);
+ const childSessionId = row?.childSessionId || meta.childSessionId;
+ const active = row && ['queued', 'running', 'waiting'].includes(row.status);
+ const stop = async () => {
+ if (!online || pending) return;
+ setPending(true); setActionFailed(false);
+ try {
+ const result = await invoke<BotDelegationCancelResult>(deviceId, 'maker:bot-delegation:cancel', [parentSessionId, meta.delegationId]);
+ setActionFailed(!result.ok); refresh();
+ } catch { setActionFailed(true); }
+ finally { setPending(false); }
+ };
+ return <View style={styles.card} testID="companion.taskCard">
+ <Text style={styles.note}>{t('devices.companions.backgroundTask')}</Text>
+ <Text style={styles.title}>{row?.title || meta.objective}</Text>
+ <Text style={styles.note}>{!online ? t('devices.resources.hostOffline') : t(`devices.companions.status.${row?.status || 'unknown'}`)}</Text>
+ {row?.pendingInteraction ? <Text style={styles.note}>{row.pendingInteraction.summary}</Text> : null}
+ {row?.resultSummary ? <Text style={styles.note}>{row.resultSummary}</Text> : null}
+ <View style={styles.actions}>
+ {childSessionId ? <Pressable accessibilityRole="button" style={styles.action} onPress={() => router.push({ pathname: '/sessions/[sessionId]', params: { deviceId, sessionId: childSessionId } })}>
+ <Text style={styles.note}>{t('devices.companions.openTask')}</Text>
+ </Pressable> : null}
+ {active ? <Pressable accessibilityRole="button" disabled={!online || pending} style={[styles.action, (!online || pending) && styles.disabled]} onPress={() => void stop()}>
+ <Text style={styles.note}>{t('devices.companions.stopTask')}</Text>
+ </Pressable> : null}
+ {error ? <Pressable accessibilityRole="button" style={styles.action} onPress={refresh}><Text style={styles.note}>{t('devices.resources.retry')}</Text></Pressable> : null}
+ </View>
+ {actionFailed ? <Text style={styles.error}>{t('devices.companions.actionFailed')}</Text> : null}
+ </View>;
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ card: { marginVertical: spacing.sm, padding: spacing.md, gap: spacing.xs, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, backgroundColor: colors.surfaceElevated, borderRadius: radius.container },
+ title: { color: colors.textPrimary, fontSize: typeScale.body },
+ note: { color: colors.textSecondary, fontSize: typeScale.footnote },
+ error: { color: colors.statusError, fontSize: typeScale.footnote },
+ actions: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
+ action: { minHeight: 44, paddingHorizontal: spacing.sm, justifyContent: 'center' },
+ disabled: { opacity: 0.5 },
+});
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index ea3c8ad1a6..b96799e969 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -1,3 +1,4 @@
+import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -2611,7 +2612,9 @@ const RenderItemView = memo(function RenderItemView({
let node: ReactNode;
switch (item.type) {
case 'message':
- node = item.message.orcaCard
+ node = item.message.companion
+ ? <CompanionMessageCard message={item.message} />
+ : item.message.orcaCard
? <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth} />
: <MessageBubble item={hookSourceUserItem ?? systemCardUserItem ?? item} actions={actions} />;
break;
diff --git a/apps/mobile/src/session/homeChromeMenus.ts b/apps/mobile/src/session/homeChromeMenus.ts
index 29e516db78..12176dba64 100644
--- a/apps/mobile/src/session/homeChromeMenus.ts
+++ b/apps/mobile/src/session/homeChromeMenus.ts
@@ -192,9 +192,21 @@ function inlineGroup(
};
}
+export const HOME_SCOPE_COLLECTION_PREFIX = "scope.collection:";
+
+export function parseHomeScopePullDownAction(
+ id: string,
+): { kind: "select"; filterId: string } | { kind: "collection"; collectionId: string } {
+ if (id.startsWith(HOME_SCOPE_COLLECTION_PREFIX)) {
+ return { kind: "collection", collectionId: id.slice(HOME_SCOPE_COLLECTION_PREFIX.length) };
+ }
+ return { kind: "select", filterId: id };
+}
+
export function buildHomeScopePullDownActions(
filters: readonly MobileHomeDeviceFilterItem[],
allConversationsLabel: string,
+ collections: readonly { id: string; title: string }[] = [],
): NativePullDownAction[] {
const allFilter = filters.find((item) => item.deviceId === null) ?? null;
const deviceFilters = filters.filter(
@@ -206,6 +218,12 @@ export function buildHomeScopePullDownActions(
checkable(allFilter.id, allConversationsLabel, allFilter.selected),
);
}
+ for (const collection of collections) {
+ items.push({
+ id: `${HOME_SCOPE_COLLECTION_PREFIX}${collection.id}`,
+ title: collection.title,
+ });
+ }
for (const item of deviceFilters) {
if (!item.deviceId) continue;
items.push(checkable(item.id, item.label, item.selected));
diff --git a/apps/mobile/src/session/hostManagedSession.ts b/apps/mobile/src/session/hostManagedSession.ts
new file mode 100644
index 0000000000..d703a2b41c
--- /dev/null
+++ b/apps/mobile/src/session/hostManagedSession.ts
@@ -0,0 +1,11 @@
+import type { RemoteSession } from '@/session/types';
+
+/**
+ * A Bot owns and may replace its canonical Session. Mobile may operate the
+ * conversation and its permissions; identity, model and Session lifecycle stay with the host.
+ */
+export function isHostManagedSession(
+ session: Pick<RemoteSession, 'source'> | null | undefined,
+): boolean {
+ return session?.source === 'bot';
+}
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index 72f5ca32cc..82ae07cbc2 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -1,3 +1,5 @@
+import { readBotCollaborationMeta, type BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';
+import { readBotDirectMessageMeta, type BotDirectMessageMeta } from '@cindy/maker-shared/botDirectMessage';
import type { RemoteMessage, RemoteMessageRole } from '@/session/types';
import type { MobileSystemCardType } from '@/session/systemCard';
import { contentToPreview } from '@/utils/contentPreview';
@@ -107,6 +109,7 @@ export interface NormalizedRemoteMessage {
modelMismatch?: { selected: string; actual: string };
/** Orca 协同卡片(Lead 派活 / worker 回报);存在时由 MessageRenderer 渲染成专属卡片而非普通气泡。 */
orcaCard?: OrcaCollabCard;
+ companion?: { kind: 'task'; meta: BotCollaborationMeta } | { kind: 'direct'; meta: BotDirectMessageMeta };
/** tool 消息专用:tool_result 是否已到达(含被隐藏的 orca 空结果),驱动工具行 running/done 状态。 */
toolSettled?: boolean;
/** Large settled tool input is fetched only when the user asks to view it. */
@@ -195,6 +198,20 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
const result: NormalizedRemoteMessage[] = [];
for (const message of sorted) {
if (message.role === 'tool_result') continue;
+ if (message.role === 'assistant') {
+ const task = readBotCollaborationMeta(message.agentMeta?.botCollaboration);
+ const direct = readBotDirectMessageMeta(message.agentMeta?.botDirectMessage);
+ if (task?.role === 'delegation-request' || task?.role === 'interjection' || direct) {
+ result.push({
+ key: messageNormalizeKey(message), source: message, kind: 'system', role: message.role,
+ label: 'companion', body: typeof message.content === 'string' ? message.content : '',
+ align: 'agent', createdAt: message.createdAt,
+ companion: task && (task.role === 'delegation-request' || task.role === 'interjection')
+ ? { kind: 'task', meta: task } : { kind: 'direct', meta: direct! },
+ });
+ continue;
+ }
+ }
if (message.role === 'tool_use') {
const tool = parseToolUse(message);
diff --git a/apps/mobile/src/session/useRemoteCompanionQuery.ts b/apps/mobile/src/session/useRemoteCompanionQuery.ts
new file mode 100644
index 0000000000..5d59020bd1
--- /dev/null
+++ b/apps/mobile/src/session/useRemoteCompanionQuery.ts
@@ -0,0 +1,63 @@
+import { useCallback, useRef, useState } from 'react';
+import { AppState } from 'react-native';
+import { useFocusEffect } from 'expo-router';
+import { useAuth } from '@/auth/AuthContext';
+import { subscribeRemoteBotChanges, useDeviceLink } from '@/device-link/DeviceLinkContext';
+
+const pending = new Map<string, { promise: Promise<unknown>; invalidated: boolean }>();
+
+/** Share concurrent list reads between cards; responses never outlive their account/link. */
+export function useRemoteCompanionQuery<T>(deviceId: string, channel: string, args: string[]) {
+ const link = useDeviceLink();
+ const { accountGeneration } = useAuth();
+ const argsKey = JSON.stringify(args);
+ const binding = JSON.stringify([accountGeneration, link.connectionEpoch, deviceId, channel, argsKey]);
+ const online = link.status === 'online' && link.getPresenceAvailability(deviceId) !== false;
+ const [state, setState] = useState<{ binding: string; value: T | null; error: boolean }>({ binding, value: null, error: false });
+ const [revision, setRevision] = useState(0);
+ const refresh = useCallback(() => setRevision((n) => n + 1), []);
+ const currentBinding = useRef(binding);
+ currentBinding.current = binding;
+ useFocusEffect(useCallback(() => {
+ if (!deviceId || !online) return;
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let generation = 0;
+ const load = () => {
+ if (AppState.currentState !== 'active') return;
+ const expected = ++generation;
+ let entry = pending.get(binding);
+ if (entry?.invalidated) {
+ void entry.promise.finally(() => { if (!disposed && generation === expected && currentBinding.current === binding) load(); }).catch(() => undefined);
+ return;
+ }
+ if (!entry) {
+ entry = { promise: link.invoke(deviceId, channel, JSON.parse(argsKey)), invalidated: false };
+ pending.set(binding, entry);
+ const captured = entry;
+ void entry.promise.finally(() => { if (pending.get(binding) === captured) pending.delete(binding); }).catch(() => undefined);
+ }
+ void entry.promise.then((value) => {
+ if (!disposed && generation === expected && currentBinding.current === binding) setState({ binding, value: value as T, error: false });
+ }).catch(() => {
+ if (!disposed && generation === expected && currentBinding.current === binding) setState({ binding, value: null, error: true });
+ });
+ };
+ load();
+ const unsubscribe = subscribeRemoteBotChanges((source, changedChannel, payload) => {
+ if (source !== deviceId || !payload || typeof payload !== 'object') return;
+ const row = payload as { parentSessionId?: string; threadId?: string };
+ const relevant = channel === 'maker:bot-delegations:list'
+ ? changedChannel === 'maker:bot-delegation:changed' && row.parentSessionId === JSON.parse(argsKey)[0]
+ : changedChannel === 'maker:bot-direct-message:changed' && row.threadId === JSON.parse(argsKey)[0];
+ if (!relevant) return;
+ const entry = pending.get(binding);
+ if (entry) entry.invalidated = true;
+ if (timer) return;
+ timer = setTimeout(() => { timer = undefined; load(); }, 300);
+ });
+ const appState = AppState.addEventListener('change', (state) => { generation += 1; if (state === 'active') load(); });
+ return () => { disposed = true; unsubscribe(); appState.remove(); if (timer) clearTimeout(timer); };
+ }, [argsKey, binding, channel, deviceId, link.invoke, online, revision]));
+ return { value: state.binding === binding ? state.value : null, error: state.binding === binding && state.error, online, refresh };
+}
diff --git a/apps/mobile/src/session/useRemoteResourceSession.ts b/apps/mobile/src/session/useRemoteResourceSession.ts
new file mode 100644
index 0000000000..091e9ba3c0
--- /dev/null
+++ b/apps/mobile/src/session/useRemoteResourceSession.ts
@@ -0,0 +1,70 @@
+import { useCallback, useRef } from 'react';
+import { AppState } from 'react-native';
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { useAuth } from '@/auth/AuthContext';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { getRemoteResource } from '@/device-link/remoteResources';
+import { markRemoteResourceRead } from '@/device-link/remoteResourceCache';
+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
+import { remoteSessionStore } from './remoteSessionStore';
+import type { RemoteSession } from './types';
+
+/** Follow a companion's current host-owned task on focus/reconnect, retaining its permanent identity. */
+export function useRemoteResourceSession(deviceId: string, deviceName: string, sessionId: string, canMarkRead: boolean): void {
+ const params = useLocalSearchParams<{ resourceCollectionId?: string; resourceId?: string; resourceKind?: string }>();
+ const collectionId = typeof params.resourceCollectionId === 'string' ? params.resourceCollectionId : '';
+ const resourceId = typeof params.resourceId === 'string' ? params.resourceId : '';
+ const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : '';
+ const { invoke, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
+ const { user, accountGeneration } = useAuth();
+ const router = useRouter();
+ const binding = JSON.stringify([accountGeneration, connectionEpoch, deviceId, sessionId, collectionId, resourceId, canMarkRead]);
+ const current = useRef(binding); current.current = binding;
+ useFocusEffect(useCallback(() => {
+ if (!collectionId || !resourceId || !resourceKind || !deviceId || status !== 'online') return;
+ let disposed = false;
+ let generation = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const load = async () => {
+ if (AppState.currentState !== 'active') return;
+ const expected = ++generation;
+ const valid = () => !disposed && current.current === binding && generation === expected && AppState.currentState === 'active';
+ try {
+ const resource = await getRemoteResource(invoke, { deviceId, deviceName }, { collectionId, id: resourceId, kind: resourceKind });
+ if (!valid()) return;
+ const target = resource.links.find((link) => link.rel === 'conversation')?.target;
+ if (target?.kind !== 'session') return;
+ if (target.sessionId !== sessionId) {
+ const session = await invoke<RemoteSession>(deviceId, 'local-db:sessions:get', [target.sessionId]);
+ if (!valid() || !session || session.id !== target.sessionId || (resourceKind === 'bot' && session.source !== 'bot')) return;
+ const prior = remoteSessionStore.getSessionDeviceId(session.id);
+ if (prior && prior !== deviceId) return;
+ remoteSessionStore.upsertDeviceSession(deviceId, deviceName, session);
+ router.setParams({ sessionId: session.id });
+ return; // The replacement task must mount and finish its own message sync first.
+ }
+ if (canMarkRead && resourceKind === 'bot') void markRemoteResourceRead(user?.id ?? '', deviceId, resourceId, resource.display.lastReplyAt ?? 0);
+ } catch (error) {
+ if (!valid()) return;
+ const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
+ if (code === 'NOT_FOUND' || /\[NOT_FOUND\]/.test(String(error))) {
+ // A removed/hidden resource must leave the cached task view immediately.
+ // The resolver displays the existing unavailable/retry state.
+ router.replace({ pathname: '/resources/[collectionId]/[resourceId]', params: {
+ collectionId, resourceId, resourceKind, deviceId, deviceName,
+ } });
+ }
+ // Transient link errors retain the normal task recovery path.
+ }
+ };
+ const offPush = onRemoteResourceChanged((source, payload) => {
+ if (source !== deviceId || payload.collectionId !== collectionId || timer) return;
+ if (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.id === resourceId && ref.kind === resourceKind)) return;
+ timer = setTimeout(() => { timer = undefined; void load(); }, 300);
+ });
+ const offTopic = startFocusedTopicSubscription({ deviceId, owner: `resource-session:${sessionId}`, topic: 'sessions', subscribe, unsubscribe });
+ const appState = AppState.addEventListener('change', (state) => { generation += 1; if (state === 'active') void load(); });
+ void load();
+ return () => { disposed = true; offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };
+ }, [binding, canMarkRead, collectionId, deviceId, deviceName, invoke, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, unsubscribe, user?.id]));
+}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 1a5ccdab99..3a9a55c029 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -18,7 +18,7 @@
| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 21 |
| `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 |
| `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 21 |
-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTemplates.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 290 | 50 | 489 |
+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTemplates.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 290 | 50 | 490 |
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 22 | 7 | 64 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 2 |
| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 267 | 50 | 416 |
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index f235514b3b..dee1cd9c5d 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -68,6 +68,29 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
一起打掉线,由 #1405 收窄止损半径修复。协议兼容、allowlist、单测三层防线对这类问题
全部免疫,只有 review 时点名问「半径」才拦得住。
+## 模块通过 Remote Resource 接入移动端
+
+面向移动端新增独立产品入口时,默认通过 `@cindy/device-link` 的 Remote Resource
+协议接入,不为每个业务模块复制 DTO、store、channel 与 push reason。稳定 wire 入口只有:
+
+- `maker:remote-resources:manifest`:主机声明 collection、placement 与客户端可展示的有限原语;
+- `maker:remote-resources:list` / `maker:remote-resources:get`:读取资源投影;
+- `maker:remote-resources:invoke`:调用主机已注册、已校验的 opaque action;
+- `maker:remote-resources:changed`:只表达 collection/ref 失效,控制端据此重拉。
+
+Desktop 功能模块通过 `RemoteResourceRegistry` 注册 provider;主机保留业务权威和安全边界,
+provider 只投影用户可见信息。密钥、Token、渠道凭证、系统路径、内部 prompt 与运行时对象不得
+进入资源响应。Mobile shell 只理解有限的展示/交互原语,不按 Bot、Schedule 或 Plugin 的内部
+enum 编译分支,也不接受任意 HTML、React 或无限 UI DSL。
+
+资源身份必须包含 `deviceId + collectionId + kind + id`。资源路由打开时应重新调用 `resource:get`
+解析 `conversation` 等 link,不能把可能 rollover 的 Session id 当成永久资源身份。已有对话继续
+复用 canonical Session 的消息、输入、确认与恢复链路,不复制一套模块专属聊天协议。
+
+协议按字段追加演进。未知字段、未知 collection 和未知 action 不得导致整个首页或会话崩溃;
+结构化 Session 内容必须携带可读 `fallbackMarkdown`,旧客户端至少能阅读并继续任务。只有新增
+移动端此前无法表达的内容或交互原语时,才要求客户端发版。
+
## PR 门禁
功能类 PR 的 Description 必须写明上述每一项的结论,三选一:
diff --git a/docs/product-rules/cindy-bots-completion-matrix.md b/docs/product-rules/cindy-bots-completion-matrix.md
index 19103fc153..7ccbebbb11 100644
--- a/docs/product-rules/cindy-bots-completion-matrix.md
+++ b/docs/product-rules/cindy-bots-completion-matrix.md
@@ -50,3 +50,16 @@
任何真实失败都回到对应矩阵行修复,不用 UI 绕过数据或运行时约束。Ready 使用仓库统一发布门禁;不得把未验证场景标为通过。
2026-09-05 隔离沙盒记录:Claude、Codex、Pi 均真实回复并完成后台任务回传;同一任务追加第二轮、主动停止、Pi 提问等待跨重启与回答恢复通过。伙伴私聊双方留痕且自动确认不增加未读。Pi 独立记忆保存、搜索、读回及重启后读取通过;HTML 从消息打开到内嵌预览、SVG 图片加载、Word 工具生成并解包核对正文均通过。Light/Dark 已目检主聊天与任务卡,Light 创建页已目检。远程设备端到端、长周期压缩和完整文档格式生成不在已通过证据中。
+
+
+## 2026-09-06 手机与另一台电脑的补齐范围
+
+- 多设备名册:来源电脑与伙伴身份共同定位;保存账号隔离的名册缓存,冷启动缓存只按离线展示。单个来源失败只影响该来源,重新连接后重新读取,旧请求不能覆盖停连或换账号后的状态。
+- 后台任务:手机与另一台 Desktop 均可从伙伴时间线读取任务状态、打开来源电脑的子任务、停止任务;状态推送沿父任务订阅回流。远端只得到任务卡所需字段,不输出数据库行或冻结的权限配置。
+- 伙伴私聊:两端从原消息入口打开来源电脑的只读私聊,收到更新或重连时刷新;不会以控制端本机的同名伙伴替换远端身份。
+- 手机呈现:解析与 Desktop 共用的持久任务/私聊标记,显示预设和托管图片头像,恢复成果文件入口与运行模型展示。主任务记录发生恢复替换时,聚焦/重连/资源更新重新解析伙伴身份。
+- 未读:控制端各自保存已读位置,使用来源电脑的最后可见回复时间,避免电脑时钟差异;用户发送、内部私聊、回撤和清除边界不会伪造新回复。
+- 身份创建、Profile 设置与长期技能维护仍由托管电脑负责;没有新增自主跨电脑调度,也没有让手机成为被控主机。
+
+自动证据:`remoteBots.test.tsx`、`remoteBotSession.test.tsx`、`BotCollaborationCard.test.tsx`、`BotDirectMessageView.test.tsx`、手机 `CompanionMessageCard.test.tsx` / `remoteResourceCache.test.ts` / `messageNormalize.test.ts`、`botCanonicalSession.test.ts` 与 device-link topic/allowlist 用例。
+本批未启动 Desktop DEV、Mobile DEV 或 Metro;未把模拟传输的集成测试称为两台安装版联网或 iPhone Light/Dark 实机通过。发布时仍需先合入 Desktop 依赖,再交付包含对应通道的电脑与手机版本。
diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.ts
index ef3457c4d1..c7e61f3cb5 100644
--- a/packages/device-link/src/__tests__/topics.test.ts
+++ b/packages/device-link/src/__tests__/topics.test.ts
@@ -15,6 +15,11 @@ import {
} from '../topics.js';
describe('topicForPush', () => {
+ it('delivers companion task state to the parent and private-thread changes to the account topic', () => {
+ expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: 'parent', childSessionId: 'child' })).toBe('session:parent');
+ expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: null })).toBeNull();
+ expect(topicForPush('maker:bot-direct-message:changed', { threadId: 'private' })).toBe('sessions');
+ });
it('会话列表级 channel → sessions', () => {
expect(topicForPush('local-db:sessions:created', { sessionId: 's1' })).toBe('sessions');
expect(
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 5a28fb8fc5..a10dc97dfc 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -431,6 +431,11 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// memory, prompts, configuration, or native UI/file mutations.
'local-db:bots:list',
'local-db:bots:get',
+ // Same-account opted-in controllers may inspect and stop a companion's own
+ // child task and read a participant-checked private thread. No profile mutation.
+ 'maker:bot-delegations:list',
+ 'maker:bot-delegation:cancel',
+ 'maker:bot-direct-message-thread:get',
'maker:memory:get',
'maker:memory:get-settings',
// —— 命令 / 技能 / at 资源 列举(只读)——
@@ -564,6 +569,8 @@ export const REMOTE_INVOKE_ALLOWLIST: ReadonlySet<string> = new Set([
* 命中这些 channel 的事件才会经 link 转发给控制端。
*/
export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
+ 'maker:bot-delegation:changed',
+ 'maker:bot-direct-message:changed',
// maker-ipc MAKER_PUSH
'maker:event',
// Device-level runtime Agent roster changes; controllers refresh their local availability cache.
diff --git a/packages/device-link/src/remoteResources.ts b/packages/device-link/src/remoteResources.ts
index 0c94b46584..2596768bdc 100644
--- a/packages/device-link/src/remoteResources.ts
+++ b/packages/device-link/src/remoteResources.ts
@@ -72,6 +72,8 @@ export interface RemoteResourceDisplay {
subtitle?: RemoteText;
preview?: RemoteText;
timestamp?: number;
+ /** Latest visible reply in host time; controllers keep their own read position. */
+ lastReplyAt?: number;
avatar?: RemoteResourceAvatar;
status?: RemoteResourceStatus;
badges?: RemoteResourceBadge[];
diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.ts
index f67df5d994..497f0a3de9 100644
--- a/packages/device-link/src/topics.ts
+++ b/packages/device-link/src/topics.ts
@@ -169,6 +169,7 @@ const ACCOUNT_CHANNELS: ReadonlySet<string> = new Set([
// 模块中立的资源集合失效通知;控制端已有 sessions 常驻订阅可直接接收,
// 不为每个新模块扩张一档 topic。
REMOTE_RESOURCE_CHANGED_CHANNEL,
+ 'maker:bot-direct-message:changed',
'maker:schedule:event',
'maker:project-automation:event',
// 被控端「当前 New Maker 草稿」全量变更:账号 / 全局级(无 sessionId),并入 `sessions` topic
@@ -212,6 +213,10 @@ export function topicForPush(channel: string, payload: unknown): Topic | null {
const workdir = readStringField(payload, 'workdir');
return workdir ? fsWatchTopic(workdir) : null;
}
+ if (channel === 'maker:bot-delegation:changed') {
+ const parent = readStringField(payload, 'parentSessionId');
+ return parent ? `session:${parent}` : null;
+ }
if (channel === 'maker:orca:worker-changed') {
const lead = readStringField(payload, 'leadSessionId');
return lead ? `session:${lead}` : null;
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index fee08565bc..a35b8a97ed 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -74,7 +74,10 @@
"./usage-format": "./src/usageFormat.ts",
"./work-activity-projection": "./src/workActivityProjection.ts",
"./worktree-paths": "./src/worktreePaths.ts",
- "./codex-usage-buckets": "./src/codexUsageBuckets.ts"
+ "./codex-usage-buckets": "./src/codexUsageBuckets.ts",
+ "./botCollaboration": "./src/botCollaboration.ts",
+ "./botDirectMessage": "./src/botDirectMessage.ts",
+ "./botDelegation": "./src/botDelegation.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/maker-shared/src/botCollaboration.ts b/packages/maker-shared/src/botCollaboration.ts
new file mode 100644
index 0000000000..37154e5f36
--- /dev/null
+++ b/packages/maker-shared/src/botCollaboration.ts
@@ -0,0 +1,117 @@
+/**
+ * 伙伴发起的可追踪任务在消息流中的结构化标记。
+ *
+ * 事实源仍是 `bot_delegations` 行。这里是父任务消息流里的持久锚点,让 renderer 在原位
+ * 投影唯一任务卡与补充消息留痕。字段名 `botCollaboration` 为 v1 持久化兼容保留。
+ *
+ * 设计约束:
+ * - 只增不改。老数据(没有本标记的镜像消息)继续按普通文本渲染,不回填、不迁移。
+ * - 写进 `messages.agent_meta`(JSON 列)的 `botCollaboration` 字段,不动 schema。
+ * - 只承载呈现所需的**冻结快照**(当时的名字),不做权限判据:能不能打开对方任务
+ * 仍由既有的会话可见性决定,本标记不放宽任何边界。
+ */
+
+/** 后台任务标记在某条消息上的用途。后三种只用于读取旧数据,不再生成或展示。 */
+export type BotCollaborationRole =
+ /** 父任务:启动时写下的任务卡锚点(空正文,只为承载卡片)。 */
+ | 'delegation-request'
+ /** 历史:父任务里的目标伙伴结果。 */
+ | 'guest-result'
+ /** 父任务:发起方给进行中任务追加消息的留痕。 */
+ | 'interjection'
+ /** 历史:目标伙伴主任务里的请求镜像。 */
+ | 'guest-request'
+ /** 历史:目标伙伴主任务里的终态镜像。 */
+ | 'result-mirror';
+
+export interface BotCollaborationMeta {
+ v: 1;
+ role: BotCollaborationRole;
+ delegationId: string;
+ /** 发起后台任务的伙伴。 */
+ fromBotId: string;
+ fromBotName: string;
+ /** 新数据恒为 null;非 null 只可能来自旧版具名伙伴任务。 */
+ toBotId: string | null;
+ toBotName: string;
+ /** 发起方任务;目标侧镜像据此回跳,看得到「这活是谁派的」。 */
+ parentSessionId: string | null;
+ /** 目标执行用的子任务;发起方侧据此跳过去看 TA 的完整对话。 */
+ childSessionId: string | null;
+ /** 委派目标摘要,用于卡片折叠态文案。 */
+ objective: string;
+}
+
+const ROLES = new Set<BotCollaborationRole>([
+ 'delegation-request',
+ 'guest-result',
+ 'interjection',
+ 'guest-request',
+ 'result-mirror',
+]);
+
+function optionalId(value: unknown): string | null | undefined {
+ if (value === null) return null;
+ if (typeof value === 'string') return value;
+ return undefined;
+}
+
+/**
+ * 严格解析:形状不对一律当作「没有标记」,退回普通文本渲染。宁可少一张卡,
+ * 也不要把无法核实的身份贴到别人的气泡上。
+ */
+export function readBotCollaborationMeta(value: unknown): BotCollaborationMeta | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const raw = value as Record<string, unknown>;
+ if (raw.v !== 1) return null;
+ if (typeof raw.role !== 'string' || !ROLES.has(raw.role as BotCollaborationRole)) return null;
+ if (typeof raw.delegationId !== 'string' || !raw.delegationId) return null;
+ if (typeof raw.fromBotId !== 'string' || !raw.fromBotId) return null;
+ if (raw.toBotId !== null && (typeof raw.toBotId !== 'string' || !raw.toBotId)) return null;
+ if (typeof raw.fromBotName !== 'string' || typeof raw.toBotName !== 'string') return null;
+ if (typeof raw.objective !== 'string') return null;
+ const parentSessionId = optionalId(raw.parentSessionId);
+ const childSessionId = optionalId(raw.childSessionId);
+ if (parentSessionId === undefined || childSessionId === undefined) return null;
+ return {
+ v: 1,
+ role: raw.role as BotCollaborationRole,
+ delegationId: raw.delegationId,
+ fromBotId: raw.fromBotId,
+ fromBotName: raw.fromBotName,
+ toBotId: raw.toBotId,
+ toBotName: raw.toBotName,
+ parentSessionId,
+ childSessionId,
+ objective: raw.objective,
+ };
+}
+
+/** 委派相关消息的幂等 clientId 前缀,main 与测试共用同一份常量。 */
+export const BOT_DELEGATION_CLIENT_ID = {
+ /** 父任务里的任务卡锚点。 */
+ parentRequest: (delegationId: string) => `bot-delegation-request:${delegationId}`,
+ /** 父任务里的结果回传(历史值,不可改)。 */
+ completion: (delegationId: string) => `bot-delegation-completion:${delegationId}`,
+ /** 同一任务结束后继续执行时,每一轮必须有独立的完成回执。首轮保持历史值兼容。 */
+ completionRun: (delegationId: string, runSequence: number) =>
+ runSequence <= 1
+ ? `bot-delegation-completion:${delegationId}`
+ : `bot-delegation-completion:${delegationId}:${runSequence}`,
+ /** 插话:投进子任务的那条。 */
+ interjection: (delegationId: string, token: string) =>
+ `bot-delegation-interject:${delegationId}:${token}`,
+ /** 插话:留在父任务里的留痕。 */
+ interjectionMirror: (delegationId: string, token: string) =>
+ `bot-delegation-interject-mirror:${delegationId}:${token}`,
+} as const;
+
+export type BotDelegationInterjectResult =
+ | {
+ ok: true;
+ delegationId: string;
+ childSessionId: string;
+ /** 子任务当时是否正忙:忙则本条进它的输入队列,当前回合结束后被读到。 */
+ queued: boolean;
+ }
+ | { ok: false; errorCode: string; message: string };
diff --git a/packages/maker-shared/src/botDelegation.ts b/packages/maker-shared/src/botDelegation.ts
new file mode 100644
index 0000000000..c5db4eb3b7
--- /dev/null
+++ b/packages/maker-shared/src/botDelegation.ts
@@ -0,0 +1,222 @@
+/**
+ * 一条伙伴发起的后台 Session 任务状态机:
+ *
+ * queued → running ⇄ waiting → completed | failed | cancelled
+ *
+ * - queued: 已发起,对方还没接手(含首句没送进去、正在退避重试)。
+ * - running: 对方正在做。
+ * - waiting: 对方停在一个要人拍板的地方(权限确认 / 提问 / 计划审核),
+ * `pendingInteraction` 里是具体在等什么;发起方伙伴替用户答,
+ * 或用户直接在子任务里答,任一侧答了就回到 running。
+ * - completed / failed / cancelled: 终态。超时归入 failed(lastError 以 TIMEOUT 开头)。
+ */
+export const BOT_DELEGATION_STATUSES = [
+ 'queued',
+ 'running',
+ 'waiting',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ /** Legacy terminal rows remain readable; new timeouts are stored as failed + TIMEOUT. */
+ 'timed-out',
+] as const;
+
+export type BotDelegationStatus = (typeof BOT_DELEGATION_STATUSES)[number];
+
+export type BotDelegationInteractionKind = 'permission' | 'ask_user_question' | 'plan_review';
+
+/** waiting 状态下对方正在等的那件事,给卡片与发起方伙伴看的同一份摘要。 */
+export interface BotDelegationPendingInteraction {
+ requestId: string;
+ kind: BotDelegationInteractionKind;
+ /** 人话摘要:要批的是什么 / 问的是什么 / 计划标题。 */
+ summary: string;
+ raisedAt: number;
+}
+
+/** 子任务交出的文件(相对子任务工作目录的路径 + 绝对路径)。 */
+export interface BotDelegationArtifact {
+ path: string;
+ absolutePath: string;
+ status: 'added' | 'modified' | 'deleted' | 'renamed';
+}
+
+export interface BotDelegationCapabilitySnapshot {
+ profileVersion: number;
+ agentKind: 'cc' | 'codex' | 'pi';
+ model: string;
+ capabilitiesSha256: string;
+ identitySha256: string;
+ skills: string[];
+ skillMode: 'inherit' | 'allowlist';
+ mcpServers: string[];
+ mcpMode: 'inherit' | 'allowlist';
+ toolsets: string[];
+ toolsetMode: 'inherit' | 'allowlist';
+ memoryEnabled: boolean;
+}
+
+/**
+ * Execution plan captured before a child task is made visible.
+ *
+ * Bot Profile versions freeze identity, but capability catalogs are mutable.
+ * Delegations therefore persist the exact authorization facts approved at
+ * creation time. Runtime startup and restart recovery must consume this
+ * snapshot instead of re-reading the Bot's current configuration. Authorization and
+ * destination facts remain immutable; only `limits.deadlineAt` may move forward by the
+ * measured time spent waiting for a user decision.
+ *
+ * `targetBotId === null` means the child is a plain Cindy task (not another
+ * Bot): no target Profile freeze, no target-side timeline mirror — the child
+ * session itself is the user-visible workspace.
+ */
+export interface BotDelegationPlanSnapshot {
+ version: 1;
+ createdAt: number;
+ targetBotId: string | null;
+ /**
+ * The target Bot task that received the human-visible delegation transcript.
+ * Frozen at creation so an abnormal canonical recovery never splits the request and result
+ * across two tasks. Absent for plain-Cindy delegations.
+ */
+ targetCanonicalSessionId?: string;
+ /** Frozen target capability facts. Absent for plain-Cindy delegations. */
+ target?: BotDelegationCapabilitySnapshot;
+ access: {
+ contextRefs: string[];
+ };
+ /** Frozen destination for the completion signal. */
+ completionTarget: {
+ parentSessionId: string;
+ };
+ limits: {
+ maxDepth: number;
+ timeoutMs: number;
+ deadlineAt: number;
+ };
+ permission: {
+ /** 子任务实际运行的权限档;Cindy 任务目标从 ask 开始并把交互回调给发起伙伴。 */
+ mode: string;
+ requesterMode: string | null;
+ targetConfigured: 'ask' | 'trusted';
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
+}
+
+function isCapabilitySnapshot(target: unknown): target is BotDelegationCapabilitySnapshot {
+ if (!isRecord(target)) return false;
+ return (
+ typeof target.profileVersion === 'number'
+ && (target.agentKind === 'cc' || target.agentKind === 'codex' || target.agentKind === 'pi')
+ && typeof target.model === 'string'
+ && typeof target.capabilitiesSha256 === 'string'
+ && typeof target.identitySha256 === 'string'
+ && isStringArray(target.skills)
+ && (target.skillMode === 'inherit' || target.skillMode === 'allowlist')
+ && isStringArray(target.mcpServers)
+ && (target.mcpMode === 'inherit' || target.mcpMode === 'allowlist')
+ && isStringArray(target.toolsets)
+ && (target.toolsetMode === 'inherit' || target.toolsetMode === 'allowlist')
+ && typeof target.memoryEnabled === 'boolean'
+ );
+}
+
+/** Strict parser: malformed or pre-v1 plans are never silently reinterpreted. */
+export function parseBotDelegationPlanSnapshot(
+ value: string | Record<string, unknown> | null | undefined,
+): BotDelegationPlanSnapshot | null {
+ let parsed: unknown = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value) as unknown;
+ } catch {
+ return null;
+ }
+ }
+ if (!isRecord(parsed) || parsed.version !== 1) return null;
+ const access = parsed.access;
+ const limits = parsed.limits;
+ const permission = parsed.permission;
+ const completionTarget = parsed.completionTarget;
+ if (
+ typeof parsed.createdAt !== 'number'
+ || (parsed.targetBotId !== null && typeof parsed.targetBotId !== 'string')
+ || !isRecord(access)
+ || !isRecord(limits)
+ || !isRecord(permission)
+ || !isRecord(completionTarget)
+ || typeof completionTarget.parentSessionId !== 'string'
+ ) return null;
+ if (
+ parsed.targetCanonicalSessionId !== undefined
+ && (
+ typeof parsed.targetCanonicalSessionId !== 'string'
+ || parsed.targetCanonicalSessionId.length === 0
+ )
+ ) return null;
+ if (parsed.targetBotId !== null && !isCapabilitySnapshot(parsed.target)) return null;
+ if (parsed.targetBotId === null && parsed.target !== undefined) return null;
+ if (!isStringArray(access.contextRefs)) return null;
+ if (
+ typeof limits.maxDepth !== 'number'
+ || typeof limits.timeoutMs !== 'number'
+ || typeof limits.deadlineAt !== 'number'
+ || typeof permission.mode !== 'string'
+ || permission.mode.length === 0
+ || (permission.requesterMode !== null && typeof permission.requesterMode !== 'string')
+ || (permission.targetConfigured !== 'ask' && permission.targetConfigured !== 'trusted')
+ ) return null;
+ return parsed as unknown as BotDelegationPlanSnapshot;
+}
+
+export interface BotDelegationView {
+ id: string;
+ requestingBotId: string;
+ /** null = 委派给一条普通 Cindy 任务。 */
+ targetBotId: string | null;
+ targetBotName: string;
+ parentSessionId: string | null;
+ childSessionId: string | null;
+ /** The actual child Session title, including a caller-supplied task name. */
+ title: string;
+ objective: string;
+ contextRefs: string[];
+ permissionSnapshot: Record<string, unknown>;
+ lineage: string[];
+ targetProfileVersion: number | null;
+ depth: number;
+ status: BotDelegationStatus;
+ /** 只在 waiting 时非空。 */
+ pendingInteraction: BotDelegationPendingInteraction | null;
+ resultSummary: string | null;
+ /** Remote task cards omit host-only absolute paths. Local artifacts retain them. */
+ artifacts: Array<Omit<BotDelegationArtifact, 'absolutePath'> & { absolutePath?: string }>;
+ lastError: string | null;
+ createdAt: number;
+ acceptedAt: number | null;
+ completedAt: number | null;
+ updatedAt: number;
+}
+
+export interface BotDelegationChangedPayload {
+ delegationId: string;
+ parentSessionId: string | null;
+ childSessionId: string | null;
+ status: BotDelegationStatus;
+ pendingInteraction?: BotDelegationPendingInteraction | null;
+}
+
+export type BotDelegationListResult =
+ | { ok: true; delegations: BotDelegationView[] }
+ | { ok: false; errorCode: string; message: string };
+
+export type BotDelegationCancelResult =
+ | { ok: true; delegationId: string; childSessionId: string | null }
+ | { ok: false; errorCode: string; message: string };
diff --git a/packages/maker-shared/src/botDirectMessage.ts b/packages/maker-shared/src/botDirectMessage.ts
new file mode 100644
index 0000000000..ed16eeba4b
--- /dev/null
+++ b/packages/maker-shared/src/botDirectMessage.ts
@@ -0,0 +1,79 @@
+export type BotDirectMessageThreadStatus = 'active' | 'closed';
+export type BotDirectMessageCloseReason = 'message-limit' | 'idle-timeout' | null;
+
+export interface BotDirectMessageMeta {
+ v: 1;
+ threadId: string;
+ viewerBotId: string;
+ peerBotId: string;
+ peerBotName: string;
+ direction: 'sent' | 'received';
+ sequence: number;
+ preview: string;
+}
+
+export interface BotDirectMessageItem {
+ id: string;
+ sequence: number;
+ senderBotId: string;
+ senderBotName: string;
+ recipientBotId: string;
+ recipientBotName: string;
+ content: string;
+ createdAt: number;
+}
+
+export interface BotDirectMessageThreadView {
+ id: string;
+ botAId: string;
+ botAName: string;
+ botBId: string;
+ botBName: string;
+ status: BotDirectMessageThreadStatus;
+ closeReason: BotDirectMessageCloseReason;
+ messageCount: number;
+ maxMessages: number;
+ createdAt: number;
+ updatedAt: number;
+ closedAt: number | null;
+ messages: BotDirectMessageItem[];
+}
+
+export type BotDirectMessageThreadResult =
+ | { ok: true; thread: BotDirectMessageThreadView }
+ | { ok: false; errorCode: string; message: string };
+
+export interface BotDirectMessageChangedPayload {
+ threadId: string;
+ participantBotIds: [string, string];
+}
+
+export function readBotDirectMessageMeta(value: unknown): BotDirectMessageMeta | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const raw = value as Record<string, unknown>;
+ if (raw.v !== 1) return null;
+ if (typeof raw.threadId !== 'string' || !raw.threadId) return null;
+ if (typeof raw.viewerBotId !== 'string' || !raw.viewerBotId) return null;
+ if (typeof raw.peerBotId !== 'string' || !raw.peerBotId) return null;
+ if (typeof raw.peerBotName !== 'string') return null;
+ if (raw.direction !== 'sent' && raw.direction !== 'received') return null;
+ if (typeof raw.sequence !== 'number' || !Number.isInteger(raw.sequence) || raw.sequence < 1) {
+ return null;
+ }
+ if (typeof raw.preview !== 'string') return null;
+ return {
+ v: 1,
+ threadId: raw.threadId,
+ viewerBotId: raw.viewerBotId,
+ peerBotId: raw.peerBotId,
+ peerBotName: raw.peerBotName,
+ direction: raw.direction,
+ sequence: raw.sequence,
+ preview: raw.preview,
+ };
+}
+
+export const BOT_DIRECT_MESSAGE_CLIENT_ID = {
+ timelineAnchor: (threadId: string, deliveryId: string, sessionId: string) =>
+ `bot-dm-thread:${threadId}:${deliveryId}:${sessionId}`,
+} as const;