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): show host upgrade hint for rejected settings capability

Chriscb0fd2b96834
diff --git a/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx b/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx
index bccfea08e0..5a15b89ba3 100644
--- a/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx
@@ -1,21 +1,28 @@
// @vitest-environment jsdom
// Regression: IM records were inaccessible on both mobile presentations. Exercise the
// shared record picker with the real request envelope; opening must not reset a lane. Unit tier.
-import { act, createElement } from 'react';
+import { act, createElement, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
import { CompanionChannelTasks } from '@/session/CompanionChannelTasks';
-const h = vi.hoisted(() => ({ requests: [] as any[], supported: true, fail: false, refresh: vi.fn() }));
-vi.mock('@/session/useRemoteCompanionQuery', () => ({ useRemoteCompanionQuery: (device: string, channel: string, args: any[], options: any) => {
+const h = vi.hoisted(() => ({ requests: [] as any[], supported: true, fail: false, rejectCaps: null as unknown }));
+const invoke = vi.fn(async (device: string, channel: string, args: any[]) => {
const request = args[0];
- if (options.enabled) h.requests.push({ device, channel, request });
+ h.requests.push({ device, channel, request });
const op = request.input.op;
+ if (op === 'caps' && h.rejectCaps) throw h.rejectCaps;
const value = op === 'caps' ? { ops: h.supported ? ['channels.im.list', 'channels.im.listLanes'] : [] }
: op === 'channels.im.list' ? { connections: [{ id: 'connection', botId: 'bot', channel: 'telegram' }, { id: 'other', botId: 'other-bot', channel: 'discord' }] }
: { lanes: [{ sessionId: 'original-lane', name: 'Release group', chatId: 'group', kind: 'group' }] };
- return { value: options.enabled ? { result: { ok: !h.fail, value } } : null, error: false, refresh: h.refresh };
-} }));
-vi.mock('react-native', () => ({ View: ({ children }: any) => createElement('div', {}, children), StyleSheet: { create: (s: unknown) => s } }));
+ return { result: { ok: !h.fail, value } };
+});
+const link = { invoke, status: 'online', connectionEpoch: 1, getPresenceAvailability: () => true };
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => link, subscribeRemoteBotChanges: () => () => {} }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+vi.mock('expo-router', () => ({ useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]) }));
+vi.mock('react-native', () => ({ View: ({ children }: any) => createElement('div', {}, children), StyleSheet: { create: (s: unknown) => s },
+ AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) },
+}));
vi.mock('@/components/AppText', () => ({ Text: 'span' }));
vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: ({ action }: any) => createElement('button', { disabled: action.disabled, onClick: action.onPress }, action.label) }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
@@ -25,7 +32,7 @@ const host = document.createElement('div');
let root = createRoot(host);
const open = vi.fn();
const render = (online = true) => act(async () => root.render(<CompanionChannelTasks deviceId="studio" botId="bot" online={online} onOpenTask={open} />));
-afterEach(() => { act(() => root.unmount()); root = createRoot(host); h.requests = []; h.supported = true; h.fail = false; vi.clearAllMocks(); });
+afterEach(() => { act(() => root.unmount()); root = createRoot(host); h.requests = []; h.supported = true; h.fail = false; h.rejectCaps = null; vi.clearAllMocks(); });
it('opens the exact channel task and only reads the selected connection on its computer', async () => {
await render();
expect(host.querySelectorAll('button')).toHaveLength(1);
@@ -42,6 +49,32 @@ it('explains offline, unsupported hosts and logical failures instead of an empty
await render(false); expect(host.textContent).toContain('devices.resources.hostOffline');
expect(h.requests).toHaveLength(0);
h.supported = false; await render(); expect(host.textContent).toContain('devices.companionProfile.hostUpgrade');
- h.fail = true; await render(); expect(host.textContent).toContain('devices.companionProfile.readFailed');
- await act(async () => host.querySelector('button')!.click()); expect(h.refresh).toHaveBeenCalled();
+ h.fail = true; await act(async () => root.unmount()); root = createRoot(host); await render(); expect(host.textContent).toContain('devices.companionProfile.readFailed');
+ const attempts = h.requests.length;
+ await act(async () => host.querySelector('button')!.click()); expect(h.requests.length).toBeGreaterThan(attempts);
+});
+
+// Review #7105: the real query catch previously erased UNSUPPORTED_CAPABILITY.
+// Empty ops did not exercise rejected transport promises. One rejected caps read is the failure input; unit tier.
+it.each([
+ Object.assign(new Error('Unknown teammate action'), { code: 'UNSUPPORTED_CAPABILITY' }),
+ new Error('[UNSUPPORTED_CAPABILITY] Unknown teammate action'),
+ Object.assign(new Error('Channel unavailable'), { code: 'CHANNEL_NOT_ALLOWED' }),
+])('shows the upgrade hint when the host rejects the settings capability (%s)', async error => {
+ h.rejectCaps = error;
+ await render();
+ expect(host.textContent).toContain('devices.companionProfile.hostUpgrade');
+ expect(host.textContent).not.toContain('devices.companionProfile.readFailed');
+ expect(host.querySelector('button')).toBeNull();
+ expect(h.requests.map(row => row.request.input.op)).toEqual(['caps']);
+});
+it('keeps a transient rejected read retryable and recovers after retry', async () => {
+ h.rejectCaps = Object.assign(new Error('Host timeout'), { code: 'INVOKE_TIMEOUT' });
+ await render();
+ expect(host.textContent).toContain('devices.companionProfile.readFailed');
+ expect(host.textContent).not.toContain('devices.companionProfile.hostUpgrade');
+ h.rejectCaps = null;
+ await act(async () => host.querySelector('button')!.click());
+ expect(host.textContent).not.toContain('devices.companionProfile.readFailed');
+ expect(host.querySelectorAll('button')).toHaveLength(1);
});
diff --git a/apps/mobile/src/session/CompanionChannelTasks.tsx b/apps/mobile/src/session/CompanionChannelTasks.tsx
index d4fe2deee2..f8bf806143 100644
--- a/apps/mobile/src/session/CompanionChannelTasks.tsx
+++ b/apps/mobile/src/session/CompanionChannelTasks.tsx
@@ -17,6 +17,14 @@ function request(op: string, botId?: string, args?: Record<string, unknown>) {
input: { v: 1, op, ...(args ? { args } : {}) } }];
}
+function requiresHostUpgrade(error: unknown): boolean {
+ const transportCode = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
+ const message = error instanceof Error ? error.message : '';
+ const code = typeof transportCode === 'string' && transportCode !== 'IPC_ERROR' ? transportCode
+ : /^(?:Error invoking remote method '[^']+': Error: )?\[([A-Z0-9_]+)\]/.exec(message)?.[1];
+ return code === 'UNSUPPORTED_CAPABILITY' || code === 'CHANNEL_NOT_ALLOWED' || code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+}
+
/** Read existing channel tasks; opening one never resets its context or starts a turn. */
export function CompanionChannelTasks({ deviceId, botId, online, onOpenTask }: {
deviceId: string; botId: string; online: boolean; onOpenTask(id: string): void;
@@ -29,14 +37,15 @@ export function CompanionChannelTasks({ deviceId, botId, online, onOpenTask }: {
const connections = useRemoteCompanionQuery<Result<{ connections: Connection[] }>>(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, request('channels.im.list', botId), { enabled: online && !!supported });
const lanes = useRemoteCompanionQuery<Result<{ lanes: Lane[] }>>(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, request('channels.im.listLanes', botId, { id: expanded }), { enabled: online && !!supported && !!expanded });
const rows = connections.value?.result?.value?.connections?.filter(row => row.botId === botId) ?? [];
+ const unsupported = caps.error && requiresHostUpgrade(caps.cause) || caps.value?.result?.ok === true && !supported;
const failed = caps.error || caps.value?.result?.ok === false || connections.error || connections.value?.result?.ok === false;
const retry = () => { caps.refresh(); connections.refresh(); lanes.refresh(); };
return <View style={styles.content}>
- {!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text> : failed ? <>
+ {!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text>
+ : unsupported ? <Text style={styles.note}>{t('devices.companionProfile.hostUpgrade')}</Text> : failed ? <>
<Text style={styles.note}>{t('devices.companionProfile.readFailed')}</Text>
<MainWindowActionButton action={{ label: t('devices.resources.retry'), onPress: retry }} />
- </> : caps.value && !supported ? <Text style={styles.note}>{t('devices.companionProfile.hostUpgrade')}</Text>
- : !connections.value ? <Text style={styles.note}>{t('devices.resources.loading')}</Text>
+ </> : !connections.value ? <Text style={styles.note}>{t('devices.resources.loading')}</Text>
: rows.length === 0 ? <Text style={styles.note}>{t('devices.companionProfile.channelsEmpty')}</Text> : null}
{rows.map(row => <View key={row.id} style={styles.content}>
<MainWindowActionButton action={{ label: `${t(`devices.companionProfile.channelPlatforms.${row.service === 'lark' ? 'lark' : row.channel}`, { defaultValue: row.channel })}${row.identity?.username ? ` · ${row.identity.username}` : ''}`, onPress: () => setExpanded(expanded === row.id ? null : row.id) }} />
diff --git a/apps/mobile/src/session/useRemoteCompanionQuery.ts b/apps/mobile/src/session/useRemoteCompanionQuery.ts
index 4387e4b0a0..dc3c593831 100644
--- a/apps/mobile/src/session/useRemoteCompanionQuery.ts
+++ b/apps/mobile/src/session/useRemoteCompanionQuery.ts
@@ -37,6 +37,7 @@ export function useRemoteCompanionQuery<T>(
binding: string;
value: T | null;
error: boolean;
+ cause?: unknown;
}>({ identity, binding, value: null, error: false });
const [revision, setRevision] = useState(0);
const refresh = useCallback(() => setRevision((n) => n + 1), []);
@@ -122,13 +123,14 @@ export function useRemoteCompanionQuery<T>(
});
}
})
- .catch(() => {
+ .catch((cause: unknown) => {
if (!disposed && generation === expected && currentBinding.current === binding)
setState((previous) => ({
identity,
binding,
value: previous.identity === identity ? previous.value : null,
error: true,
+ cause,
}));
});
};
@@ -191,6 +193,7 @@ export function useRemoteCompanionQuery<T>(
return {
value: options.enabled !== false && state.identity === identity ? state.value : null,
error: state.identity === identity && (state.error || state.binding !== binding),
+ cause: state.identity === identity && state.binding === binding ? state.cause : undefined,
online,
refresh,
};