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): 伙伴设置离线或冲突时可放弃修改离开,安卓遵守宿主禁用

Claude7bdb420cd014
diff --git a/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx
new file mode 100644
index 0000000000..e52b643972
--- /dev/null
+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx
@@ -0,0 +1,97 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({
+ account: 1, sheet: {} as any, inputs: {} as Record<string, any>, buttons: {} as Record<string, any>, pressables: {} as Record<string, any>,
+ alert: vi.fn(), read: vi.fn(), openLink: vi.fn(), invoke: vi.fn(), close: vi.fn(),
+}));
+vi.mock('react-native', async () => {
+ const { createElement: el } = await import('react');
+ return {
+ Platform: { OS: 'android' }, StyleSheet: { create: (v: unknown) => v }, View: 'div', Alert: { alert: h.alert }, Image: 'img', ScrollView: 'div', Switch: () => null,
+ Pressable: (p: any) => { if (p.accessibilityLabel) h.pressables[p.accessibilityLabel] = p; return el('div', null, p.children); },
+ };
+});
+vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-id' }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
+vi.mock('lucide-react-native', () => Object.fromEntries(['Brain','Check','ChevronRight','Clock3','FileText','MessageCircle','Search','Settings2','Sparkles','UserRound'].map(key => [key, () => null])));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: h.account }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));
+vi.mock('@/device-link/remoteResources', () => ({ invokeRemoteResourceAction: (...args: unknown[]) => h.invoke(...args) }));
+vi.mock('@/components/AppText', () => ({ Text: 'span', TextInput: (p: any) => { h.inputs[p.accessibilityLabel] = p; return null; } }));
+vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: (p: any) => { h.buttons[p.action.label] = p.action; return null; } }));
+vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, usesNativePullDownMenu: () => false }));
+vi.mock('@/session/CompanionSettingsRow', () => ({ CompanionSettingsRow: () => null }));
+vi.mock('@/session/CompanionSheet', async () => {
+ const { createElement: el } = await import('react');
+ return { CompanionSheet: (p: any) => { h.sheet = p; return el('div', null, p.children); } };
+});
+vi.mock('@/session/CompanionProfileArtifacts', () => ({ CompanionProfileArtifacts: () => null }));
+vi.mock('@/theme', async () => ({ ...await import('@/theme/tokens'), useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
+vi.mock('@/session/companionProfileData', async original => ({ ...await original<object>(), loadCompanionProfile: (...args: unknown[]) => h.read(...args) }));
+vi.mock('@/session/CompanionModelChain', () => ({ readCompanionModelChain: () => [], CompanionModelChain: () => null, CompanionModelPicker: () => null }));
+import { CompanionProfileSheet } from '@/session/CompanionProfileSheet';
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+const resource = { ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, display: { title: 'Cindy' }, links: [], revision: 'v1' };
+const profilePanel = (disabled = false) => ({ id: 'profile', values: { name: 'Cindy' },
+ action: { id: 'grant', label: 'Save', disabled, fields: [{ id: 'name', label: 'Name', kind: 'text' }] } });
+let root: Root | undefined;
+async function render(online = true) {
+ root ??= createRoot(document.createElement('div'));
+ await act(async () => root!.render(createElement(CompanionProfileSheet, { visible: true, resource, collectionId: 'teammates', deviceId: 'host', deviceName: 'Mac', online, onClose: h.close, onOpenSearch() {}, onOpenAutomation() {} } as any)));
+}
+async function openProfile() {
+ await act(async () => h.pressables['devices.companionProfile.profile'].onPress());
+}
+function alertButton(label: string) {
+ const buttons = h.alert.mock.calls.at(-1)?.[2] as { text: string; onPress?: () => void }[];
+ return buttons.find(button => button.text === label)!;
+}
+beforeEach(() => {
+ vi.clearAllMocks(); h.inputs = {}; h.buttons = {}; h.pressables = {};
+ h.read.mockResolvedValue({ resource, panels: [profilePanel()] });
+ h.invoke.mockResolvedValue({ effects: [] });
+});
+afterEach(() => { act(() => root?.unmount()); root = undefined; });
+
+it('keeps a host-disabled action read-only like iOS', async () => {
+ h.read.mockResolvedValue({ resource, panels: [profilePanel(true)] });
+ await render(); await openProfile();
+ expect(h.inputs.Name.editable).toBe(false);
+ expect(h.buttons['devices.companionProfile.save'].disabled).toBe(true);
+});
+
+it('asks to discard an offline draft on back instead of trapping the page', async () => {
+ await render(); await openProfile();
+ await act(async () => h.inputs.Name.onChangeText('Unsaved'));
+ await render(false);
+ await act(async () => h.sheet.onBack());
+ expect(h.alert).toHaveBeenCalledOnce(); expect(h.invoke).not.toHaveBeenCalled();
+ // Keep editing: the draft and page stay.
+ alertButton('devices.common.cancel').onPress?.();
+ expect(h.inputs.Name.value).toBe('Unsaved'); expect(h.sheet.onBack).toBeDefined();
+ await act(async () => h.sheet.onBack());
+ await act(async () => alertButton('devices.companions.automation.discard').onPress!());
+ expect(h.sheet.onBack).toBeUndefined(); expect(h.close).not.toHaveBeenCalled();
+});
+
+it('closes after discarding an offline draft, and still saves an online draft first', async () => {
+ await render(); await openProfile();
+ await act(async () => h.inputs.Name.onChangeText('Unsaved'));
+ await render(false);
+ await act(async () => h.sheet.onClose());
+ await act(async () => alertButton('devices.companions.automation.discard').onPress!());
+ expect(h.close).toHaveBeenCalledOnce(); expect(h.invoke).not.toHaveBeenCalled();
+
+ h.close.mockClear(); h.alert.mockClear();
+ await render(true); await openProfile();
+ await act(async () => h.inputs.Name.onChangeText('Saved on close'));
+ await act(async () => h.sheet.onClose());
+ expect(h.alert).not.toHaveBeenCalled();
+ expect(h.invoke.mock.calls[0][2].input).toEqual({ name: 'Saved on close' });
+ expect(h.close).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
index b5fc478895..f0a75640b9 100644
--- a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx
@@ -47,6 +47,18 @@ it('does not renew a dirty draft against a newer remote revision', async () => {
expect(h.view.conflict).toBe(true); expect(h.view.values.name).toBe('Local edit');
await act(async () => h.view.onSubmit(h.view.panel)); expect(h.invoke).not.toHaveBeenCalled();
});
+it('asks to discard a conflicted draft on back instead of ignoring the gesture', async () => {
+ await render(); await act(async () => h.view.onOpen('profile'));
+ await act(async () => h.view.onChange({ name: 'Local edit' }));
+ h.read.mockResolvedValue({ resource: { ...resource, revision: 'v2' }, panels: [{ ...panel, values: { name: 'Desktop edit' } }] });
+ await act(async () => h.view.onRetry());
+ const { Alert } = await import('react-native');
+ await act(async () => h.view.onBack());
+ expect(Alert.alert).toHaveBeenCalledOnce(); expect(h.invoke).not.toHaveBeenCalled();
+ const discard = vi.mocked(Alert.alert).mock.calls[0][2]!.find(button => button.style === 'destructive')!;
+ await act(async () => discard.onPress!());
+ expect(h.view.page).toBe('home'); expect(h.close).not.toHaveBeenCalled();
+});
it('waits for native dismissal before presenting the model picker and preserves the draft on return', async () => {
await render(); await act(async () => h.view.onOpen('models'));
await act(async () => h.model.onPick(0));
diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsx
index 926ab93215..0232efa300 100644
--- a/apps/mobile/src/session/CompanionProfileSheet.tsx
+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx
@@ -142,16 +142,13 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
const open = (next: string) => {
if (inFlight.current) return;
if (next === 'memoryEntries') {
- void (async () => {
- if (dirty && panel && !(await submit(panel))) return;
+ void settleDraft(() => {
setReceipt(null); setError(false); setDeleteFailure(false); setNameTakenOnSave(false); setConfirmation(null); setEditing(false); setPage(next);
- })(); return;
+ }); return;
}
if (next === 'avatar' || next === 'connections' || next === 'personalSkills') {
- void (async () => {
- if (dirty && panel && !(await submit(panel))) return;
- await openEditor(`settings:${resource?.ref.id}/${next === 'personalSkills' ? 'skills' : next}`);
- })(); return;
+ void settleDraft(() => openEditor(`settings:${resource?.ref.id}/${next === 'personalSkills' ? 'skills' : next}`));
+ return;
}
setConflict(null); setEditor(null); setEditorPanel(null); setPage(next); setReceipt(null); setError(false); setDeleteFailure(false); setNameTakenOnSave(false); setConfirmation(null); setEditing(false);
setValues(data?.panels.find(item => item.id === next)?.values ?? {});
@@ -222,7 +219,9 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
else if (!(await memory.back())) open('memory');
return;
}
- if (dirty && panel && !(await submit(panel))) return;
+ await settleDraft(() => leavePage(close));
+ };
+ const leavePage = async (close: boolean) => {
if (close) { onClose(); return; }
if (page === 'editor' && editor) {
if (editorPanel && editor.panels.filter(item => item.action && item.id !== 'remove').length > 1) { setEditorPanel(null); setEditing(false); return; }
@@ -246,6 +245,24 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
} else { setEditor(next); setError(false); }
} catch { if (current.current === started && generation.current === sequence) setError(true); }
};
+ // Leaving a page saves its dirty draft first. When the draft cannot be saved right now
+ // (offline, a host-disabled action or an unresolved version conflict), ask whether to
+ // discard it instead of silently keeping the user on a page they cannot leave.
+ const settleDraft = async (proceed: () => void | Promise<void>) => {
+ if (!dirty || !panel) { await proceed(); return; }
+ if (online && resource && panel.action && !panel.action.disabled && conflict?.page !== page) {
+ if (await submit(panel)) await proceed();
+ return;
+ }
+ const started = binding;
+ Alert.alert(t('devices.companions.automation.unsavedTitle'), t('devices.companions.automation.unsavedBody'), [
+ { text: t('devices.common.cancel'), style: 'cancel' },
+ { text: t('devices.companions.automation.discard'), style: 'destructive', onPress: () => {
+ if (current.current !== started || inFlight.current) return;
+ setEditing(false); setConflict(null); void proceed();
+ } },
+ ]);
+ };
const discardDraft = (reload: boolean) => {
Alert.alert(t('devices.companions.automation.unsavedTitle'), t('devices.companions.automation.unsavedBody'), [
{ text: t('devices.common.cancel'), style: 'cancel' },
@@ -267,8 +284,10 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
const titleKey = page === 'home' ? 'settingsTitle' : page === 'editor' ? editorTitles[editorResourceId.split('/')[1]] ?? 'title' : page;
const note = (key: string) => <Text selectable style={styles.note}>{t(`devices.companionProfile.${key}`, { deviceName })}</Text>;
const row = (id: string, Icon: typeof Brain) => <ContextSheetRow key={id} trailing="chevron" label={t(`devices.companionProfile.${id}`)} icon={<Icon size={iconSize.lg} color={colors.textSecondary} />} onPress={() => open(id)} />;
+ // Same as iOS: a host-disabled action (an unavailable connection, a paused teammate's skill) is read-only.
const renderPanel = (target: ProfilePanel | undefined) => target?.action
- ? <CompanionProfileForm panel={target} values={editing ? values : target.values} onChange={next => { if (!editing) draftBase.current = target.values; setValues(next); setEditing(true); }} disabled={busy || !online} />
+ ? <>{target.id === 'capability' && target.text ? <Text selectable style={styles.note}>{target.text}</Text> : null}
+ <CompanionProfileForm panel={target} values={editing ? values : target.values} onChange={next => { if (!editing) draftBase.current = target.values; setValues(next); setEditing(true); }} disabled={busy || !online || !!target.action.disabled} /></>
: target?.text ? <Text selectable style={styles.body}>{target.text}</Text> : !data && online ? <Text style={styles.note}>{t('devices.resources.loading')}</Text> : note('hostUpgrade');
const memoryPage = <CompanionMemoryPage memory={memory} online={online} botName={name} memoryEnabled={actionPanel('memory')?.values.memory !== false} />;
@@ -327,7 +346,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
{editorLoading ? <Text style={styles.note}>{t('devices.resources.loading')}</Text> : null}
{panel ? <>
{renderPanel(panel)}
- <MainWindowActionButton action={{ label: t('devices.companionProfile.save'), busy, disabled: !online || !dirty || conflict?.page === page, onPress: () => void submit(panel) }} />
+ <MainWindowActionButton action={{ label: t('devices.companionProfile.save'), busy, disabled: !online || !dirty || conflict?.page === page || !!panel.action?.disabled, onPress: () => void submit(panel) }} />
{editor?.panels.filter(item => item.id === 'remove' && item.action).map(item => <MainWindowActionButton key={item.id} action={{ label: label(item.action!.label), tone: 'danger', disabled: busy || !online, onPress: () => setConfirmation(item) }} />)}
</> : editor?.panels.map(item => item.entries ? item.entries.map(entry => <ContextSheetRow key={entry.id} icon={null} trailing="chevron" label={label(entry.title)} onPress={() => void openEditor(entry.resourceId)} />)
: item.action ? item.id === 'remove' ? <MainWindowActionButton key={item.id} action={{ label: label(item.action.label), tone: 'danger', disabled: busy || !online, onPress: () => setConfirmation(item) }} /> : <ContextSheetRow key={item.id} icon={null} trailing="chevron" label={label(item.title ?? item.action.label)} onPress={() => { setEditorPanel(item.id); setValues(item.values); setEditing(false); }} />
@@ -358,7 +377,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
{page === 'profile' && actionPanel('avatar')?.entries?.length ? row('avatar', UserRound) : null}
{page === 'models' && panel?.action ? models : renderPanel(panel)}
{(page === 'profile' || page === 'memory') && panel && !panel.action ? note('largeProfileRecovery') : null}
- {panel?.action ? <MainWindowActionButton action={{ label: t('devices.companionProfile.save'), busy, disabled: !online || !dirty || conflict?.page === page, onPress: () => void submit(panel) }} /> : null}
+ {panel?.action ? <MainWindowActionButton action={{ label: t('devices.companionProfile.save'), busy, disabled: !online || !dirty || conflict?.page === page || !!panel.action?.disabled, onPress: () => void submit(panel) }} /> : null}
{page === 'memory' && data ? memoryList ? row('memoryEntries', Brain) : panel?.action ? note('hostUpgrade') : null : null}
</>}
</View>