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。

fix(mobile): send only enabled models and remove catalog paging

Chrisfc97eaa3eab0
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index b9d2798773..3b844c69d9 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -36,7 +36,6 @@ vi.mock('../../logger', () => ({
}));
import { __testing } from '../dispatch';
-import { readProviderCatalog } from '@cindy/device-link';
const project = (result: unknown) =>
__testing.projectInvokeResultForTunnel('maker:provider:list', result) as {
@@ -100,15 +99,49 @@ function xdProviderWithFullRouting() {
}
describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
- it('pages only the credential-free projection and preserves all model options', async () => {
- const value = { providers: [xdProviderWithFullRouting()], modelVisibilityOverrides: { hidden: false } };
- const result = await readProviderCatalog({ channel: 'maker:provider:list', args: [] }, async payload => ({
- ok: true, result: __testing.projectInvokeResultForTunnel(payload.channel, value, true, payload.args),
+ it('applies owner visibility per provider and runtime before transport, preserving enabled model options', () => {
+ const models = [
+ { id: 'default-on', defaultEnabled: true, supportsFastMode: true },
+ { id: 'manual-on', defaultEnabled: false, efforts: ['low', 'high'], contextWindow: 272000 },
+ { id: 'manual-off', defaultEnabled: true },
+ { id: 'default-off', defaultEnabled: false },
+ { id: 'legacy-default' },
+ ];
+ const providers = ['a', 'b'].map(id => ({ id, agents: ['codex', 'pi'],
+ models: { codex: models, pi: models }, imageModels: models, videoModels: models,
+ audioModels: models, embeddingModels: models }));
+ const input = { providers, providerOrder: ['b', 'a'], modelVisibilityOverrides: {
+ 'codex:a:manual-on': true, 'codex:a:manual-off': false,
+ } };
+ const output = project(input);
+ const a = output.providers[0];
+ const expected = [models[0], models[1], models[4]];
+ expect(a.models).toEqual({ codex: expected, pi: [models[0], models[2], models[4]] });
+ expect(output.providers[1].models).toEqual({ codex: [models[0], models[2], models[4]], pi: [models[0], models[2], models[4]] });
+ for (const field of ['imageModels', 'videoModels', 'audioModels', 'embeddingModels']) expect(a[field]).toEqual(expected);
+ expect(output.providerOrder).toEqual(['b', 'a']);
+ expect(output.modelVisibilityOverrides).toEqual(input.modelVisibilityOverrides);
+ expect(input.providers[0].models.codex).toHaveLength(5);
+ expect(project({ ...input, modelVisibilityOverrides: { 'codex:a:manual-on': false } }).providers[0].models)
+ .toEqual({ codex: [models[0], models[2], models[4]], pi: [models[0], models[2], models[4]] });
+ });
+
+ it('fits a catalog dominated by hidden models into the unchanged legacy response without truncating enabled rows', () => {
+ const enabled = Array.from({ length: 150 }, (_, i) => ({
+ id: `enabled-${i}`, defaultEnabled: true, efforts: ['medium', 'high'], supportsFastMode: true,
}));
- expect(result).toEqual({ ok: true, result: projectForCurrentController(value) });
- expect(JSON.stringify(result)).not.toContain('leak-me');
- expect(JSON.stringify(result)).not.toContain(XD_GATEWAY_BASE_URL);
+ const hidden = Array.from({ length: 900 }, (_, i) => ({
+ id: `hidden-${i}`, defaultEnabled: false, description: 'metadata '.repeat(600),
+ }));
+ const input = { providers: [{ id: 'large', models: { codex: [...enabled, ...hidden] } }] };
+ expect(Buffer.byteLength(JSON.stringify(input))).toBeGreaterThan(4 * 1024 * 1024);
+ const output = project(input); // No capability negotiation, same path as an old phone.
+ expect(output.providers[0].models).toEqual({ codex: enabled });
+ expect(Buffer.byteLength(JSON.stringify(output))).toBeLessThan(64 * 1024);
+ expect(output).not.toHaveProperty('format');
+ expect(output).not.toHaveProperty('data');
});
+
it('keeps the remote native Codex preference after stripping OAuth execution details', () => {
const model = {
id: 'gpt-6-astra', name: 'GPT-6 Astra', contextWindow: 400000,
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
index bd2cc025b4..f25118613a 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
@@ -11,17 +11,6 @@ function capture(): SharedTaskPeerCapture {
}
afterEach(() => { setSharedTaskQueueReader(null); setSharedTaskInteractionReader(null); });
describe('sharedTask dispatch scope', () => {
- it('authorizes each provider page as a history read and rejects malformed cursors', () => {
- const options = { capabilities: ['provider-catalog-pages-v1'], catalogPage: { offset: 262144, revision: 'a'.repeat(64) } };
- const request = { channel: 'maker:provider:list', args: [options] };
- expect(() => assertSharedTaskInvoke(capture(), request)).not.toThrow();
- expect(() => assertSharedTaskInvoke({ ...capture(), authorize: () => false }, request)).toThrow('PERMISSION_DENIED');
- for (const invalid of [
- { ...options, catalogPage: { offset: -1, revision: 'a'.repeat(64) } },
- { ...options, capabilities: [] },
- { ...options, path: '/private' },
- ]) expect(() => assertSharedTaskInvoke(capture(), { ...request, args: [invalid] })).toThrow('PERMISSION_DENIED');
- });
it('reads subagent context only through the shared parent task', () => {
for (const channel of ['local-db:subagent-runs:list', 'local-db:subagent-runs:detail', 'local-db:subagent-runs:transcript']) {
const request = { sessionId: 'task', provider: 'pi', runIdOrAlias: 'child' };
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 7b361073f6..0832038d3e 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -1,4 +1,3 @@
-import { createHash } from 'node:crypto';
import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';
import type { TaskTagRequest } from '@cindy/maker-shared';
import {
@@ -6,7 +5,6 @@ import {
TASK_MIGRATION_CHANNEL,
encodeSessionTagCatalog,
decodeSessionTagCatalog,
- encodeProviderCatalogPage,
} from '@cindy/device-link';
import { requestFilePeer, stopFilePeers } from './filePeer';
import { requestTaskMigration } from '../task-migration/service';
@@ -85,6 +83,7 @@ import {
type ProviderLogoKind,
type ProviderLogoRouting,
} from '@cindy/model-providers/branding';
+import { isModelVisible } from '@cindy/model-providers/sections';
import { app } from 'electron';
import { remoteDesktop, requestRemoteDesktop } from '../remote-desktop';
import { remoteCredentialHost } from '../remote-desktop/credentialHost';
@@ -518,21 +517,38 @@ function projectRoutingForDisplay(
* availability marker so both current and independently-updated legacy Mobile clients keep the
* published provider model shape.
*/
-function projectModelsForController(models: unknown): unknown {
+function projectModelsForController(
+ models: unknown,
+ providerId: string,
+ visibility: Record<string, boolean>,
+): unknown {
if (!models || typeof models !== 'object' || Array.isArray(models)) return models;
return Object.fromEntries(
- Object.entries(models as Record<string, unknown>).map(([agent, value]) => {
- if (!Array.isArray(value)) return [agent, value];
- const projected = value.flatMap((model) => {
- if (!model || typeof model !== 'object' || Array.isArray(model)) return [model];
- const { availability, ...legacyModel } = model as Record<string, unknown>;
- return availability === 'requires_payment' ? [] : [legacyModel];
- });
- return [agent, projected];
- }),
+ Object.entries(models as Record<string, unknown>).map(([agent, value]) => [
+ agent, projectVisibleModelList(value, providerId, agent, visibility),
+ ]),
);
}
+/** Apply the same owner preferences as the picker before paying the transport cost. */
+function projectVisibleModelList(
+ value: unknown,
+ providerId: string,
+ agent: string,
+ visibility: Record<string, boolean>,
+): unknown {
+ if (!Array.isArray(value)) return value;
+ return value.flatMap((model) => {
+ if (!model || typeof model !== 'object' || Array.isArray(model)) return [model];
+ const { availability, ...legacyModel } = model as Record<string, unknown>;
+ const visible = isModelVisible(
+ visibility[`${agent}:${providerId}:${legacyModel.id}`],
+ typeof legacyModel.defaultEnabled === 'boolean' ? legacyModel.defaultEnabled : undefined,
+ );
+ return availability === 'requires_payment' || !visible ? [] : [legacyModel];
+ });
+}
+
/**
* 隧道返回投影:`maker:provider:list` 只回「显示用」字段——先从 provider id / upstream
* 解析非敏感 `logoKind`,再剥掉每个 provider 的 `routing` 执行字段(upstream /
@@ -607,6 +623,14 @@ function projectInvokeResultForTunnel(
if (channel !== 'maker:provider:list') return result;
const r = result as { providers?: unknown; modelVisibilityOverrides?: unknown; providerOrder?: unknown };
if (!Array.isArray(r.providers)) return result;
+ const modelVisibilityOverrides = r.modelVisibilityOverrides
+ && typeof r.modelVisibilityOverrides === 'object'
+ && !Array.isArray(r.modelVisibilityOverrides)
+ ? Object.fromEntries(
+ Object.entries(r.modelVisibilityOverrides)
+ .filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean'),
+ )
+ : undefined;
const providers = (r.providers as Record<string, unknown>[]).map((p) => {
const rest = { ...p };
const logoKind = typeof p.id === 'string'
@@ -620,23 +644,23 @@ function projectInvokeResultForTunnel(
) {
rest.logoKind = logoKind;
}
- rest.models = projectModelsForController(p.models);
+ const providerId = typeof p.id === 'string' ? p.id : '';
+ const visibility = modelVisibilityOverrides ?? {};
+ rest.models = projectModelsForController(p.models, providerId, visibility);
+ // Media uses the same preference key as the host visibility snapshot.
+ const mediaAgent = Array.isArray(p.agents) && typeof p.agents[0] === 'string'
+ ? p.agents[0] : 'claude-code';
+ for (const field of ['imageModels', 'videoModels', 'audioModels', 'embeddingModels'] as const) {
+ if (Array.isArray(p[field])) rest[field] = projectVisibleModelList(p[field], providerId, mediaAgent, visibility);
+ }
rest.routing = projectRoutingForDisplay(p.routing);
return rest;
});
- const modelVisibilityOverrides = r.modelVisibilityOverrides
- && typeof r.modelVisibilityOverrides === 'object'
- && !Array.isArray(r.modelVisibilityOverrides)
- ? Object.fromEntries(
- Object.entries(r.modelVisibilityOverrides)
- .filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean'),
- )
- : undefined;
- return encodeProviderCatalogPage(args, {
+ return {
providers,
...(modelVisibilityOverrides !== undefined ? { modelVisibilityOverrides } : {}),
...(Array.isArray(r.providerOrder) ? { providerOrder: normalizeProviderOrder(r.providerOrder) } : {}),
- }, json => createHash('sha256').update(json).digest('hex'));
+ };
}
/** 持有 client 的引用(转发 push 用);wireInboundDispatch 接入时设置。 */
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 235a101bdb..75ea66ea01 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -1,6 +1,5 @@
import { isSharedTaskPeer, parseSharedTaskPeer, isSharedTaskAttachment, type InvokePayload, type InvokeResultPayload, type SharedTaskQueueItem } from '@cindy/device-link';
import type { SharedTaskHost } from './sharedTaskHost.js';
-import { isProviderCatalogCursor, PROVIDER_CATALOG_PAGES_CAPABILITY } from '@cindy/device-link';
export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;
export interface SharedTaskInteractionCapture {
@@ -206,10 +205,8 @@ export function assertSharedTaskInvoke(
if (channel === 'maker:get-capabilities' && !['claude-code', 'codex', 'pi'].includes(String(args[0]))) deny();
if (channel === 'maker:provider:list' && args[0] !== undefined) {
const options = record(args[0]);
- if (!options || Object.keys(options).some((key) => key !== 'capabilities' && key !== 'catalogPage') ||
+ if (!options || Object.keys(options).some((key) => key !== 'capabilities') ||
!Array.isArray(options.capabilities) || options.capabilities.some((item) => typeof item !== 'string')) deny();
- if (options.catalogPage !== undefined && (!options.capabilities.includes(PROVIDER_CATALOG_PAGES_CAPABILITY)
- || !isProviderCatalogCursor(options.catalogPage))) deny();
}
return;
}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index c006e1d092..285b4ce859 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -6167,7 +6167,9 @@ export default function NewRemoteSessionScreen() {
) : null}
</View>
) : null}
- <View style={styles.composerToolbarWrap}>
+ <View style={[styles.composerToolbarWrap, composerCardActive && {
+ minHeight: COMPOSER_CARD_CHROME_HEIGHT + MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT,
+ }]}>
<MobileComposerInputRow
accessibilityLabel={t('session.new.firstMessagePlaceholder')}
bodyScrollGesture={composerResize.scrollGesture}
@@ -6754,7 +6756,13 @@ function NewComposerPaletteFrame({
const { t } = useTranslation();
const hasRows = Array.isArray(children) ? children.length > 0 : !!children;
return (
- <View style={styles.palettePanel} testID={testID}>
+ <ScrollView
+ style={styles.palettePanel}
+ contentContainerStyle={styles.paletteContent}
+ keyboardShouldPersistTaps="handled"
+ nestedScrollEnabled
+ testID={testID}
+ >
{loading ? (
<View style={styles.paletteStatusRow}>
<ActivityIndicator color={colors.textSecondary} />
@@ -6767,7 +6775,7 @@ function NewComposerPaletteFrame({
) : (
<Text style={styles.paletteStatusText}>{emptyText}</Text>
)}
- </View>
+ </ScrollView>
);
}
@@ -7287,8 +7295,11 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
borderColor: colors.border,
borderRadius: radius.container,
borderWidth: StyleSheet.hairlineWidth,
- gap: spacing.xs,
+ flexShrink: 1,
maxHeight: 220,
+ },
+ paletteContent: {
+ gap: spacing.xs,
padding: spacing.sm,
},
paletteRow: {
diff --git a/apps/mobile/docs/navigation-and-composer.md b/apps/mobile/docs/navigation-and-composer.md
index 2f77da6db1..2a7542a95b 100644
--- a/apps/mobile/docs/navigation-and-composer.md
+++ b/apps/mobile/docs/navigation-and-composer.md
@@ -14,6 +14,7 @@
拉开成完整卡片(原生),约 0.05s 后原生聚焦,键盘随后升起;输入框逐帧跟随键盘
(均在 `ComposerDockKeyboardFollow.tsx`:新建页 `DockKeyboardBottomSpacer`,已有任务 `DockKeyboardLift` / `DockKeyboardViewportSpacer`)。
- 新建页输入卡固定在页面滚动区之外;已有任务输入卡仅正文与附件可滚动,发送、语音与拖拽把手保留在滚动视口之外。长文本、附件及键盘改变可用高度时仍能直接发送,收起再展开不重挂编辑器。
+- 新建任务输入卡内的 `/` 命令和 `@` 资源候选面板使用可收缩的独立滚动视口;键盘弹出时保留输入与发送区域,候选项可在面板内滚动选择。
- 减弱动态效果:不播形变与拉开,直接到位。
- 伙伴对话:左上角为返回(回到伙伴列表);Duo 系统栏已有返回时保留侧栏按钮,不出现两个返回。
- 设置等整页滚动的二级页:顶栏透明、系统柔和边缘,内容滚到顶栏和底部指示条下面,无硬分界(设置、语音词典、账号注销、伙伴私聊、共享任务管理、资源列表);设备详情只去掉底部色带。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index d695def3f6..371d67dcb3 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -636,16 +636,13 @@ Mobile 原生 fingerprint 输入,服务端无需改动。
远程端继续使用已有 `settings:<botId>/skills` 资源,不扩 IPC allowlist。
SSH 继续沿用现有伙伴远端技能限制,不读取控制端本机资料;设备互联由执行宿主保存与复盘。
-## 模型目录分段读取
-
-`maker:provider:list` 通过请求的 `capabilities: ['provider-catalog-pages-v1']` 协商分段响应。
-主机先完成原有授权、路由凭证剥离和模型投影,再将完整 JSON 按至多 256 Ki 个 UTF-16
-码元分段;`provider-catalog-page-v1` 携带 `revision`(完整投影的 SHA-256)、`offset`、
-`total` 与 `data`。后续请求的可选 `catalogPage: { offset, revision }` 必须匹配当前目录,
-每次仍执行授权与投影,目录改变则明确失败,不拼接不同快照。控制端仅在完整重组后发布目录,
-限制重组至 64 Mi 个码元;单段即使全部需要 JSON 转义也低于既有 2 MiB 帧限制。
-
-共享 DeviceLinkClient 为手机和远程桌面统一协商与重组,保留模型、顺序、偏好和能力字段。
-旧主机忽略能力声明并返回原格式;旧控制端不声明能力,新主机也返回原格式。共享任务仍要求
-`history.read`,游标不增加权限。服务端、relay、传输帧限制和 Mobile 原生指纹均不改变;
-超大目录的完整修复需要执行主机及控制端均升级,单端回退保留原有大小限制。
+## 远程模型目录按显示设置过滤
+
+`maker:provider:list` 在执行主机完成既有授权和账号快照读取后,先按同一快照中的
+`modelVisibilityOverrides` 与模型 `defaultEnabled` 过滤,再通过原有响应格式传输。
+判定复用共享 `isModelVisible`:用户显式开关优先,否则跟随目录默认;不限制已开启模型的
+数量、不修改用户偏好。聊天模型按 agent/provider/model 区分,媒体模型沿用主机的显示设置键。
+未开启模型不再传给控制端;供应商结构、连接状态、顺序及开启模型的能力配置保留。
+
+这是执行主机的投影修复,旧 Mobile 和远控 Desktop 无需新增能力协商即可接收。
+不增加分页、客户端重组或重试,不提高传输大小上限;本机 Desktop 设置仍读取完整目录。
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index b01e8dd80c..1b73d4d26e 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -3,8 +3,6 @@
* 握手 / 请求配对 / 超时 / relay-error / 重连退避 / 心跳僵死 / token 缺失。
*/
import { describe, it, expect, vi } from 'vitest';
-import { createHash } from 'node:crypto';
-import { encodeProviderCatalogPage } from '../providerCatalogTransport.js';
import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../client.js';
import {
PROTOCOL_VERSION,
@@ -967,27 +965,6 @@ describe('DeviceLinkClient', () => {
await expect(p).resolves.toMatchObject({ ok: true, result: ['s1'] });
h.client.stop();
});
- it('assembles provider pages through invoke and checks ownership before each page', async () => {
- const h = makeHarness();
- h.client.start();
- await tick();
- h.current().ack();
- const preSend = vi.fn();
- const value = { providers: [{ id: 'custom', models: { pi: [{ id: 'model', description: 'x'.repeat(300000) }] } }] };
- const pending = h.client.invoke('dev-b', { channel: 'maker:provider:list', args: [] }, undefined, { preSend });
- for (let i = 0; i < 2; i++) {
- const sent = h.current().sent.filter(e => e.kind === 'invoke')[i];
- expect(sent).toBeDefined();
- const request = sent.payload as { args: unknown[] };
- h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', id: sent.id, src: 'dev-b',
- payload: { ok: true, result: encodeProviderCatalogPage(request.args, value,
- json => createHash('sha256').update(json).digest('hex')) } });
- await tick();
- }
- await expect(pending).resolves.toEqual({ ok: true, result: value });
- expect(preSend).toHaveBeenCalledTimes(2);
- h.client.stop();
- });
it("negotiates a tag catalog and returns the original session array to callers", async () => {
const h = makeHarness();
h.client.start();
diff --git a/packages/device-link/src/__tests__/providerCatalogTransport.test.ts b/packages/device-link/src/__tests__/providerCatalogTransport.test.ts
deleted file mode 100644
index 08285c78e3..0000000000
--- a/packages/device-link/src/__tests__/providerCatalogTransport.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { createHash } from 'node:crypto';
-import { describe, expect, it, vi } from 'vitest';
-import { encodeProviderCatalogPage, readProviderCatalog, PROVIDER_CATALOG_PAGES_CAPABILITY } from '../providerCatalogTransport.js';
-import { encodeReliableFrames } from '../transport.js';
-import type { InvokePayload, InvokeResultPayload } from '../protocol.js';
-
-const revisionOf = (json: string) => createHash('sha256').update(json).digest('hex');
-const payload: InvokePayload = { channel: 'maker:provider:list', args: [{ capabilities: ['provider-logo-kinds-v2'] }] };
-const catalog = (count = 1) => ({
- providers: [{ id: 'custom', connected: true, models: { pi: Array.from({ length: count }, (_, i) => ({
- id: `model-${i}`, name: `模型 🐈 ${i}`, description: '引用 "\\\n🐈'.repeat(80), efforts: ['low', 'high'],
- })) } }],
- providerOrder: ['custom'], modelVisibilityOverrides: { 'pi:custom:model-0': false },
-});
-
-describe('provider catalog pages', () => {
- it('round-trips every model/option in a >4MiB catalog through bounded reliable frames', async () => {
- const value = catalog(4000);
- expect(Buffer.byteLength(JSON.stringify(value))).toBeGreaterThan(4 * 1024 * 1024);
- const request = vi.fn(async (next: InvokePayload): Promise<InvokeResultPayload> => {
- const result = encodeProviderCatalogPage(next.args, value, revisionOf);
- const envelope = { v: 1 as const, kind: 'invoke-result' as const, src: 'host', dst: 'phone', id: 'read', payload: { ok: true as const, result } };
- expect(Buffer.byteLength(JSON.stringify(envelope))).toBeLessThan(2 * 1024 * 1024);
- expect(() => encodeReliableFrames(envelope, 'stream', 1)).not.toThrow();
- return envelope.payload;
- });
- expect(await readProviderCatalog(payload, request)).toEqual({ ok: true, result: value });
- expect(request.mock.calls.length).toBeGreaterThan(1);
- expect(payload.args).toEqual([{ capabilities: ['provider-logo-kinds-v2'] }]);
- });
-
- it('keeps old hosts, old controllers and unrelated invokes compatible', async () => {
- const value = catalog();
- expect(encodeProviderCatalogPage(payload.args, value, revisionOf)).toBe(value);
- const reply = { ok: true as const, result: value };
- const legacy = vi.fn(async () => reply);
- expect(await readProviderCatalog(payload, legacy)).toBe(reply);
- expect(legacy).toHaveBeenCalledTimes(1);
- const unrelated = { channel: 'maker:list-active', args: [] };
- await readProviderCatalog(unrelated, legacy);
- expect(legacy).toHaveBeenLastCalledWith(unrelated);
- });
-
- it('rejects changed snapshots, malformed cursors and out-of-order pages', async () => {
- const value = catalog(1000);
- const options = { capabilities: [PROVIDER_CATALOG_PAGES_CAPABILITY] };
- expect(() => encodeProviderCatalogPage([{ ...options, catalogPage: { offset: -1, revision: 'x' } }], value, revisionOf)).toThrow('Invalid provider catalog cursor');
- let calls = 0;
- await expect(readProviderCatalog(payload, async next => {
- calls++;
- return { ok: true, result: encodeProviderCatalogPage(next.args, calls > 1 ? catalog(999) : value, revisionOf) };
- })).rejects.toThrow('Provider catalog changed');
- await expect(readProviderCatalog(payload, async next => ({
- ok: true, result: { ...(encodeProviderCatalogPage(next.args, value, revisionOf) as object), offset: 1 },
- }))).rejects.toThrow('Inconsistent provider catalog page');
- });
-
- it('propagates a later authorization failure without exposing a partial catalog', async () => {
- let calls = 0;
- const denied = { ok: false as const, error: { code: 'ACCESS_REVOKED' as const, message: 'revoked' } };
- expect(await readProviderCatalog(payload, async next => ++calls > 1 ? denied : ({
- ok: true, result: encodeProviderCatalogPage(next.args, catalog(1000), revisionOf),
- }))).toBe(denied);
- expect(calls).toBe(2);
- });
-});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 3765c065b6..b998502bbe 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,6 +1,5 @@
import { isPeerResetRetryableReadChannel, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';
import { InvokeScheduler } from './invokeScheduler.js';
-import { readProviderCatalog } from './providerCatalogTransport.js';
import { encodeSharedTaskEnvelope, decodeSharedTaskEnvelope } from './sharedTaskEnvelope.js';
import { isSharedTaskPeer } from './sharedTaskPeer.js';
import { SHARED_TASK_RELAY_CAPABILITY } from '@cindy/device-link-protocol';
@@ -1348,15 +1347,6 @@ export class DeviceLinkClient {
payload: InvokePayload,
timeoutMs?: number,
options?: { preSend?: () => void },
- ): Promise<InvokeResultPayload> {
- return readProviderCatalog(payload, page => this.invokeOnce(dst, page, timeoutMs, options));
- }
-
- private async invokeOnce(
- dst: string,
- payload: InvokePayload,
- timeoutMs?: number,
- options?: { preSend?: () => void },
): Promise<InvokeResultPayload> {
if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
const send = () => {
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index a9556c448f..4c5fe55299 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -41,7 +41,6 @@ export * from "./sharedTaskInvitation.js";
export * from "./sharedTaskProbe.js";
export * from "./modelFavorites.js";
export * from "./sessionListTransport.js";
-export * from './providerCatalogTransport.js';
export * from "./clipboardSync.js";
export * from "./clipboardSyncFailure.js";
diff --git a/packages/device-link/src/providerCatalogTransport.ts b/packages/device-link/src/providerCatalogTransport.ts
deleted file mode 100644
index 98d2460961..0000000000
--- a/packages/device-link/src/providerCatalogTransport.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { DeviceLinkError, type InvokePayload, type InvokeResultPayload } from './protocol.js';
-
-export const PROVIDER_CATALOG_PAGES_CAPABILITY = 'provider-catalog-pages-v1';
-export const PROVIDER_CATALOG_PAGE_CHARS = 256 * 1024;
-const channel = 'maker:provider:list';
-const format = 'provider-catalog-page-v1';
-// Bound controller-side assembly independently of the per-message transport limit.
-const maxCatalogChars = 64 * 1024 * 1024;
-const record = (value: unknown): value is Record<string, unknown> =>
- !!value && typeof value === 'object' && !Array.isArray(value);
-
-export function isProviderCatalogCursor(value: unknown): value is { offset: number; revision: string } {
- return record(value) && Object.keys(value).every(key => key === 'offset' || key === 'revision')
- && Number.isSafeInteger(value.offset) && (value.offset as number) > 0
- && (value.offset as number) < maxCatalogChars
- && typeof value.revision === 'string' && /^[a-f0-9]{64}$/.test(value.revision);
-}
-
-/** Called only after the host's normal authorization and credential-free projection. */
-export function encodeProviderCatalogPage(
- args: readonly unknown[], value: unknown, revisionOf: (json: string) => string,
-): unknown {
- const options = args[0];
- if (!record(options) || !Array.isArray(options.capabilities)
- || !options.capabilities.includes(PROVIDER_CATALOG_PAGES_CAPABILITY)) return value;
- const json = JSON.stringify(value);
- if (json === undefined) return value;
- if (json.length > maxCatalogChars) throw new Error('[PRECONDITION_FAILED] Provider catalog exceeds assembly budget');
- const revision = revisionOf(json);
- const cursor = options.catalogPage;
- if (cursor !== undefined && !isProviderCatalogCursor(cursor)) {
- throw new Error('[INVALID_PARAMS] Invalid provider catalog cursor');
- }
- if (cursor && (cursor.revision !== revision || cursor.offset >= json.length)) {
- throw new Error('[PRECONDITION_FAILED] Provider catalog changed during read');
- }
- const offset = cursor?.offset ?? 0;
- // Even worst-case JSON escaping stays below the legacy 2MiB frame budget.
- return { format, revision, offset, total: json.length, data: json.slice(offset, offset + PROVIDER_CATALOG_PAGE_CHARS) };
-}
-
-/** Preserve the public invoke result, assembling the entire catalog before publishing it. */
-export async function readProviderCatalog(
- payload: InvokePayload,
- invoke: (payload: InvokePayload) => Promise<InvokeResultPayload>,
-): Promise<InvokeResultPayload> {
- if (payload.channel !== channel) return invoke(payload);
- const original = payload.args?.[0];
- if (original !== undefined && !record(original)) return invoke(payload);
- const options = {
- ...original,
- capabilities: [...new Set([
- ...(Array.isArray(original?.capabilities) ? original.capabilities : []),
- PROVIDER_CATALOG_PAGES_CAPABILITY,
- ])],
- };
- let response = await invoke({ ...payload, args: [options, ...(payload.args?.slice(1) ?? [])] });
- // Old hosts ignore the capability and return the original complete catalog.
- if (!response.ok || !record(response.result) || response.result.format !== format) return response;
- const revision = response.result.revision;
- const total = response.result.total;
- if (typeof revision !== 'string' || !/^[a-f0-9]{64}$/.test(revision)
- || !Number.isSafeInteger(total) || (total as number) <= 0 || (total as number) > maxCatalogChars) {
- throw new DeviceLinkError('BAD_REQUEST', 'Invalid provider catalog page');
- }
- const parts: string[] = [];
- let offset = 0;
- while (response.ok) {
- const page = response.result;
- if (!record(page) || page.format !== format || page.revision !== revision || page.total !== total
- || page.offset !== offset || typeof page.data !== 'string' || !page.data.length
- || page.data.length !== Math.min(PROVIDER_CATALOG_PAGE_CHARS, (total as number) - offset)) {
- throw new DeviceLinkError('BAD_REQUEST', 'Inconsistent provider catalog page');
- }
- parts.push(page.data);
- offset += page.data.length;
- if (offset === total) return { ...response, result: JSON.parse(parts.join('')) };
- response = await invoke({ ...payload, args: [{ ...options, catalogPage: { offset, revision } }, ...(payload.args?.slice(1) ?? [])] });
- }
- return response;
-}