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(provider-group): 手机与远程控制的模型列表收起组里的电脑,归组的任务在组那一项里换模型不换电脑

Lizi4594882cacd8
diff --git a/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts b/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
index e84b774c5c..432e14e7ab 100644
--- a/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
@@ -8,6 +8,7 @@ import { encodeReliableFrames, MAX_FRAME_BYTES, MAX_TRANSPORT_MESSAGE_BYTES, PRO
import type { ProviderGroupConfig, ProviderGroupMember } from '../../../shared/providerGroup';
import {
parseProviderGroupRemoteRequest,
+ parseProviderGroupRemoteSessionGroup,
providerGroupUsageRowsForWire,
PROVIDER_GROUP_REMOTE_MAX_USAGE_ROWS,
PROVIDER_GROUP_REMOTE_MAX_USAGE_REPORT_ROWS,
@@ -75,6 +76,7 @@ function deps(overrides: Partial<ProviderGroupRemoteHandlerDeps> = {}) {
isRemoteAllowed: () => true,
now: () => now,
replaceReportedUsage: vi.fn(),
+ sessionGroup: vi.fn(async () => null),
...overrides,
} satisfies ProviderGroupRemoteHandlerDeps;
return {
@@ -243,6 +245,7 @@ describe('provider-group:remote', () => {
isRemoteAllowed: () => true,
now: () => now,
replaceReportedUsage: vi.fn(),
+ sessionGroup: async () => null,
} satisfies ProviderGroupRemoteHandlerDeps;
const first = handleProviderGroupRemote(d, 'laptop', { ...PICK, exclude: [] });
const second = handleProviderGroupRemote(d, 'desktop', { ...PICK, sessionId: 's2', exclude: [] });
@@ -251,6 +254,30 @@ describe('provider-group:remote', () => {
expect(new Set(picked).size).toBe(2);
});
+ it('answers which group a task on this computer belongs to, read-only', async () => {
+ const sessionGroup = vi.fn(async (sessionId: string) =>
+ (sessionId === 's1' ? { groupDeviceId: 'studio', providerId: 'anthropic' } : null));
+ const d = deps({ sessionGroup });
+ expect(await handleProviderGroupRemote(d, 'phone', { action: 'session-group', sessionId: 's1' }))
+ .toEqual({ group: { groupDeviceId: 'studio', providerId: 'anthropic' } });
+ expect(await handleProviderGroupRemote(d, 'phone', { action: 'session-group', sessionId: 's2' }))
+ .toEqual({ group: null });
+ // 只读:不碰分配器与负载,也不看这台有没有组。
+ expect(d.router.pick).not.toHaveBeenCalled();
+ expect(d.router.markCooling).not.toHaveBeenCalled();
+ await expect(handleProviderGroupRemote(d, 'phone', { action: 'session-group', sessionId: '../x' }))
+ .rejects.toThrow('[INVALID_PARAMS]');
+ // 问的一方读回包:格式不对一律按没归组。
+ expect(parseProviderGroupRemoteSessionGroup({ group: { groupDeviceId: null, providerId: 'anthropic' } }))
+ .toEqual({ groupDeviceId: null, providerId: 'anthropic' });
+ expect(parseProviderGroupRemoteSessionGroup({ group: { providerId: 'anthropic' } }))
+ .toEqual({ groupDeviceId: null, providerId: 'anthropic' });
+ for (const bad of [null, {}, { group: null }, { group: { groupDeviceId: 'share:x', providerId: 'a' } },
+ { group: { groupDeviceId: 'studio', providerId: '../a' } }, { group: { groupDeviceId: 3, providerId: 'a' } }]) {
+ expect(parseProviderGroupRemoteSessionGroup(bad)).toBeNull();
+ }
+ });
+
it('drops a pick when the account changed while it waited for the directory', async () => {
const d = deps();
d.router.pick.mockImplementationOnce(async (input: ProviderGroupPickInput) => {
diff --git a/apps/desktop/src/main/provider-group/remoteHandler.ts b/apps/desktop/src/main/provider-group/remoteHandler.ts
index d87276ace8..5eeee5af6f 100644
--- a/apps/desktop/src/main/provider-group/remoteHandler.ts
+++ b/apps/desktop/src/main/provider-group/remoteHandler.ts
@@ -7,6 +7,8 @@
*
* 只服务同账号电脑(dispatch 已拒绝受邀者与共享任务访客),且只对仍「允许被远程调用」的供应商提供组:
* 没开放的供应商对其他电脑本来就不可见。
+ *
+ * 另有一个只读查询发给任务所在的电脑(不论它有没有组):手机与远程控制问这台电脑上的某个任务此刻归哪个组(§10)。
*/
import { PROVIDER_RUNNING_TURNS_FIELD } from '@cindy/device-link';
@@ -16,7 +18,9 @@ import {
providerGroupSummaryForWire,
type ProviderGroupConfig,
type ProviderGroupRemotePick,
+ type ProviderGroupRemoteSessionGroup,
type ProviderGroupRemoteUsageRow,
+ type ProviderGroupSessionGroup,
type ProviderGroupUsagePartAck,
type ProviderGroupView,
} from '../../shared/providerGroup.js';
@@ -36,6 +40,8 @@ export interface ProviderGroupRemoteHandlerDeps {
now(): number;
/** 同账号电脑报告来的用量:整体替换那台从 sinceDay 起的行(记进当前账号的按使用方账本)。 */
replaceReportedUsage(controller: string, sinceDay: string | null, rows: ProviderGroupRemoteUsageRow[]): void;
+ /** 这台电脑上的任务此刻归哪个组(只读本机记录,读不到为 null)。 */
+ sessionGroup(sessionId: string): Promise<ProviderGroupSessionGroup>;
}
/** 每个账号、每台报告来的电脑最近收下的用量报告序号(乱序到达的旧份丢弃)。按账号的负载对象区分账号。 */
@@ -98,8 +104,11 @@ export async function handleProviderGroupRemote(
deps: ProviderGroupRemoteHandlerDeps,
controller: string,
raw: unknown,
-): Promise<ProviderGroupRemotePick | ProviderGroupView | ProviderGroupUsagePartAck | Record<string, never>> {
+): Promise<
+ ProviderGroupRemotePick | ProviderGroupView | ProviderGroupUsagePartAck | ProviderGroupRemoteSessionGroup | Record<string, never>
+> {
const request = parseProviderGroupRemoteRequest(raw);
+ if (request.action === 'session-group') return { group: await deps.sessionGroup(request.sessionId) };
const scope = deps.scope();
switch (request.action) {
case 'pick': {
diff --git a/apps/desktop/src/main/provider-group/remoteRegistration.ts b/apps/desktop/src/main/provider-group/remoteRegistration.ts
index e301581c7d..43e5b37b7d 100644
--- a/apps/desktop/src/main/provider-group/remoteRegistration.ts
+++ b/apps/desktop/src/main/provider-group/remoteRegistration.ts
@@ -12,7 +12,11 @@ import {
sharedProviderGroupSize,
type ProviderGroupRemoteHandlerDeps,
} from './remoteHandler.js';
-import { getProviderGroupOwnerScope, readProviderRunningTurnsByProvider } from './runtime.js';
+import {
+ getProviderGroupOwnerScope,
+ readProviderGroupOfSession,
+ readProviderRunningTurnsByProvider,
+} from './runtime.js';
import { readProviderGroup } from './store.js';
export function registerProviderGroupRemoteHandler(): void {
@@ -23,6 +27,7 @@ export function registerProviderGroupRemoteHandler(): void {
now: () => Date.now(),
replaceReportedUsage: (controller, sinceDay, rows) =>
currentProviderPartyUsageStore().replaceReported(controller, sinceDay, rows),
+ sessionGroup: readProviderGroupOfSession,
};
setProviderGroupRemoteHandler({
handle: (controller, raw) => handleProviderGroupRemote(deps, controller, raw),
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroupCurrentTask.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroupCurrentTask.test.tsx
index d048706fe1..dfbac204d3 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroupCurrentTask.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroupCurrentTask.test.tsx
@@ -8,7 +8,8 @@
* 选模型 = 留在 grok-bot-vm 只换模型(带那台上的供应商 id),不把 Agent 挪到 Mac Mini;
* 2. 没归组、只是直接用着那台的任务:同样收进组里,但组那一项不显示为正在用,选它照旧是挪过去;
* 3. 组所在电脑离线(组那一项不在):那台照常单独显示、照常选中;
- * 4. 归组的任务就在这台电脑上运行:打开同样先停在组那一项,在里面选模型留在这台。
+ * 4. 归组的任务就在这台电脑上运行:打开同样先停在组那一项,在里面选模型留在这台;
+ * 5. 远程控制 Mac Mini 上的任务(组就建在被控电脑上):同样问得到归组,在组那一项里选模型留在 grok-bot-vm。
*/
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import React from 'react';
@@ -273,4 +274,38 @@ describe('任务正跑在组里的某台电脑上', () => {
expect.objectContaining({ providerId: 'anthropic-local', modelId: 'sonnet', agentDevice: null }),
);
});
+
+ it('远程控制被控电脑上归组的任务:组那一项是被控电脑自己的供应商,在里面选模型留在 grok-bot-vm', async () => {
+ const onRelocate = vi.fn(async () => true);
+ // 被控电脑回答「归它自己建的组」:位置是任务所在电脑视角,null = 被控电脑自己的供应商。
+ const readProviderGroup = vi.fn(async () => ({ deviceId: null, providerId: 'anthropic' }));
+ render(
+ React.createElement(ModelSelectorContent, {
+ modelId: 'opus',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ currentProviderId: 'anthropic-9z',
+ onProviderChange: vi.fn(),
+ actualRoute: true,
+ vendorKey: 'cc',
+ deviceId: 'mini',
+ remoteAgent: {
+ devices: [{ deviceId: 'vm', name: 'grok-bot-vm' }],
+ selectedDeviceId: 'vm',
+ homeDeviceId: 'mini',
+ homeDeviceName: 'Mac Mini',
+ onRelocate,
+ readProviderGroup,
+ },
+ }),
+ );
+ await act(async () => {});
+ expect(screen.queryByRole('button', { name: 'Anthropic · grok-bot-vm' })).toBeNull();
+ expect(row('Opus').getAttribute('aria-selected')).toBe('true');
+ await click(row('Sonnet'));
+ expect(onRelocate).toHaveBeenCalledWith(
+ expect.objectContaining({ providerId: 'anthropic-9z', modelId: 'sonnet', agentDevice: { deviceId: 'vm', name: 'grok-bot-vm' } }),
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index b80fb04546..c287af015a 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -7199,10 +7199,10 @@ export function ChatInput({
selfDeviceId: selfDeviceId ?? null,
...(taskComputerModelMemory ? { localModelMemory: taskComputerModelMemory } : {}),
deviceModelMemory: agentDeviceModelMemoryAccessors,
- // 归组的任务在组那一项下显示与选择(provider-groups.md §10)。组的绑定记在任务所在电脑上,被控电脑上的
- // 任务不读(那台的绑定不对控制端开放),按没归组的处理;挂着换位置的意图时下一条消息就不在原处了,也不按组显示。
- ...(!deviceLinkDeviceId && intentAgentDeviceId === undefined
- ? { readProviderGroup: () => readSessionProviderGroup(sessionId) }
+ // 归组的任务在组那一项下显示与选择(provider-groups.md §10)。组的绑定记在任务所在电脑上:被控电脑上的
+ // 任务经设备互联问那台(旧版本问不到按没归组处理);挂着换位置的意图时下一条消息就不在原处了,也不按组显示。
+ ...(intentAgentDeviceId === undefined
+ ? { readProviderGroup: () => readSessionProviderGroup(sessionId, deviceLinkDeviceId || undefined) }
: {}),
onRelocate: async (selection) => {
if (!(await confirmAgentRelocation(selection.agentDevice))) return false;
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index a15c4c0287..5e38c93ead 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -1607,10 +1607,13 @@ function ModelSelectorContentView({
};
}, [readProviderGroup, remoteAgentDeviceId, currentProviderId]);
// 归的组那一项此刻在列表里(组所在电脑在线、组还在)才按组显示;不然照常列出任务实际所在的那台。
+ // 任务所在电脑自己建的组:本机任务看本机设置,被控电脑上的任务看那台目录里的组摘要。
const boundEntry = useMemo(() => {
if (!boundGroup) return null;
const visible = boundGroup.deviceId === null
- ? !homeDeviceId && localProviderGroups[boundGroup.providerId] !== undefined
+ ? homeDeviceId
+ ? remoteProviderGroups.groups.has(remoteProviderEntryKey(homeDeviceId, boundGroup.providerId))
+ : localProviderGroups[boundGroup.providerId] !== undefined
: remoteProviderGroups.groups.has(remoteProviderEntryKey(boundGroup.deviceId, boundGroup.providerId));
return visible ? boundGroup : null;
}, [boundGroup, homeDeviceId, localProviderGroups, remoteProviderGroups]);
diff --git a/apps/desktop/src/renderer/features/provider-group/sessionProviderGroup.ts b/apps/desktop/src/renderer/features/provider-group/sessionProviderGroup.ts
index 4498fec45f..f3ef49f3ac 100644
--- a/apps/desktop/src/renderer/features/provider-group/sessionProviderGroup.ts
+++ b/apps/desktop/src/renderer/features/provider-group/sessionProviderGroup.ts
@@ -1,17 +1,43 @@
/**
* 这个任务此刻归哪个供应商组(provider-groups.md §10):模型列表把归组的任务显示在组那一项下,在组那一项里
- * 选模型时留在此刻运行的那台。只问本机(组的绑定记在任务所在电脑上),读不到按没归组处理。
+ * 选模型时留在此刻运行的那台。组的绑定记在任务所在电脑上:本机任务问本机,被控电脑上的任务经设备互联问
+ * 那台(`provider-group:remote` 的只读 `session-group`)。读不到(含旧版本)按没归组处理。
*/
+import { PROVIDER_GROUP_REMOTE_CHANNEL } from '@cindy/device-link';
+
import type { RemoteProviderGroupEntry } from '@/lib/remoteProviderGroups';
-import type { ProviderGroupSessionGroup } from '../../../shared/providerGroup';
+import {
+ parseProviderGroupRemoteSessionGroup,
+ type ProviderGroupSessionGroup,
+} from '../../../shared/providerGroup';
-export async function readSessionProviderGroup(sessionId: string): Promise<RemoteProviderGroupEntry | null> {
- const api = window.electronAPI?.providerGroup;
- if (typeof api?.command !== 'function') return null;
+/**
+ * @param hostDeviceId 任务所在的被控电脑;本机任务不传。返回的位置是任务所在电脑视角(`deviceId` 为 null =
+ * 那台自己的供应商,与模型列表里任务所在电脑那一栏一致)。
+ */
+export async function readSessionProviderGroup(
+ sessionId: string,
+ hostDeviceId?: string,
+): Promise<RemoteProviderGroupEntry | null> {
try {
- const group = (await api.command({ action: 'session-group', sessionId })) as ProviderGroupSessionGroup;
- return group ? { deviceId: group.groupDeviceId, providerId: group.providerId } : null;
+ let group: ProviderGroupSessionGroup;
+ if (hostDeviceId) {
+ const deviceLink = window.electronAPI?.deviceLink;
+ if (typeof deviceLink?.invoke !== 'function') return null;
+ group = parseProviderGroupRemoteSessionGroup(
+ await deviceLink.invoke(hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [{ action: 'session-group', sessionId }]),
+ );
+ } else {
+ const api = window.electronAPI?.providerGroup;
+ if (typeof api?.command !== 'function') return null;
+ group = (await api.command({ action: 'session-group', sessionId })) as ProviderGroupSessionGroup;
+ }
+ if (!group) return null;
+ return {
+ deviceId: hostDeviceId && group.groupDeviceId === hostDeviceId ? null : group.groupDeviceId,
+ providerId: group.providerId,
+ };
} catch {
return null;
}
diff --git a/apps/desktop/src/shared/providerGroup.ts b/apps/desktop/src/shared/providerGroup.ts
index b996e42245..a2fa3a53a2 100644
--- a/apps/desktop/src/shared/providerGroup.ts
+++ b/apps/desktop/src/shared/providerGroup.ts
@@ -332,7 +332,17 @@ export type ProviderGroupRemoteRequest =
*/
| { action: 'usage'; seq: number; sinceDay: string | null; rows: ProviderGroupRemoteUsageRow[] }
/** 新动作防止旧端忽略分批字段后把半份报告当整份替换。offset 从 0 开始,收齐 total 才提交。 */
- | { action: 'usage-part'; seq: number; sinceDay: string | null; offset: number; total: number; rows: ProviderGroupRemoteUsageRow[] };
+ | { action: 'usage-part'; seq: number; sinceDay: string | null; offset: number; total: number; rows: ProviderGroupRemoteUsageRow[] }
+ /**
+ * 只读:这台电脑上的某个任务此刻归哪个组(手机与远程控制的模型列表用,provider-groups.md §10)。
+ * 发给任务所在的电脑,不是组所在电脑。
+ */
+ | { action: 'session-group'; sessionId: string };
+
+/** `session-group` 的回包:坐标是任务所在电脑视角(`groupDeviceId` 为 null = 那台自己建的组)。 */
+export interface ProviderGroupRemoteSessionGroup {
+ group: ProviderGroupSessionGroup;
+}
export type ProviderGroupRemotePick =
/** 那个供应商现在没有组(组被删了或旧版本):照常直接在组所在电脑上运行。 */
@@ -460,6 +470,8 @@ export function parseProviderGroupRemoteRequest(raw: unknown): ProviderGroupRemo
|| report.rows.length === 0 || (value.offset as number) + report.rows.length > (value.total as number)) invalidRemote('invalid usage offset');
return { action: 'usage-part', ...report, offset: value.offset as number, total: value.total as number };
}
+ case 'session-group':
+ return { action: 'session-group', sessionId: remoteSessionId(value.sessionId) };
default:
invalidRemote('unknown provider group action');
}
@@ -481,6 +493,22 @@ export function parseProviderGroupRemotePick(raw: unknown, groupProviderId: stri
};
}
+/** 读任务所在电脑 `session-group` 的回包;格式不对按没归组处理。坐标仍是那台电脑视角。 */
+export function parseProviderGroupRemoteSessionGroup(raw: unknown): ProviderGroupSessionGroup {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const group = (raw as Record<string, unknown>).group;
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return null;
+ const value = group as Record<string, unknown>;
+ const groupDeviceId = value.groupDeviceId ?? null;
+ if (groupDeviceId !== null && (
+ typeof groupDeviceId !== 'string'
+ || !DEVICE_ID_PATTERN.test(groupDeviceId)
+ || isProviderShareAgentDeviceId(groupDeviceId)
+ )) return null;
+ if (!isProviderGroupProviderId(value.providerId)) return null;
+ return { groupDeviceId, providerId: value.providerId };
+}
+
const MEMBER_STATES: readonly ProviderGroupMemberState[] = ['available', 'full', 'paused', 'cooling', 'offline', 'unavailable'];
const UNAVAILABLE_REASONS: readonly ProviderGroupUnavailableReason[] = ['provider-off', 'disconnected', 'share-paused', 'share-removed'];
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index e18143fa4c..8e7534844e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -374,6 +374,7 @@ import {
} from '@/session/sessionAgentSwitch';
import { formatProviderAccountLabel, resolveSessionUsageAccount } from '@/session/sessionUsageAccount';
import { useRemoteAgentCatalogs } from '@/session/useRemoteAgentCatalogs';
+import { useSessionProviderGroup } from '@/session/useSessionProviderGroup';
import {
drainComposerAnnotationSubmissions,
drainComposerAttachments,
@@ -2636,6 +2637,22 @@ export default function SessionScreen() {
keepDeviceIds: remoteAgentKeepDeviceIds,
keepOnly: !(agentLocationMovable && modelSheetOpen),
});
+ // 供应商组(provider-groups.md §10):这个任务此刻归哪个组,选择器每次打开问一次被控电脑。归组的任务在组那一项里
+ // 选模型 = 留在此刻运行的那台只换模型(不弹换电脑确认);挂着换电脑的意图时下一条消息就不在原处,不按组显示。
+ const currentProviderId = currentSession?.providerId ?? null;
+ const sessionProviderGroup = useSessionProviderGroup({
+ enabled: agentLocationMovable && modelSheetOpen && !intentChangesAgentLocation(agentSwitchIntent),
+ hostDeviceId: deviceId,
+ sessionId,
+ routeKey: JSON.stringify([currentAgentDeviceId, currentProviderId]),
+ });
+ const remoteProviderGroup = useMemo(
+ () => ({
+ bound: sessionProviderGroup,
+ running: { deviceId: currentAgentDeviceId, providerId: currentProviderId },
+ }),
+ [sessionProviderGroup, currentAgentDeviceId, currentProviderId],
+ );
// 协同 Worker 的模型选择器:与任务模型列表同一份远程供应商(其他电脑与分享),Worker 的 Agent
// 现在选的位置即使掉线也保留。只在 Worker 选择器打开时读。
const workerAgentKeepDeviceIds = useMemo(
@@ -9707,7 +9724,15 @@ export default function SessionScreen() {
onSelect: selectUnifiedComposerModel,
// 远程 Agent:其他电脑上开放了远程调用的供应商接在后面,每个供应商一段、标题带电脑名。
...(agentLocationMovable
- ? { remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: nextAgentDeviceId } }
+ ? {
+ remote: {
+ catalogs: remoteAgentCatalogs,
+ selectedDeviceId: nextAgentDeviceId,
+ // 供应商组:组里其他电脑收进组那一项;归组的任务在组那一项里选模型留在此刻运行的那台。
+ hostDeviceId: deviceId,
+ providerGroup: remoteProviderGroup,
+ },
+ }
: {}),
}}
activeModelId={modelSheetSelection.model}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index a3f8fb1ed1..0a7a4b868e 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -6985,7 +6985,14 @@ export default function NewRemoteSessionScreen() {
// 远程 Agent / 供应商分享:其他电脑开放了远程调用的供应商与别人分享给这台电脑的供应商接在
// 后面,每个供应商一段、标题带电脑名。旧被控电脑上协同草稿与它们互斥(见 collabEligible)。
...(remoteAgentSupported && (!collabDraft || workerAgentLocationSupported)
- ? { remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: remoteAgentPick?.deviceId ?? null } }
+ ? {
+ remote: {
+ catalogs: remoteAgentCatalogs,
+ selectedDeviceId: remoteAgentPick?.deviceId ?? null,
+ // 供应商组:组里其他电脑收进组那一项,新任务开始后由组选一台(provider-groups.md §10)。
+ hostDeviceId: selectedDeviceId,
+ },
+ }
: {}),
}}
activeModelId={remoteAgentPick?.model ?? draft.model}
diff --git a/apps/mobile/src/__tests__/remoteProviderGroups.test.ts b/apps/mobile/src/__tests__/remoteProviderGroups.test.ts
new file mode 100644
index 0000000000..93e2cd2835
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteProviderGroups.test.ts
@@ -0,0 +1,105 @@
+/**
+ * 手机模型列表里的供应商组(provider-groups.md §10,与桌面 remoteProviderGroups 同口径):组里其他电脑上的这个供应商
+ * 收进组那一项,被控电脑自己的照常显示;任务归哪个组由被控电脑回答。
+ */
+import type { ProviderView } from '@cindy/model-providers/registry';
+import { describe, expect, it } from 'vitest';
+
+import {
+ collectMobileProviderGroups,
+ parseSessionProviderGroup,
+ providerGroupEntryKey,
+} from '@/session/remoteProviderGroups';
+
+const provider = (id: string, extra: Record<string, unknown> = {}) =>
+ ({ id, name: id, models: {}, connected: true, remoteInvocationEnabled: true, ...extra }) as unknown as ProviderView;
+const summary = (owner: string, members: Array<{ kind: string; agentDeviceId: string | null; providerId: string }>) => ({
+ group: {
+ strategy: 'least',
+ autoSwitch: true,
+ members: [
+ { key: 'local', kind: 'local', agentDeviceId: null, providerId: owner, paused: false },
+ ...members.map((m) => ({ key: `${m.kind}:${m.agentDeviceId}:${m.providerId}`, ...m, paused: false })),
+ ],
+ },
+});
+
+describe('collectMobileProviderGroups', () => {
+ it('folds members of another computer’s group into the group entry', () => {
+ const groups = collectMobileProviderGroups({
+ hostDeviceId: 'host',
+ hostProviders: [provider('account')],
+ catalogs: [
+ {
+ deviceId: 'mini',
+ providers: [provider('anthropic', summary('anthropic', [
+ { kind: 'device', agentDeviceId: 'vm', providerId: 'anthropic-9z' },
+ // 被控电脑自己的供应商在组里也照常显示,不收起。
+ { kind: 'device', agentDeviceId: 'host', providerId: 'account' },
+ { kind: 'share', agentDeviceId: 'share:abc', providerId: 'claude' },
+ ]))],
+ },
+ { deviceId: 'vm', providers: [provider('anthropic-9z'), provider('fp')] },
+ ],
+ });
+ expect([...groups.hidden].sort()).toEqual([
+ providerGroupEntryKey('share:abc', 'claude'),
+ providerGroupEntryKey('vm', 'anthropic-9z'),
+ ].sort());
+ expect(groups.memberOf.get(providerGroupEntryKey('vm', 'anthropic-9z'))).toEqual({ deviceId: 'mini', providerId: 'anthropic' });
+ expect(groups.sizes.get(providerGroupEntryKey('mini', 'anthropic'))).toBe(4);
+ expect(groups.hidden.has(providerGroupEntryKey(null, 'account'))).toBe(false);
+ });
+
+ it('labels the controlled computer’s own group and shared groups, and keeps entries that carry a group', () => {
+ const groups = collectMobileProviderGroups({
+ hostDeviceId: 'host',
+ hostProviders: [provider('account', summary('account', [{ kind: 'device', agentDeviceId: 'vm', providerId: 'anthropic-9z' }]))],
+ catalogs: [
+ // vm 自己也建了组:本身带组的项不收起(两个组互相包含时两个组都还在)。
+ { deviceId: 'vm', providers: [provider('anthropic-9z', summary('anthropic-9z', [{ kind: 'device', agentDeviceId: 'host', providerId: 'account' }]))] },
+ { deviceId: 'share:abc', providers: [provider('claude', { groupSize: 3 })] },
+ ],
+ });
+ expect(groups.sizes.get(providerGroupEntryKey(null, 'account'))).toBe(2);
+ expect(groups.sizes.get(providerGroupEntryKey('share:abc', 'claude'))).toBe(3);
+ expect(groups.hidden.size).toBe(0);
+ });
+
+ it('ignores groups of providers closed to remote use and malformed summaries', () => {
+ const groups = collectMobileProviderGroups({
+ hostDeviceId: 'host',
+ hostProviders: [],
+ catalogs: [{
+ deviceId: 'mini',
+ providers: [
+ provider('closed', { remoteInvocationEnabled: false, ...summary('closed', [{ kind: 'device', agentDeviceId: 'vm', providerId: 'a' }]) }),
+ provider('broken', { group: { members: 'nope' } }),
+ provider('mixed', { group: { members: [{ kind: 'share', agentDeviceId: 'vm', providerId: 'a' }, { kind: 'device', agentDeviceId: 'vm', providerId: 'b' }] } }),
+ ],
+ }],
+ });
+ expect([...groups.hidden]).toEqual([providerGroupEntryKey('vm', 'b')]);
+ expect(groups.sizes.has(providerGroupEntryKey('mini', 'closed'))).toBe(false);
+ expect(groups.sizes.has(providerGroupEntryKey('mini', 'broken'))).toBe(false);
+ });
+});
+
+describe('parseSessionProviderGroup', () => {
+ it('maps the controlled computer’s answer onto the picker’s positions', () => {
+ expect(parseSessionProviderGroup({ group: { groupDeviceId: 'mini', providerId: 'anthropic' } }, 'host'))
+ .toEqual({ deviceId: 'mini', providerId: 'anthropic' });
+ // 组建在被控电脑自己身上。
+ expect(parseSessionProviderGroup({ group: { groupDeviceId: null, providerId: 'account' } }, 'host'))
+ .toEqual({ deviceId: null, providerId: 'account' });
+ expect(parseSessionProviderGroup({ group: { groupDeviceId: 'host', providerId: 'account' } }, 'host'))
+ .toEqual({ deviceId: null, providerId: 'account' });
+ });
+
+ it('treats old computers and malformed answers as not in a group', () => {
+ for (const raw of [undefined, null, {}, { group: null }, [], { group: { providerId: '../x' } },
+ { group: { groupDeviceId: 'a b', providerId: 'x' } }, { group: { groupDeviceId: 7, providerId: 'x' } }]) {
+ expect(parseSessionProviderGroup(raw, 'host')).toBeNull();
+ }
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
index 9e35a64deb..a272639435 100644
--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
@@ -13,7 +13,9 @@ describe('new task remote Agent wiring', () => {
// 位置时协同草稿与之不互斥,旧被控电脑仍互斥。
expect(source).toContain('const remoteAgentCatalogs = useRemoteAgentCatalogs({');
expect(source).toContain('...(remoteAgentSupported && (!collabDraft || workerAgentLocationSupported)');
- expect(source).toContain('remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: remoteAgentPick?.deviceId ?? null }');
+ expect(source).toContain('catalogs: remoteAgentCatalogs,\n selectedDeviceId: remoteAgentPick?.deviceId ?? null,');
+ // 供应商组:组里其他电脑收进组那一项(按被控电脑的目录比)。
+ expect(source).toContain('hostDeviceId: selectedDeviceId,');
expect(source).toContain('&& (remoteAgentPick === null || workerAgentLocationSupported);');
expect(source).toContain('&& capabilities?.supportsOrcaWorkerAgentDevice === true;');
// 选中远程行单独记;选本机行清掉。
@@ -80,8 +82,14 @@ describe('session Agent switch UI wiring', () => {
expect(source).toContain("Object.prototype.hasOwnProperty.call(currentSession, 'agentDeviceId')");
// 模型列表另列其他电脑的供应商,选中态跟着下一条消息时 Agent 所在的电脑。
expect(source).toContain(
- '? { remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: nextAgentDeviceId } }',
+ 'catalogs: remoteAgentCatalogs,\n selectedDeviceId: nextAgentDeviceId,',
);
+ // 供应商组:归组的任务在组那一项里选模型留在此刻运行的那台;挂着换电脑的意图时不按组显示。
+ expect(source).toContain('providerGroup: remoteProviderGroup,');
+ expect(source).toContain(
+ 'enabled: agentLocationMovable && modelSheetOpen && !intentChangesAgentLocation(agentSwitchIntent),',
+ );
+ expect(source).toContain('running: { deviceId: currentAgentDeviceId, providerId: currentProviderId },');
// 顶部常驻说明已去掉,由换电脑前的二次确认代替。
expect(source).not.toContain('notice={agentLocationNotice}');
diff --git a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
index 48c0bd6186..763e34aeb0 100644
--- a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
+++ b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
@@ -4,7 +4,9 @@ import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { UnifiedModelPickerSheet } from '@/session/UnifiedModelPickerSheet';
vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-uuid' }));
-const test = vi.hoisted(() => ({ view: null as any, favoritesReady:true, quotas:{} as any, syncError:null as unknown, prefs: {favorites:[],engines:{}} as any, save: vi.fn(), entries: [] as any[] }));
+const test = vi.hoisted(() => ({ view: null as any, favoritesReady:true, quotas:{} as any, syncError:null as unknown, prefs: {favorites:[],engines:{}} as any, save: vi.fn(), entries: [] as any[],
+ // 按传入的目录派生(供应商组用例:每台电脑的供应商各有自己的行与正在用的来源);缺省用上面的固定值。
+ entriesFor: null as null | ((providers: any[]) => any[]), activeSource: null as null | ((input: any) => string | null) }));
vi.mock('@/session/UnifiedModelPickerView', () => ({ UnifiedModelPickerView: (p:any) => {test.view=p;return null;} }));
vi.mock('@/session/useMobileModelQuotas',()=>({useMobileModelQuotas:()=>({quotas:test.quotas,now:0})}));
vi.mock('@/session/mobileModelPreferences', async () => {
@@ -15,15 +17,15 @@ vi.mock('@/session/mobileModelPreferences', async () => {
save:async (value:typeof test.prefs)=>{await test.save(value);refresh();}};
}};
});
-vi.mock('@/session/providerModelSections', () => ({buildMobileModelSections:()=>({activeSourceId:'account'})}));
+vi.mock('@/session/providerModelSections', () => ({buildMobileModelSections:(input:any)=>({activeSourceId:test.activeSource?test.activeSource(input):'account'})}));
vi.mock('@/session/draftModelMemory',()=>({useDraftModelMemoryVersion:()=>0}));
vi.mock('@/session/sessionModelMirror',()=>({useSessionModelMirrorVersion:()=>0}));
vi.mock('@/session/modelPickerRows',()=>({budgetRowDisabled:()=>false,presentPickerPrice:()=>null}));
-vi.mock('@/session/unifiedMobileModels',async importOriginal=>({...await importOriginal<any>(),mobileUnifiedEntries:()=>test.entries}));
+vi.mock('@/session/unifiedMobileModels',async importOriginal=>({...await importOriginal<any>(),mobileUnifiedEntries:(providers:any[])=>test.entriesFor?test.entriesFor(providers):test.entries}));
vi.mock('react-i18next',()=>({useTranslation:()=>({t:(key:string)=>key})}));
(globalThis as any).IS_REACT_ACT_ENVIRONMENT=true;
let root:ReturnType<typeof createRoot>;
-beforeEach(()=>{test.favoritesReady=true;test.syncError=null;test.quotas={};test.save.mockReset().mockImplementation(async value => {test.prefs=value;});test.prefs={favorites:[],engines:{}};test.entries=[{
+beforeEach(()=>{test.favoritesReady=true;test.syncError=null;test.quotas={};test.entriesFor=null;test.activeSource=null;test.save.mockReset().mockImplementation(async value => {test.prefs=value;});test.prefs={favorites:[],engines:{}};test.entries=[{
providerId:'account',modelId:'model',displayName:'Model',candidates:['codex','claude-code'],recommended:'codex',nativeAgent:'codex',
capabilities:{codex:{wireModelId:'codex/model',efforts:['medium','high'],defaultEffort:'medium',supportsFastMode:true,contextWindow:200000},
'claude-code':{wireModelId:'model',efforts:['medium','high'],defaultEffort:'medium',supportsFastMode:false,contextWindow:200000}},
@@ -605,3 +607,70 @@ it('keeps settings of another computer\'s rows out of this phone\'s preferences'
await act(async()=>test.view.onSelect(test.view.groups[1].rows[0]));
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({effort:'high'}),{deviceId:'device-studio-mac'});
});
+
+// 供应商组(provider-groups.md §10,与桌面同口径):Mac Mini 把 Anthropic 建成了组(Mac Mini 自己 + grok-bot-vm),
+// 任务被组分到 grok-bot-vm 上运行。手机同样把 grok-bot-vm 的 Anthropic 收进组那一项;归组的任务在组那一项里
+// 选模型 = 留在 grok-bot-vm 只换模型,不当成换电脑。
+const groupProvider = (id:string,name:string,extra:Record<string,unknown>={}) =>
+ ({id,name,models:{},connected:true,remoteInvocationEnabled:true,...extra});
+const groupSummary = (owner:string,members:{agentDeviceId:string,providerId:string}[]) => ({group:{strategy:'least',autoSwitch:true,members:[
+ {key:'local',kind:'local',agentDeviceId:null,providerId:owner,paused:false},
+ ...members.map(m=>({key:`device:${m.agentDeviceId}:${m.providerId}`,kind:'device',...m,paused:false})),
+]}});
+const miniCatalog = {deviceId:'mini',name:'Mac Mini',status:'ready',
+ providers:[groupProvider('anthropic','Anthropic',groupSummary('anthropic',[{agentDeviceId:'vm',providerId:'anthropic-9z'}]))]};
+const vmCatalog = {deviceId:'vm',name:'grok-bot-vm',status:'ready',
+ providers:[groupProvider('anthropic-9z','Anthropic'),groupProvider('fp','FP')]};
+const miniGroupId = 'remote:["mini","anthropic"]';
+const vmMemberId = 'remote:["vm","anthropic-9z"]';
+async function mountGroup(options:{bound?:{deviceId:string|null,providerId:string}|null,host?:any[],catalogs?:any[]},onSelect=vi.fn(async()=>true)) {
+ test.entriesFor = providers => providers.map((provider:any)=>({...test.entries[0],providerId:provider.id}));
+ test.activeSource = input => input.providers.some((provider:any)=>provider.id===input.selectedProviderId) ? input.selectedProviderId : null;
+ await act(async()=>root.render(createElement(UnifiedModelPickerSheet,{
+ visible:true,onClose:vi.fn(),providers:options.host??[{id:'account',name:'Provider',models:{},connected:true}],agentKind:'codex',capabilities:{hasFastMode:true},
+ activeModelId:'codex/model',selectedProviderId:'anthropic-9z',selectedEffort:'medium',selectedFastMode:false,
+ existingSessionRoute:true,modelMemory:{getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()},
+ unified:{scope:'user-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect,
+ remote:{catalogs:options.catalogs??[miniCatalog,vmCatalog],selectedDeviceId:'vm',hostDeviceId:'host',
+ providerGroup:{bound:options.bound??null,running:{deviceId:'vm',providerId:'anthropic-9z'}}}},
+ } as any)));
+ return {onSelect};
+}
+it('folds a group member into the group entry and opens there without marking it as in use',async()=>{
+ const {onSelect}=await mountGroup({bound:null});
+ // 组里的那台不单独出现,那台组外的供应商照常列出;组那一项标题带台数。
+ expect(test.view.filters.map((f:any)=>f.id)).not.toContain(vmMemberId);
+ expect(test.view.filters.map((f:any)=>f.id)).toContain('remote:["vm","fp"]');
+ expect(test.view.filters.find((f:any)=>f.id===miniGroupId).remote.providerLabel).toBe('models.unified.providerGroup');
+ // 任务正跑在组员上:打开停在组那一项,但没归组,不显示为正在用。
+ expect(test.view.filter).toBe(miniGroupId);
+ expect(test.view.groups.map((g:any)=>g.key)).toEqual([miniGroupId]);
+ expect(test.view.groups[0].title).toBe('models.unified.remoteProviderGroup');
+ expect(test.view.groups[0].rows[0].selected).toBe(false);
+ // 选它照旧是把 Agent 挪到组所在电脑(由调用方确认换电脑)。
+ await act(async()=>test.view.onSelect(test.view.groups[0].rows[0]));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({providerId:'anthropic'}),{deviceId:'mini'});
+});
+it('keeps a task that belongs to the group on the computer it runs on',async()=>{
+ const {onSelect}=await mountGroup({bound:{deviceId:'mini',providerId:'anthropic'}});
+ expect(test.view.filter).toBe(miniGroupId);
+ expect(test.view.groups[0].rows[0].selected).toBe(true);
+ await act(async()=>test.view.onSelect(test.view.groups[0].rows[0]));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({providerId:'anthropic-9z',modelId:'codex/model'}),{deviceId:'vm'});
+});
+it('shows the group entry of the controlled computer itself and stays put inside it',async()=>{
+ const host=[groupProvider('account','Provider',groupSummary('account',[{agentDeviceId:'vm',providerId:'anthropic-9z'}]))];
+ const {onSelect}=await mountGroup({bound:{deviceId:null,providerId:'account'},host,catalogs:[vmCatalog]});
+ expect(test.view.filters.map((f:any)=>f.id)).not.toContain(vmMemberId);
+ expect(test.view.filter).toBe('account');
+ const group=test.view.groups.find((g:any)=>g.key==='account');
+ expect(group.title).toBe('models.unified.providerGroup');
+ expect(group.rows[0].selected).toBe(true);
+ await act(async()=>test.view.onSelect(group.rows[0]));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({providerId:'anthropic-9z'}),{deviceId:'vm'});
+});
+it('lists the member again when the group owner is not in the list',async()=>{
+ await mountGroup({bound:{deviceId:'mini',providerId:'anthropic'},catalogs:[vmCatalog]});
+ expect(test.view.filter).toBe(vmMemberId);
+ expect(test.view.groups[0].rows[0].selected).toBe(true);
+});
diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.json
index 8bc6bdef58..03ff9f45bc 100644
--- a/apps/mobile/src/i18n/locales/en/models.json
+++ b/apps/mobile/src/i18n/locales/en/models.json
@@ -92,6 +92,10 @@
"recommended": "Recommended",
"source": "Source",
"remoteProvider": "{{provider}} · {{device}}",
+ "remoteProviderGroup": "{{provider}} · {{device}} · {{group}}",
+ "providerGroup": "{{provider}} · {{group}}",
+ "groupBadge_one": "Provider Group · {{count}} computer",
+ "groupBadge_other": "Provider Group · {{count}} computers",
"harness": "Harness",
"restoreRecommended": "Restore recommended",
"saveFailed": "Could not save. Please try again.",
diff --git a/apps/mobile/src/i18n/locales/ja/models.json b/apps/mobile/src/i18n/locales/ja/models.json
index 8a90953a49..f6a0570b2e 100644
--- a/apps/mobile/src/i18n/locales/ja/models.json
+++ b/apps/mobile/src/i18n/locales/ja/models.json
@@ -92,6 +92,10 @@
"recommended": "おすすめ",
"source": "接続元",
"remoteProvider": "{{provider}} · {{device}}",
+ "remoteProviderGroup": "{{provider}} · {{device}} · {{group}}",
+ "providerGroup": "{{provider}} · {{group}}",
+ "groupBadge_one": "プロバイダーグループ · {{count}} 台のパソコン",
+ "groupBadge_other": "プロバイダーグループ · {{count}} 台のパソコン",
"harness": "Harness",
"restoreRecommended": "推奨設定に戻す",
"saveFailed": "保存できませんでした。再試行してください。",
diff --git a/apps/mobile/src/i18n/locales/ko/models.json b/apps/mobile/src/i18n/locales/ko/models.json
index 765fb15390..6241eba2ae 100644
--- a/apps/mobile/src/i18n/locales/ko/models.json
+++ b/apps/mobile/src/i18n/locales/ko/models.json
@@ -92,6 +92,10 @@
"recommended": "추천",
"source": "공급원",
"remoteProvider": "{{provider}} · {{device}}",
+ "remoteProviderGroup": "{{provider}} · {{device}} · {{group}}",
+ "providerGroup": "{{provider}} · {{group}}",
+ "groupBadge_one": "제공자 그룹 · 컴퓨터 {{count}}대",
+ "groupBadge_other": "제공자 그룹 · 컴퓨터 {{count}}대",
"harness": "Harness",
"restoreRecommended": "권장 설정 복원",
"saveFailed": "저장하지 못했습니다. 다시 시도하세요.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/models.json b/apps/mobile/src/i18n/locales/zh-CN/models.json
index cf46b4996b..11b56c4379 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/models.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json
@@ -92,6 +92,10 @@
"recommended": "推荐",
"source": "来源",
"remoteProvider": "{{provider}} · {{device}}",
+ "remoteProviderGroup": "{{provider}} · {{device}} · {{group}}",
+ "providerGroup": "{{provider}} · {{group}}",
+ "groupBadge_one": "供应商组 · {{count}} 台电脑",
+ "groupBadge_other": "供应商组 · {{count}} 台电脑",
"harness": "Harness",
"restoreRecommended": "恢复推荐",
"saveFailed": "未能保存,请重试。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/models.json b/apps/mobile/src/i18n/locales/zh-TW/models.json
index 532a9c0430..e157d232c3 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/models.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/models.json
@@ -92,6 +92,10 @@
"recommended": "推薦",
"source": "來源",
"remoteProvider": "{{provider}} · {{device}}",
+ "remoteProviderGroup": "{{provider}} · {{device}} · {{group}}",
+ "providerGroup": "{{provider}} · {{group}}",
+ "groupBadge_one": "供應商組 · {{count}} 台電腦",
+ "groupBadge_other": "供應商組 · {{count}} 台電腦",
"harness": "Harness",
"restoreRecommended": "恢復推薦",
"saveFailed": "無法儲存,請重試。",
diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
index ec0cbd5bd1..26605bae8d 100644
--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
@@ -30,9 +30,20 @@ import { budgetRowDisabled, presentPickerPrice } from "./modelPickerRows";
import { mobileWeeklyQuota } from "./mobileModelRowPresentation";
import { mobileAgentLabel } from "./sessionAgentSwitch";
import type { RemoteAgentCatalog } from "./remoteAgentCatalogs";
+import {
+ collectMobileProviderGroups,
+ providerGroupEntryKey,
+ type MobileProviderGroupEntry,
+ type MobileProviderGroups,
+} from "./remoteProviderGroups";
import { remoteFilterId } from "./remoteSourceFilters";
const NO_REMOTE_CATALOGS: readonly RemoteAgentCatalog[] = [];
+const NO_PROVIDER_GROUPS: MobileProviderGroups = {
+ hidden: new Set(),
+ sizes: new Map(),
+ memberOf: new Map(),
+};
function createFavoriteUid(): string {
const cryptoWithUuid = globalThis.crypto as Crypto | undefined;
@@ -72,6 +83,19 @@ export interface UnifiedMobilePickerOptions {
catalogs: readonly RemoteAgentCatalog[];
/** 当前选中态(下一条消息时 Agent 所在电脑)属于哪份目录;null = 被控电脑。 */
selectedDeviceId: string | null;
+ /**
+ * 被控电脑的设备 id:按目录里的组摘要把组里其他电脑上的这个供应商收进组那一项,标题带台数
+ * (provider-groups.md §10)。缺省 = 不收起。
+ */
+ hostDeviceId?: string;
+ /**
+ * 已建任务:这个任务此刻归哪个组(null = 没归组)与 Agent 此刻在哪台、用哪个供应商(null = 被控电脑)。
+ * 归组的任务在组那一项里显示为正在用的,在里面选模型 = 留在此刻运行的那台、只换模型。
+ */
+ providerGroup?: {
+ bound: MobileProviderGroupEntry | null;
+ running: { deviceId: string | null; providerId: string | null };
+ };
};
/** source.deviceId = 这一行来自哪台电脑的目录(null / 缺省 = 被控电脑)。 */
onSelect(
@@ -178,6 +202,8 @@ export function UnifiedModelPickerSheet(
>(new Map());
// 打开时 Agent 在另一台电脑:目录读到后停在那台电脑的当前供应商上(用户先手动换过就不再跳)。
const initialRemoteFilter = useRef(false);
+ // 用户这次打开后自己点过来源:归组的任务读回来得晚,也不再把列表挪到组那一项。
+ const filterTouched = useRef(false);
const [favoriteEdit, setFavoriteEdit] = useState<{
original: MobileModelFavorite;
config: MobileModelConfiguration;
@@ -196,6 +222,7 @@ export function UnifiedModelPickerSheet(
setQuery("");
setFilter("all");
initialRemoteFilter.current = true;
+ filterTouched.current = false;
setTarget(null);
setRemoteConfigs(new Map());
setFavoriteEdit(null);
@@ -229,6 +256,43 @@ export function UnifiedModelPickerSheet(
}),
[p.selectedProviderId, p.activeModelId, p.agentKind],
);
+ // 供应商组(provider-groups.md §10):组里其他电脑上的这个供应商收进组那一项,只列组那一项。
+ const hostDeviceId = p.unified.remote?.hostDeviceId;
+ const providerGroups = useMemo(
+ () =>
+ hostDeviceId
+ ? collectMobileProviderGroups({
+ hostDeviceId,
+ hostProviders: p.providers,
+ catalogs: remoteCatalogs,
+ })
+ : NO_PROVIDER_GROUPS,
+ [hostDeviceId, p.providers, remoteCatalogs],
+ );
+ // 任务归的组那一项此刻在列表里(组所在电脑在线、组还在)才按组显示。此刻不在组那一项本身上运行时
+ // (被组分到或换到了组里另一台),组那一项显示为正在用的,在里面选模型 = 留在那台只换模型。
+ const groupInfo = p.unified.remote?.providerGroup;
+ const boundCandidate = groupInfo?.bound ?? null;
+ const boundEntry =
+ boundCandidate &&
+ providerGroups.sizes.has(
+ providerGroupEntryKey(boundCandidate.deviceId, boundCandidate.providerId),
+ )
+ ? boundCandidate
+ : null;
+ const stayInGroup =
+ !!boundEntry &&
+ !!groupInfo?.running.providerId &&
+ !(
+ boundEntry.deviceId === groupInfo.running.deviceId &&
+ boundEntry.providerId === groupInfo.running.providerId
+ );
+ const boundGroup = stayInGroup ? boundEntry : null;
+ const boundKeepModel = useMemo(
+ () =>
+ boundGroup ? { ...keepModel, providerId: boundGroup.providerId } : undefined,
+ [boundGroup, keepModel],
+ );
const entries = useMemo(
() =>
mobileUnifiedEntries(
@@ -236,7 +300,11 @@ export function UnifiedModelPickerSheet(
p.unified.agents,
p.modelVisibilityOverrides,
!!p.existingSessionRoute,
- selectedDeviceId === null ? keepModel : undefined,
+ boundGroup?.deviceId === null
+ ? boundKeepModel
+ : selectedDeviceId === null
+ ? keepModel
+ : undefined,
),
[
p.providers,
@@ -244,60 +312,87 @@ export function UnifiedModelPickerSheet(
p.modelVisibilityOverrides,
p.existingSessionRoute,
keepModel,
+ boundKeepModel,
+ boundGroup,
selectedDeviceId,
],
);
- // 另一台电脑的目录:每台按自己的供应商与可见性派生,选中态只落在 Agent 所在那台。
+ /** Agent 下一条消息时所在的那台电脑上正在用的来源(那台在组里被收起时照样算出来,用来停在组那一项)。 */
+ const selectedCatalog = selectedDeviceId
+ ? remoteCatalogs.find((catalog) => catalog.deviceId === selectedDeviceId)
+ : undefined;
+ const selectedSourceId =
+ selectedCatalog && selectedCatalog.providers.length > 0
+ ? buildMobileModelSections({
+ providers: selectedCatalog.providers,
+ agentKind: p.agentKind,
+ selectedModelId: p.activeModelId,
+ selectedProviderId: p.selectedProviderId,
+ existingSessionRoute: p.existingSessionRoute,
+ visibilityOverrides: selectedCatalog.modelVisibilityOverrides,
+ }).activeSourceId
+ : null;
+ // 另一台电脑的目录:每台按自己的供应商与可见性派生,选中态只落在 Agent 所在那台(那台被收进组里时
+ // 不在任何一行上;归组的任务落在组那一项上)。
const remoteDirectories = useMemo(
() =>
remoteCatalogs.flatMap((catalog) => {
- if (catalog.providers.length === 0) return [];
+ const providers = catalog.providers.filter(
+ (provider) =>
+ !providerGroups.hidden.has(
+ providerGroupEntryKey(catalog.deviceId, provider.id),
+ ),
+ );
+ if (providers.length === 0) return [];
const selectedHere = catalog.deviceId === selectedDeviceId;
+ const boundHere = boundGroup?.deviceId === catalog.deviceId;
+ const visibleSource =
+ selectedHere &&
+ selectedSourceId &&
+ providers.some((provider) => provider.id === selectedSourceId)
+ ? selectedSourceId
+ : null;
return [
{
- catalog,
+ catalog: providers.length === catalog.providers.length
+ ? catalog
+ : { ...catalog, providers },
entries: mobileUnifiedEntries(
- catalog.providers,
+ providers,
p.unified.agents,
catalog.modelVisibilityOverrides,
!!p.existingSessionRoute,
- selectedHere ? keepModel : undefined,
+ boundHere ? boundKeepModel : selectedHere ? keepModel : undefined,
),
- sourceId: selectedHere
- ? buildMobileModelSections({
- providers: catalog.providers,
- agentKind: p.agentKind,
- selectedModelId: p.activeModelId,
- selectedProviderId: p.selectedProviderId,
- existingSessionRoute: p.existingSessionRoute,
- visibilityOverrides: catalog.modelVisibilityOverrides,
- }).activeSourceId
- : null,
+ sourceId: boundHere ? boundGroup!.providerId : visibleSource,
},
];
}),
[
remoteCatalogs,
+ providerGroups,
selectedDeviceId,
+ selectedSourceId,
+ boundGroup,
keepModel,
+ boundKeepModel,
p.unified.agents,
p.existingSessionRoute,
- p.selectedProviderId,
- p.activeModelId,
- p.agentKind,
],
);
const sourceId =
- selectedDeviceId === null
- ? buildMobileModelSections({
- providers: p.providers,
- agentKind: p.agentKind,
- selectedModelId: p.activeModelId,
- selectedProviderId: p.selectedProviderId,
- existingSessionRoute: p.existingSessionRoute,
- visibilityOverrides: p.modelVisibilityOverrides,
- }).activeSourceId
- : null;
+ boundGroup?.deviceId === null
+ ? boundGroup.providerId
+ : selectedDeviceId === null
+ ? buildMobileModelSections({
+ providers: p.providers,
+ agentKind: p.agentKind,
+ selectedModelId: p.activeModelId,
+ selectedProviderId: p.selectedProviderId,
+ existingSessionRoute: p.existingSessionRoute,
+ visibilityOverrides: p.modelVisibilityOverrides,
+ }).activeSourceId
+ : null;
const selection: MobileModelConfiguration = {
providerId: sourceId ?? "",
modelId: p.activeModelId,
@@ -421,21 +516,41 @@ export function UnifiedModelPickerSheet(
);
return entry ? [makeRow(entry, item)] : [];
});
+ // 供应商组只写组里有几台,不写是哪几台(provider-groups.md §10):「Claude · 供应商组 · 3 台电脑」。
+ const groupBadge = (deviceId: string | null, id: string) => {
+ const size = providerGroups.sizes.get(providerGroupEntryKey(deviceId, id));
+ return size === undefined
+ ? null
+ : t("models.unified.groupBadge", { count: size });
+ };
+ const withGroupBadge = (deviceId: string | null, id: string, name: string) => {
+ const group = groupBadge(deviceId, id);
+ return group
+ ? t("models.unified.providerGroup", { provider: name, group })
+ : name;
+ };
const providerName = (id: string) => {
const provider = p.providers.find((item) => item.id === id);
if (!provider) return id;
- return mobileProviderAccountTitle(provider);
+ return withGroupBadge(null, id, mobileProviderAccountTitle(provider));
};
// 另一台电脑目录里的供应商,说法带电脑名(「Claude 订阅 · 工作室 Mac」)。
- const remoteProviderName = (catalog: RemoteAgentCatalog, id: string) => {
+ const remoteAccountTitle = (catalog: RemoteAgentCatalog, id: string) => {
const provider = catalog.providers.find((item) => item.id === id);
return provider ? mobileProviderAccountTitle(provider) : id;
};
- const remoteProviderLabel = (catalog: RemoteAgentCatalog, id: string) =>
- t("models.unified.remoteProvider", {
- provider: remoteProviderName(catalog, id),
+ const remoteProviderName = (catalog: RemoteAgentCatalog, id: string) =>
+ withGroupBadge(catalog.deviceId, id, remoteAccountTitle(catalog, id));
+ const remoteProviderLabel = (catalog: RemoteAgentCatalog, id: string) => {
+ const values = {
+ provider: remoteAccountTitle(catalog, id),
device: catalog.name,
- });
+ };
+ const group = groupBadge(catalog.deviceId, id);
+ return group
+ ? t("models.unified.remoteProviderGroup", { ...values, group })
+ : t("models.unified.remoteProvider", values);
+ };
const makeRemoteRow = (
directory: (typeof remoteDirectories)[number],
entry: UnifiedModelEntry,
@@ -502,13 +617,30 @@ export function UnifiedModelPickerSheet(
`${row.entry.displayName} ${row.entry.modelId} ${row.entry.description ?? ""} ${rowProviderName(row)}`
.toLocaleLowerCase()
.includes(query.trim().toLocaleLowerCase());
- const all = query.trim() || filter === "all";
+ // 停在(或点过)一个被收进组里的来源时,改看收着它的组那一项:组摘要读到得晚,刚打开时可能先停在了组员上。
+ const groupFilterOf = (entry: MobileProviderGroupEntry) =>
+ entry.deviceId === null
+ ? entry.providerId
+ : remoteFilterId(entry.deviceId, entry.providerId);
+ const hiddenFilterTarget = (() => {
+ for (const catalog of remoteCatalogs)
+ for (const provider of catalog.providers)
+ if (remoteFilterId(catalog.deviceId, provider.id) === filter) {
+ const entry = providerGroups.memberOf.get(
+ providerGroupEntryKey(catalog.deviceId, provider.id),
+ );
+ return entry ? groupFilterOf(entry) : null;
+ }
+ return null;
+ })();
+ const shownFilter = hiddenFilterTarget ?? filter;
+ const all = query.trim() || shownFilter === "all";
const filtered = rows.filter(
- (row) => matches(row) && (all || filter === row.entry.providerId),
+ (row) => matches(row) && (all || shownFilter === row.entry.providerId),
);
const groups: UnifiedMobileGroup[] = [];
const favoriteRows = favorites.filter(matches);
- if ((all || filter === "favorites") && favoriteRows.length)
+ if ((all || shownFilter === "favorites") && favoriteRows.length)
groups.push({
key: "favorites",
title: t("models.unified.favorites"),
@@ -526,7 +658,7 @@ export function UnifiedModelPickerSheet(
title: t("models.unified.recommended"),
rows: recommended,
});
- if (all || filter !== "favorites")
+ if (all || shownFilter !== "favorites")
for (const provider of p.providers) {
const group = filtered.filter(
(row) =>
@@ -543,7 +675,7 @@ export function UnifiedModelPickerSheet(
for (const { catalog, rows: deviceRows } of remoteRows)
for (const provider of catalog.providers) {
const id = remoteFilterId(catalog.deviceId, provider.id);
- if (!all && filter !== id) continue;
+ if (!all && shownFilter !== id) continue;
const group = deviceRows.filter(
(row) => row.entry.providerId === provider.id && matches(row),
);
@@ -660,11 +792,30 @@ export function UnifiedModelPickerSheet(
setBusy(false);
}
};
+ /**
+ * 归组的任务在组那一项里选的行:留在此刻运行的那台(换成那台上这个供应商的 id),只换模型,不把 Agent
+ * 挪到组所在电脑(与桌面同口径)。不是这种行返回 null。
+ */
+ const boundRoute = (
+ row: UnifiedMobileRow,
+ config: MobileModelConfiguration,
+ ): [MobileModelConfiguration, { deviceId: string | null }] | null => {
+ const running = groupInfo?.running;
+ return boundGroup &&
+ running?.providerId &&
+ (row.remoteDevice?.deviceId ?? null) === boundGroup.deviceId &&
+ row.entry.providerId === boundGroup.providerId
+ ? [{ ...config, providerId: running.providerId }, { deviceId: running.deviceId }]
+ : null;
+ };
const select = (row: UnifiedMobileRow) => {
if (row.disabled) return;
void transact(async (isCurrent) => {
- const source = { deviceId: row.remoteDevice?.deviceId ?? null };
- if ((await p.unified.onSelect(row.config, source)) && isCurrent())
+ const [config, source] = boundRoute(row, row.config) ?? [
+ row.config,
+ { deviceId: row.remoteDevice?.deviceId ?? null },
+ ];
+ if ((await p.unified.onSelect(config, source)) && isCurrent())
p.onClose();
});
};
@@ -683,7 +834,9 @@ export function UnifiedModelPickerSheet(
void transact(async (isCurrent) => {
if (
row.selected &&
- !(await p.unified.onSelect(config, { deviceId: remoteDevice.deviceId }))
+ !(await p.unified.onSelect(
+ ...(boundRoute(row, config) ?? [config, { deviceId: remoteDevice.deviceId }]),
+ ))
)
return;
if (!isCurrent() || row.selected) return;
@@ -696,6 +849,11 @@ export function UnifiedModelPickerSheet(
});
return;
}
+ // 被控电脑自己的组那一项(任务归它、此刻在组里别的电脑上运行)里的行同样留在那台。
+ const apply = (next: MobileModelConfiguration) => {
+ const routed = boundRoute(row, next);
+ return routed ? p.unified.onSelect(...routed) : p.unified.onSelect(next);
+ };
void transact(async (isCurrent) => {
const previousConfig =
row.favorite && sameConfiguration(row.config, live)
@@ -703,7 +861,7 @@ export function UnifiedModelPickerSheet(
: row.selected
? selection
: undefined;
- if (previousConfig && !(await p.unified.onSelect(config))) return;
+ if (previousConfig && !(await apply(config))) return;
// Selection can await remote work or a confirmation. Do not begin another
// write for a panel that closed or changed its binding while waiting.
if (!isCurrent()) return;
@@ -763,8 +921,7 @@ export function UnifiedModelPickerSheet(
),
);
} catch (error) {
- if (previousConfig && isCurrent())
- await p.unified.onSelect(previousConfig);
+ if (previousConfig && isCurrent()) await apply(previousConfig);
throw error;
}
});
@@ -803,15 +960,11 @@ export function UnifiedModelPickerSheet(
},
})),
);
- const selectedDirectory = remoteDirectories.find(
- (directory) => directory.catalog.deviceId === selectedDeviceId,
- );
- const selectedCatalogStatus = remoteCatalogs.find(
- (catalog) => catalog.deviceId === selectedDeviceId,
- )?.status;
+ const selectedCatalogStatus = selectedCatalog?.status;
+ // 那台被收进组里时同样先停在它上面,随即按 shownFilter 改看组那一项。
const selectedRemoteFilter =
- selectedDeviceId && selectedDirectory?.sourceId
- ? remoteFilterId(selectedDeviceId, selectedDirectory.sourceId)
+ selectedDeviceId && selectedSourceId
+ ? remoteFilterId(selectedDeviceId, selectedSourceId)
: null;
useEffect(() => {
if (!p.visible || !initialRemoteFilter.current) return;
@@ -825,6 +978,13 @@ export function UnifiedModelPickerSheet(
initialRemoteFilter.current = false;
if (selectedRemoteFilter) setFilter(selectedRemoteFilter);
}, [p.visible, selectedDeviceId, selectedCatalogStatus, selectedRemoteFilter]);
+ // 归组的任务打开即停在组那一项(组的归属读回来得晚也挪过去,用户自己点过来源就不再挪)。
+ const boundFilter = boundGroup ? groupFilterOf(boundGroup) : null;
+ useEffect(() => {
+ if (!p.visible || filterTouched.current || !boundFilter) return;
+ initialRemoteFilter.current = false;
+ setFilter(boundFilter);
+ }, [p.visible, boundFilter]);
return (
<UnifiedModelPickerView
visible={p.visible}
@@ -849,9 +1009,10 @@ export function UnifiedModelPickerSheet(
testID={p.testID ?? "modelSheet"}
query={query}
onQuery={setQuery}
- filter={filter}
+ filter={shownFilter}
onFilter={(value) => {
initialRemoteFilter.current = false;
+ filterTouched.current = true;
setFilter(value);
}}
filters={[
diff --git a/apps/mobile/src/session/providerShareAgentDevice.ts b/apps/mobile/src/session/providerShareAgentDevice.ts
new file mode 100644
index 0000000000..503c740e95
--- /dev/null
+++ b/apps/mobile/src/session/providerShareAgentDevice.ts
@@ -0,0 +1,8 @@
+/** 任务记录里「Agent 在某个分享者的电脑上」的设备 id 前缀(与桌面同构:`share:<shareId>`)。 */
+export const PROVIDER_SHARE_AGENT_DEVICE_PREFIX = 'share:';
+
+export function isProviderShareAgentDeviceId(deviceId: string | null | undefined): deviceId is string {
+ return typeof deviceId === 'string'
+ && deviceId.length > PROVIDER_SHARE_AGENT_DEVICE_PREFIX.length
+ && deviceId.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX);
+}
diff --git a/apps/mobile/src/session/remoteAgentCatalogs.ts b/apps/mobile/src/session/remoteAgentCatalogs.ts
index f9ca8bbe57..1db4776c4b 100644
--- a/apps/mobile/src/session/remoteAgentCatalogs.ts
+++ b/apps/mobile/src/session/remoteAgentCatalogs.ts
@@ -11,6 +11,8 @@ import type { ProviderView } from '@cindy/model-providers/registry';
import { toDeviceListItems } from '@/device-link/devices';
import type { ProviderShareCatalogEntry } from '@/device-link/providerShareCatalogCache';
+import { isProviderShareAgentDeviceId } from './providerShareAgentDevice';
+
/** 一台可选电脑的目录状态(providers 只含开了远程调用的供应商)。 */
export interface RemoteAgentCatalog {
deviceId: string;
@@ -51,14 +53,7 @@ export function selectRemoteAgentDevices(input: {
}));
}
-/** 任务记录里「Agent 在某个分享者的电脑上」的设备 id 前缀(与桌面同构:`share:<shareId>`)。 */
-export const PROVIDER_SHARE_AGENT_DEVICE_PREFIX = 'share:';
-
-export function isProviderShareAgentDeviceId(deviceId: string | null | undefined): deviceId is string {
- return typeof deviceId === 'string'
- && deviceId.length > PROVIDER_SHARE_AGENT_DEVICE_PREFIX.length
- && deviceId.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX);
-}
+export { isProviderShareAgentDeviceId, PROVIDER_SHARE_AGENT_DEVICE_PREFIX } from './providerShareAgentDevice';
/**
* 供应商分享:被控电脑收到的分享,每个分享当作一台「电脑」接在同账号其他电脑之后
diff --git a/apps/mobile/src/session/remoteProviderGroups.ts b/apps/mobile/src/session/remoteProviderGroups.ts
new file mode 100644
index 0000000000..15287bf46c
--- /dev/null
+++ b/apps/mobile/src/session/remoteProviderGroups.ts
@@ -0,0 +1,129 @@
+/**
+ * 模型列表里的供应商组(docs/product-rules/provider-groups.md §10,与桌面 remoteProviderGroups 同口径):
+ * 某台电脑把一个供应商建成了组,组里其他电脑上的这个供应商不再单独列出,只列组那一项,标题带「供应商组 · N 台电脑」。
+ *
+ * - 组摘要只在组所在电脑的目录里(`maker:provider:list` 的 `group` 字段,只给同账号),所以只看此刻列表里有的电脑:
+ * 组所在电脑离线时组那一项不在,组员自然重新单独出现;
+ * - 被控电脑自己的供应商照常显示,不被收起;本身带组的项也不收起(两个组互相包含时两个组都还在);
+ * - 任务此刻正跑在组员上也收起,模型列表停在组那一项(见 memberOf)。
+ *
+ * 位置坐标与选择器一致:deviceId 为 null = 被控电脑自己的目录,其余是其他电脑或分享(`share:<id>`)。
+ */
+import { readProviderShareGroupSize } from '@cindy/device-link';
+import type { ProviderView } from '@cindy/model-providers/registry';
+
+import { isProviderShareAgentDeviceId } from './providerShareAgentDevice';
+import type { RemoteAgentCatalog } from './remoteAgentCatalogs';
+
+/** 组那一项在列表里的位置。 */
+export interface MobileProviderGroupEntry {
+ deviceId: string | null;
+ providerId: string;
+}
+
+export interface MobileProviderGroups {
+ /** 被收起的其他电脑上的供应商(按 providerGroupEntryKey)。 */
+ hidden: ReadonlySet<string>;
+ /** 标成供应商组的项(按 providerGroupEntryKey) → 组里几台电脑;分享来的只有台数。 */
+ sizes: ReadonlyMap<string, number>;
+ /** 被收起的项 → 收着它的组那一项(同时在几个组里时取先列出的那个)。 */
+ memberOf: ReadonlyMap<string, MobileProviderGroupEntry>;
+}
+
+/** 远高于实际组员数,只用来挡异常大的摘要。 */
+const MAX_SUMMARY_MEMBERS = 512;
+
+export function providerGroupEntryKey(deviceId: string | null, providerId: string): string {
+ return JSON.stringify([deviceId, providerId]);
+}
+
+interface SummaryMember {
+ /** 组员所在电脑(组所在电脑视角);null = 组所在电脑自己,就是组那一项本身。 */
+ agentDeviceId: string | null;
+ providerId: string;
+}
+
+/** 目录里某个供应商带的组摘要里的组员;没有组或格式不对返回 null(当作没有组)。 */
+function readSummaryMembers(provider: ProviderView): SummaryMember[] | null {
+ const group = (provider as { group?: unknown }).group;
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return null;
+ const raw = (group as { members?: unknown }).members;
+ if (!Array.isArray(raw)) return null;
+ const members: SummaryMember[] = [];
+ const seen = new Set<string>();
+ for (const entry of raw.slice(0, MAX_SUMMARY_MEMBERS)) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
+ const { kind, agentDeviceId, providerId } = entry as Record<string, unknown>;
+ let member: SummaryMember | null = null;
+ if (kind === 'local') member = { agentDeviceId: null, providerId: provider.id };
+ else if (
+ (kind === 'device' || kind === 'share')
+ && typeof agentDeviceId === 'string' && agentDeviceId.length > 0 && agentDeviceId.length <= 160
+ && (kind === 'share') === isProviderShareAgentDeviceId(agentDeviceId)
+ && typeof providerId === 'string' && providerId.length > 0 && providerId.length <= 128
+ ) member = { agentDeviceId, providerId };
+ if (!member) continue;
+ const key = providerGroupEntryKey(member.agentDeviceId, member.providerId);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ members.push(member);
+ }
+ return members.length > 0 ? members : null;
+}
+
+export function collectMobileProviderGroups(input: {
+ /** 被控电脑:组里的它就是任务所在电脑,按被控电脑那一栏比。 */
+ hostDeviceId: string;
+ /** 被控电脑自己的目录。 */
+ hostProviders: readonly ProviderView[];
+ /** 列表里其他电脑与分享的目录。 */
+ catalogs: readonly Pick<RemoteAgentCatalog, 'deviceId' | 'providers'>[];
+}): MobileProviderGroups {
+ const sizes = new Map<string, number>();
+ const groupKeys = new Set<string>();
+ const memberOf = new Map<string, MobileProviderGroupEntry>();
+ const addGroup = (deviceId: string | null, provider: ProviderView) => {
+ if (provider.remoteInvocationEnabled !== true) return;
+ const key = providerGroupEntryKey(deviceId, provider.id);
+ const members = readSummaryMembers(provider);
+ if (!members) {
+ // 分享来的组只告诉受邀者台数,不给名单(§8)。
+ const shared = deviceId && isProviderShareAgentDeviceId(deviceId) ? readProviderShareGroupSize(provider) : null;
+ if (shared !== null) sizes.set(key, shared);
+ return;
+ }
+ sizes.set(key, members.length);
+ groupKeys.add(key);
+ for (const member of members) {
+ // 组员就是组那一项本身,或是被控电脑自己的供应商(被控电脑那一栏照常显示)。
+ if (member.agentDeviceId === null || member.agentDeviceId === input.hostDeviceId) continue;
+ const memberKey = providerGroupEntryKey(member.agentDeviceId, member.providerId);
+ if (!memberOf.has(memberKey)) memberOf.set(memberKey, { deviceId, providerId: provider.id });
+ }
+ };
+ for (const provider of input.hostProviders) addGroup(null, provider);
+ for (const catalog of input.catalogs) {
+ for (const provider of catalog.providers) addGroup(catalog.deviceId, provider);
+ }
+ for (const key of groupKeys) memberOf.delete(key);
+ return { hidden: new Set(memberOf.keys()), sizes, memberOf };
+}
+
+const DEVICE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
+const PROVIDER_ID = /^[a-zA-Z0-9._-]{1,128}$/;
+
+/**
+ * 读被控电脑 `provider-group:remote` 的 `session-group` 回包 `{ group: { groupDeviceId, providerId } | null }`
+ * (这个任务此刻归哪个组)。坐标换成选择器的:组建在被控电脑自己身上(`groupDeviceId` 为 null 或就是被控电脑)时
+ * 位置为 null。格式不对按没归组处理。
+ */
+export function parseSessionProviderGroup(raw: unknown, hostDeviceId: string): MobileProviderGroupEntry | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const group = (raw as { group?: unknown }).group;
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return null;
+ const { groupDeviceId = null, providerId } = group as { groupDeviceId?: unknown; providerId?: unknown };
+ if (typeof providerId !== 'string' || !PROVIDER_ID.test(providerId)) return null;
+ if (groupDeviceId === null || groupDeviceId === hostDeviceId) return { deviceId: null, providerId };
+ if (typeof groupDeviceId !== 'string' || !DEVICE_ID.test(groupDeviceId)) return null;
+ return { deviceId: groupDeviceId, providerId };
+}
diff --git a/apps/mobile/src/session/useSessionProviderGroup.ts b/apps/mobile/src/session/useSessionProviderGroup.ts
new file mode 100644
index 0000000000..7903e8cbe1
--- /dev/null
+++ b/apps/mobile/src/session/useSessionProviderGroup.ts
@@ -0,0 +1,44 @@
+/**
+ * 这个任务此刻归哪个供应商组(provider-groups.md §10):模型列表把归组的任务显示在组那一项下,在组那一项里选模型
+ * 时留在此刻运行的那台、只换模型。组的绑定记在任务所在的被控电脑上,经 `provider-group:remote` 的只读
+ * `session-group` 问它;旧版本(不认识这个通道或这个动作)、离线或回包不对都按没归组处理。
+ */
+import { useEffect, useState } from 'react';
+
+import { PROVIDER_GROUP_REMOTE_CHANNEL } from '@cindy/device-link';
+
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+
+import { parseSessionProviderGroup, type MobileProviderGroupEntry } from './remoteProviderGroups';
+
+/**
+ * @param enabled 只在模型选择器打开、且没有挂着换电脑的意图时读(挂着时下一条消息就不在原处,不按组显示)。
+ * @param routeKey 任务此刻的位置(电脑 + 供应商):变了重读。
+ */
+export function useSessionProviderGroup(input: {
+ enabled: boolean;
+ hostDeviceId: string;
+ sessionId: string;
+ routeKey: string;
+}): MobileProviderGroupEntry | null {
+ const { invoke } = useDeviceLink();
+ const [state, setState] = useState<{ key: string; entry: MobileProviderGroupEntry | null } | null>(null);
+ const key = JSON.stringify([input.hostDeviceId, input.sessionId, input.routeKey]);
+ useEffect(() => {
+ if (!input.enabled || !input.hostDeviceId || !input.sessionId) return;
+ let cancelled = false;
+ invoke(input.hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [{ action: 'session-group', sessionId: input.sessionId }])
+ .then(
+ (raw) => {
+ if (!cancelled) setState({ key, entry: parseSessionProviderGroup(raw, input.hostDeviceId) });
+ },
+ () => {
+ if (!cancelled) setState({ key, entry: null });
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [input.enabled, input.hostDeviceId, input.sessionId, invoke, key]);
+ return input.enabled && state?.key === key ? state.entry : null;
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1bea403af4..3d3e9f636c 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -825,11 +825,17 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
- `leases { seq, entries: [{ sessionId, providerId, memberKey }] }` → 整体替换 C 正在运行的经组任务,`seq` 只增(C 按时间生成,
重启后仍增大),乱序旧包丢弃,150s 不刷新作废;只用于分摊负载;
- `view { providerId }` → 组设置与组员状态(`ProviderGroupView`)。
+ - `session-group { sessionId }`(只读,2026-10-11)→ `{ group: { groupDeviceId, providerId } | null }`:发给**任务所在的电脑**
+ (不论它有没有组),回答这个任务此刻归哪个组,坐标是那台视角(`groupDeviceId` 为 null = 那台自己建的组)。手机与桌面远程控制
+ 的模型列表据此把归组的任务显示在组那一项下、在组那一项里选模型时留在此刻运行的那台(provider-groups.md §10)。不读写分配器、
+ 负载与绑定。旧版本回 `CHANNEL_NOT_ALLOWED`(没有这个通道)或 `[INVALID_PARAMS] unknown provider group action`(有通道没有这个
+ 动作),控制端一律按没归组处理,即与改动前相同。
旧 O 回 `CHANNEL_NOT_ALLOWED`:`pick` 按 `none` 处理,任务照旧直接在 O 上运行。
- **`maker:provider:list` 新增可选字段 `group`**:只对同账号调用方、只加在建了组且「允许被远程调用」的供应商上:
`{ strategy, autoSwitch, members: [{ key, kind, agentDeviceId, providerId, label?, paused }] }`(并发上限与权重不外发)。
组摘要列着组内电脑,受邀者与共享任务访客拿不到:分享投影里去掉,`scrubSharedProvider` 再兜一层(分享者电脑、受邀者电脑与
- 手机各过一遍)。旧控制端与手机不认识就忽略;新控制端据此在模型列表与设置页收起组员(只看在线电脑的目录)。O 改组后经
+ 手机各过一遍)。旧控制端与手机不认识就忽略;新控制端据此在模型列表与设置页收起组员(只看在线电脑的目录),新手机在模型列表
+ 里同样收起(2026-10-11)。O 改组后经
`maker:provider:changed` 推送让同账号电脑重读目录。
- **远程 Agent open 载荷新增可选 `groupAssigned: true`**(`remote-agent/wire.ts`):任务由供应商组分配到这台(本机的组或另一台的组),
这台直接运行、不再进入它自己的组(防转圈)。旧被控端解码时丢弃(它本来没有组)。
diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.md
index 835f14c0da..4a049f026f 100644
--- a/docs/product-rules/provider-groups.md
+++ b/docs/product-rules/provider-groups.md
@@ -463,15 +463,21 @@
- 任务归这个组(被组分到或换到那台、在组那一项里选的):组那一项里当前模型显示为选中;在组那一项里选模型 = 留在此刻
运行的那台、只换模型(换成那台上这个供应商),不把 Agent 挪到组所在电脑。归组的任务就在任务所在电脑上运行时,打开同样
先停在组那一项;
- - 没归组、只是直接用着那台的任务(建组前直接选的等):组那一项不显示为正在用,选它照旧是把 Agent 挪到组所在电脑;
- - 被控电脑上的任务读不到那台的绑定(绑定不对控制端开放),按没归组的处理;
+ - 没归组、只是直接用着那台的任务(建组前直接选的等):组那一项不显示为正在用,选它照旧是把 Agent 挪到组所在电脑,
+ 先弹换电脑的确认;
+ - 任务归哪个组记在任务所在的电脑上。远程控制另一台电脑上的任务、以及手机,打开模型列表时问任务所在的电脑
+ (2026-10-11 用户确认,此前被控电脑上的任务一律按没归组处理);那台是旧版本问不到时按没归组的处理。挂着换电脑的意图时
+ 下一条消息就不在原处了,不按组显示。组就建在被控电脑上时,组那一项是被控电脑自己那一栏里的这个供应商;
- 设置页里组那一项行内写「供应商组 · {N} 台电脑」,详情只读列出组内电脑与状态(问组所在电脑,每 15 秒重读),
说明组设置要到组所在电脑上改。
状态是组所在电脑看到的;其中「我的其他电脑」组所在电脑看着能用、这台电脑却连不上时(换电脑时由这台直连过去,§4),
状态写「从这台电脑连不上」、圆点不显示可用,运行数照列(2026-10-11);这台读那台的目录每次最多等 3 秒,到点还没结果时
照组所在电脑的状态显示,不拖住整个组的状态。实现见
`apps/desktop/src/main/provider-group/ipc.ts` 的 `markMembersUnreachableHere`。
- - 手机端本期不收起(手机只显示任务实际运行的电脑)。
+ - **手机的模型列表与桌面一致**(2026-10-11 用户要求):已建任务与新任务都按上面的规则把组里的电脑收进组那一项,
+ 分组标题与来源页写「{供应商} · {组所在电脑} · 供应商组 · 3 台电脑」(组在被控电脑上时「{供应商} · 供应商组 · 2 台电脑」);
+ 归组的任务在组那一项里选模型留在此刻运行的那台、不弹换电脑的确认;没归组的任务选组那一项照旧先确认换电脑。手机不显示组那一项
+ 的用量与组内电脑状态。实现见 `apps/mobile/src/session/remoteProviderGroups.ts` 与 `UnifiedModelPickerSheet.tsx`。
- 手机输入框上方的状态与桌面一致(2026-10-11):换电脑、重新连接期间显示「正在换一台电脑继续」「重新连接中 n/5」,不显示
「请求失败」。
- Light 与 Dark 两种模式都要实现。
@@ -483,13 +489,14 @@
- 远程 Agent 协议:新增 §4 的「已由供应商组分配」可选标记(`groupAssigned`);同账号直连新增同账号通道
`provider-group:remote` 与目录里的组摘要;分享的人经组所在电脑中转(P2b)新增 `relay`、`guestRelay` 与 `forget`;
分享的人的「需要换一台」(P2c):任务所在电脑打开任务时声明支持(可选字段 `acceptsGroupSwitch`),组所在电脑只对
- 声明了的电脑在事件流里发出凭证状态(`providerGroupSwitch`),重新打开时带回(`groupSwitchToken`)。其余沿用现有协议,不改服务端。兼容做法见 §14,登记见
+ 声明了的电脑在事件流里发出凭证状态(`providerGroupSwitch`),重新打开时带回(`groupSwitchToken`)。手机与远程控制问任务所在的电脑
+ 「这个任务归哪个组」用同一通道的只读动作 `session-group`(§10)。其余沿用现有协议,不改服务端。兼容做法见 §14,登记见
`docs/dev-rules/protocol-compatibility.md`「供应商组」。
- [跨电脑复制任务](task-device-migration.md) 与已建任务换 Agent 所在电脑:§6.1 的自动换电脑与手动「换一台继续」
都复用现有交接,不新增交接机制。
- [用量上限自动继续](usage-limit-auto-continue.md):冷却的重置时刻口径与之一致;有组时先换电脑,组里所有电脑都失败且其中有
撞上限的,才按该文等最早恢复的一台;组内电脑冷却期间,自动继续不会分到这台。
-- 手机端:首版只显示任务实际运行的电脑,供应商组的设置与用量只在电脑上。
+- 手机端:模型列表与桌面一样收起组里的电脑(§10);供应商组的设置、组内电脑状态与用量只在电脑上。
## 12. 分期
@@ -532,6 +539,7 @@
| 组所在电脑 | 组只在新版本里存在。降级到旧版本后组不生效,这个供应商回到只在本机运行;经组分到其他电脑的任务在旧版本里不能续接,需要换模型或新开任务。同账号其他电脑问它时得到 `CHANNEL_NOT_ALLOWED`、目录里也没有组摘要,当作没有组照常直接连它;已经经它的组分到别处的任务留在原处,成为普通的远程 Agent 任务 |
| 组内电脑 | 照常作为普通的同账号远程供应商或分享来的供应商接任务。「已由供应商组分配」标记对它是不认识的字段,解码时丢弃;它本来没有组,也不会转圈。旧版同账号组内电脑不声明 `guestRelay`,组所在电脑不给它分受邀者的任务(它不会按受邀者隔离);旧版分享来的组内电脑本来就把组所在电脑当受邀者,照常接,只是不按受邀者再细分作用域(组所在电脑自己按受邀者隔离) |
| 同账号其他电脑 | 直连由任务所在的电脑执行,旧版本不认识组:选组所在电脑的这个供应商时直接在组所在电脑上运行(没有组),模型列表里组内电脑照常单独显示、没有供应商组的标注 |
+| 手机与远程控制 | 旧手机、旧控制端不认识组摘要,模型列表照常逐台列出。被控电脑是旧版本时问不到「这个任务归哪个组」(`CHANNEL_NOT_ALLOWED` 或不认识的动作),按没归组处理:组照样收起,在组那一项里选模型照旧先确认换电脑,与之前相同 |
| 分享的人 | 照常使用,中转对它透明(协议不变)。打开任务阶段的换电脑由组所在电脑完成,旧版本同样享受;运行中失败时它没有声明支持「需要换一台」,组所在电脑照旧返回原来的错误(如用量上限),用户像现在一样换模型或稍后重试。新版本声明支持,运行中失败时自动换一台(§6.1)。旧版本申请弹窗仍是「Agent 在 {分享者} 的电脑上运行」(§8 已知差异) |
| 受邀者申请 | 申请弹窗由受邀者自己的 Cindy 显示,旧版本仍是原来的说法(§8 已知差异) |