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): reconcile automation retry state and errors

david5b87870d3090
diff --git a/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx b/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx
index f29429d387..9b1460ead0 100644
--- a/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx
@@ -9,6 +9,7 @@ const h = vi.hoisted(() => ({
read: vi.fn(), invoke: vi.fn(), openLink: vi.fn(), subscribe: vi.fn(), unsubscribe: vi.fn(), changed: vi.fn(), close: vi.fn(),
alert: vi.fn(), account: 1, foreground: null as null | ((state: string) => void), nativeWrites: vi.fn(),
definition: null as any, revision: 0, existing: false, now: 0, uuid: 0, perform: vi.fn(), sheet: null as any, platform: 'ios',
+ history: [] as { id: string; status: string; createdAt: number }[],
}));
vi.mock('react-i18next', () => { const t = (key: string) => key.split('.').at(-1)!; return { useTranslation: () => ({ t, i18n: { language: 'en' } }) }; });
vi.mock('react-native', () => ({
@@ -83,10 +84,10 @@ function resource(id: string) {
}));
return { ref: { collectionId: 'routines', kind: 'routine', id }, display: { title: 'Automations' }, links: [], revision: String(revision),
actions: Object.values(operationActions).map(id => ({ id, label: 'Action' })), blocks: [{ primitive: selected ? 'routine-detail' : 'routine-list', data: selected
- ? { id: existing ? 'rule' : null, revision, editable: true, input: h.definition, sources: [{ id: 'mail', name: 'Mail', status: 'ready', events: [{ type: 'received', name: 'Received', fields: ['sender', 'subject'] }] }], history: [], operationActions }
+ ? { id: existing ? 'rule' : null, revision, editable: true, input: h.definition, sources: [{ id: 'mail', name: 'Mail', status: 'ready', events: [{ type: 'received', name: 'Received', fields: ['sender', 'subject'] }] }], history: h.history, operationActions }
: { items: h.existing ? [{ id: 'rule', name: 'Existing', enabled: true, revision: h.revision, triggers: [] }] : [], operationActions } }] };
}
-async function render() { await act(async () => root.render(<CompanionAutomationSheet visible online onClose={h.close} botId="bot" collectionId="routines" deviceId="host" deviceName="Mac" />)); }
+async function render(online = true) { await act(async () => root.render(<CompanionAutomationSheet visible online={online} onClose={h.close} botId="bot" collectionId="routines" deviceId="host" deviceName="Mac" />)); }
function input(label: string) { const node = container.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`); if (!node) throw new Error(`Missing ${label}`); return node; }
async function type(label: string, value: string) { await act(async () => { const field = input(label); field.focus(); field.value = value; field.dispatchEvent(new Event('input', { bubbles: true })); }); }
async function click(label: string) { await act(async () => { const button = [...container.querySelectorAll('button')].find(node => node.textContent === label); if (!button) throw new Error(`Missing ${label}`); button.click(); }); }
@@ -94,6 +95,7 @@ async function select(label: string, value: string) { await act(async () => { co
async function open() { await render(); await click('new'); }
beforeEach(() => {
vi.resetAllMocks(); h.account = 1; h.revision = 0; h.existing = false; h.now = 0; h.uuid = 0; h.platform = 'ios'; h.definition = emptyRoutineDefinition();
+ h.history = [];
grants.clear(); grantId = 0;
h.changed.mockReturnValue(() => {}); h.openLink.mockResolvedValue(undefined);
h.read.mockImplementation((_invoke, _target, ref) => Promise.resolve(resource(ref.id)));
@@ -259,6 +261,7 @@ it('preserves a dirty draft and blocks stale saves when the host version changed
throw new Error('Response lost');
});
await click('save');
+ expect(container.textContent).toContain('Response lost');
expect(container.textContent).toContain('changed');
expect(input('name').value).toBe('Existing'); expect(input('hour').value).toBe('12');
expect(container.querySelector<HTMLButtonElement>('[data-testid="companion.automation.save"]')!.disabled).toBe(true);
@@ -266,6 +269,82 @@ it('preserves a dirty draft and blocks stale saves when the host version changed
expect(h.invoke).toHaveBeenCalledOnce();
});
+it.each(['ios', 'android'])('reconciles an acknowledged-by-read save without overwriting or locking the draft on %s', async platform => {
+ h.platform = platform;
+ await openExisting(); await type('hour', '12');
+ const hour = input('hour');
+ h.perform.mockImplementationOnce(async request => {
+ h.definition = request.input.definition; h.revision++;
+ throw new Error('Response lost');
+ });
+ await click('save');
+ expect(h.invoke).toHaveBeenCalledOnce();
+ expect(container.textContent).toContain('Response lost');
+ expect(container.textContent).not.toContain('changed');
+ expect(input('hour')).toBe(hour); expect(hour.value).toBe('12');
+ await type('hour', '13'); await click('save');
+ expect(h.perform).toHaveBeenCalledTimes(2);
+ expect(h.perform.mock.calls[1][0].input).toMatchObject({ revision: 2, definition: { triggers: [{ expression: '0 13 * * *' }] } });
+});
+
+it.each(['ios', 'android'])('shows the action error when the connection goes offline before it settles on %s', async platform => {
+ h.platform = platform;
+ await openExisting(); await type('hour', '12');
+ let reject!: (error: Error) => void;
+ h.perform.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ await click('save');
+ const reads = h.read.mock.calls.length;
+ await render(false);
+ await act(async () => reject(new Error('Host rejected the automation')));
+ expect(container.textContent).toContain('Host rejected the automation');
+ expect(container.textContent).toContain('offline');
+ expect(input('hour').value).toBe('12');
+ expect(h.read).toHaveBeenCalledTimes(reads);
+ await click('save'); expect(h.invoke).toHaveBeenCalledOnce();
+ await render(true); await click('save');
+ expect(h.perform).toHaveBeenCalledTimes(2);
+});
+
+it.each(['ios', 'android'])('disables run and delete during an ordinary refresh on %s', async platform => {
+ h.platform = platform;
+ await openExisting();
+ let finish!: (value: ReturnType<typeof resource>) => void;
+ h.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ await act(async () => h.foreground?.('active'));
+ for (const label of ['run', 'delete']) {
+ expect([...container.querySelectorAll('button')].find(node => node.textContent === label)?.disabled).toBe(true);
+ await click(label);
+ }
+ expect(h.invoke).not.toHaveBeenCalled(); expect(h.alert).not.toHaveBeenCalled();
+ await act(async () => finish(resource('bot:bot/rule')));
+ for (const label of ['run', 'delete']) {
+ expect([...container.querySelectorAll('button')].find(node => node.textContent === label)?.disabled).toBe(false);
+ }
+ await click('run'); expect(h.perform).toHaveBeenCalledOnce();
+});
+
+it.each(['ios', 'android'])('does not repeat a lost-acknowledgement run and blocks running or queued history on %s', async platform => {
+ h.platform = platform;
+ await openExisting();
+ h.perform.mockImplementationOnce(async () => {
+ h.history = [{ id: 'run-1', status: 'queued', createdAt: 1 }];
+ throw new Error('Response lost');
+ });
+ await click('run');
+ expect(h.invoke).toHaveBeenCalledOnce();
+ for (const status of ['queued', 'running']) {
+ h.history = [{ id: 'run-1', status, createdAt: 1 }];
+ await act(async () => h.foreground?.('active'));
+ expect([...container.querySelectorAll('button')].find(node => node.textContent === 'run')?.disabled).toBe(true);
+ await click('run'); expect(h.invoke).toHaveBeenCalledOnce();
+ }
+ h.history = [{ id: 'run-1', status: 'success', createdAt: 1 }];
+ await act(async () => h.foreground?.('active'));
+ expect(h.invoke).toHaveBeenCalledOnce();
+ expect(container.textContent).toContain('success');
+ await click('run'); expect(h.perform).toHaveBeenCalledTimes(2);
+});
+
it('waits for reconciliation and discards a late read after switching accounts', async () => {
await openExisting(); await type('hour', '12');
h.perform.mockRejectedValueOnce(new Error('Save rejected'));
diff --git a/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx b/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx
index 0d018f2b2b..54f8bea342 100644
--- a/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx
+++ b/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx
@@ -135,12 +135,12 @@ export function CompanionAutomationNativeView(p: CompanionAutomationNativeViewPr
</Fragment> : note(tr('largeDefinition'))}
{detail.editable ? <Section><Action label={tr('save')} onPress={() => p.onAct(p.selected === 'new' ? 'routine-create' : 'routine-save')} blocked={p.busy || p.loading || !p.online || !p.dirty || !getRoutineActionId(p.resource, p.selected === 'new' ? 'routine-create' : 'routine-save')} testID="companion.automation.save" /></Section> : null}
{p.selected !== 'new' ? <>
- {getRoutineActionId(p.resource, 'routine-run') ? <Section><Action label={tr(p.dirty ? 'saveAndRun' : 'run')} onPress={() => p.onAct('routine-run')} blocked={p.busy || !p.online || detail.history.some(r => r.status === 'running' || r.status === 'queued')} /></Section> : null}
+ {getRoutineActionId(p.resource, 'routine-run') ? <Section><Action label={tr(p.dirty ? 'saveAndRun' : 'run')} onPress={() => p.onAct('routine-run')} blocked={p.busy || p.loading || !p.online || detail.history.some(r => r.status === 'running' || r.status === 'queued')} /></Section> : null}
<Section title={tr('history')}>{detail.history.length ? detail.history.map(run => <VStack key={run.id} alignment="leading" spacing={spacing.sm}>
<Text>{tr(run.status)}</Text><Text modifiers={[font({ textStyle: 'caption' }), foregroundStyle(colors.textSecondary)]}>{new Date(run.createdAt).toLocaleString(i18n.language)}</Text>
{run.resultText ? <Text modifiers={[textSelection(true)]}>{run.resultText}</Text> : null}{run.error ? <Text modifiers={[foregroundStyle(colors.statusError), textSelection(true)]}>{run.error}</Text> : null}
</VStack>) : <Text modifiers={[foregroundStyle(colors.textSecondary)]}>{tr('noRuns')}</Text>}</Section>
- {getRoutineActionId(p.resource, 'routine-delete') ? <Section><Action label={tr('delete')} onPress={p.onDelete} blocked={p.busy || p.dirty || !p.online} destructive /></Section> : null}
+ {getRoutineActionId(p.resource, 'routine-delete') ? <Section><Action label={tr('delete')} onPress={p.onDelete} blocked={p.busy || p.loading || p.dirty || !p.online} destructive /></Section> : null}
</> : null}
</> : null}
</ComposerSheet>;
diff --git a/apps/mobile/src/session/CompanionAutomationSheet.tsx b/apps/mobile/src/session/CompanionAutomationSheet.tsx
index d9f584f06a..1bfe07cd01 100644
--- a/apps/mobile/src/session/CompanionAutomationSheet.tsx
+++ b/apps/mobile/src/session/CompanionAutomationSheet.tsx
@@ -16,7 +16,7 @@ import { fontWeight, radius, spacing, typeScale, lineHeight } from '@/theme/toke
import { CompanionSheet } from './CompanionSheet';
import { CompanionAutomationNativeView } from './CompanionAutomationNativeView';
import { useRoutineCronFields } from './useRoutineCronFields';
-import { emptyRoutineDefinition, getRoutineActionId, parseRoutineDetail, parseRoutineSummaries, routineDraftValid, type RoutineDefinition, type RoutineDetail, type RoutineSummary, type RoutineTrigger } from './companionRoutines';
+import { emptyRoutineDefinition, getRoutineActionId, parseRoutineDefinition, parseRoutineDetail, parseRoutineSummaries, routineDraftValid, type RoutineDefinition, type RoutineDetail, type RoutineSummary, type RoutineTrigger } from './companionRoutines';
function automationFailure(error: unknown, tr: (key: string) => string): string {
const code = typeof (error as { code?: unknown } | null)?.code === 'string'
@@ -52,6 +52,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId
const [initialDraft, setInitialDraft] = useState('');
const initialDraftRef = useRef(initialDraft); initialDraftRef.current = initialDraft;
const detailRef = useRef(detail); detailRef.current = detail;
+ const draftRef = useRef(draft); draftRef.current = draft;
const [draftGeneration, setDraftGeneration] = useState(0);
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState(false);
@@ -63,10 +64,13 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId
const dirty = draft !== null && JSON.stringify(draft) !== initialDraft;
const dirtyRef = useRef(dirty); dirtyRef.current = dirty;
const identity = `${accountGeneration}:${deviceId}:${collectionId}:${botId}`;
- const current = useRef({ identity, visible, selected }); current.current = { identity, visible, selected };
+ const current = useRef({ identity, visible, selected, online }); current.current = { identity, visible, selected, online };
const valid = (scope: string, page: string | null) => current.current.visible && current.current.identity === scope && current.current.selected === page;
const load = useCallback(async (actionError?: string) => {
- if (!visible || !online || !botId) return;
+ if (!visible || !botId || !valid(identity, selected)) return;
+ // An action may settle after connectivity changed; preserve its reason even offline.
+ if (actionError) setError(actionError);
+ if (!current.current.online) { setLoading(false); return; }
const generation = ++seq.current;
const scope = identity;
setLoading(true); setError(actionError ?? null);
@@ -78,14 +82,20 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId
if (!block) throw new Error(t('devices.companions.automation.unsupported'));
if (selected) {
const next = parseRoutineDetail(block.data);
- // Never renew a dirty draft's write authority against a newer version.
- if (dirtyRef.current && detailRef.current && next.revision !== detailRef.current.revision) {
- setResource(null);
- setError(t('devices.companions.automation.changed'));
- return;
+ const versionChanged = dirtyRef.current && detailRef.current && next.revision !== detailRef.current.revision;
+ if (versionChanged) {
+ // A lost save acknowledgement is settled only by identical authoritative content.
+ // Different remote edits must never grant stale drafts overwrite authority.
+ if (!next.input || JSON.stringify(next.input) !== JSON.stringify(parseRoutineDefinition(draftRef.current))) {
+ setResource(null);
+ const changed = t('devices.companions.automation.changed');
+ setError(actionError ? `${actionError}\n${changed}` : changed);
+ return;
+ }
+ setInitialDraft(JSON.stringify(draftRef.current)); dirtyRef.current = false;
}
setDetail(next);
- if (!dirtyRef.current) {
+ if (!dirtyRef.current && !versionChanged) {
const value = next.input ?? (selected === 'new' ? emptyRoutineDefinition() : null);
const serialized = JSON.stringify(value);
if (serialized !== initialDraftRef.current) {
@@ -248,10 +258,10 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId
{draft.triggers.length < 32 ? button(tr('addTrigger'), () => setDraft({ ...draft, triggers: [...draft.triggers, { id: randomUUID(), kind: 'interval', intervalMs: 3_600_000 }] })) : null}
</> : <Text style={styles.empty}>{tr('largeDefinition')}</Text>}
{selected !== 'new' ? <View style={styles.group}>
- {getRoutineActionId(resource, 'routine-run') ? button(tr(dirty ? 'saveAndRun' : 'run'), () => void act('routine-run'), false, !online || detail.history.some((r) => r.status === 'running' || r.status === 'queued')) : null}
+ {getRoutineActionId(resource, 'routine-run') ? button(tr(dirty ? 'saveAndRun' : 'run'), () => void act('routine-run'), false, loading || !online || detail.history.some((r) => r.status === 'running' || r.status === 'queued')) : null}
<Text style={styles.heading}>{tr('history')}</Text>
{detail.history.length ? detail.history.map((run) => <View key={run.id} style={styles.field}><Text style={styles.label}>{tr(run.status)}</Text><Text style={styles.secondary}>{new Date(run.createdAt).toLocaleString(i18n.language)}</Text>{run.resultText ? <Text selectable style={styles.label}>{run.resultText}</Text> : null}{run.error ? <Text selectable style={styles.error}>{run.error}</Text> : null}</View>) : <Text style={styles.empty}>{tr('noRuns')}</Text>}
- {getRoutineActionId(resource, 'routine-delete') ? button(tr('delete'), confirmDelete, true, dirty || !online) : null}
+ {getRoutineActionId(resource, 'routine-delete') ? button(tr('delete'), confirmDelete, true, loading || dirty || !online) : null}
</View> : null}
</> : null}
</CompanionSheet>;