Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): refresh automation actions after failed submissions
davide97fd623a0cf
diff --git a/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx b/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsxindex 696181f234..f29429d387 100644--- a/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx+++ b/apps/mobile/src/__tests__/CompanionAutomationSheet.test.tsx@@ -8,18 +8,24 @@ import { emptyRoutineDefinition, type RoutineDefinition } from '../session/compaconst 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: 1, sheet: null as any,+ definition: null as any, revision: 0, existing: false, now: 0, uuid: 0, perform: vi.fn(), sheet: null as any, platform: 'ios',}));vi.mock('react-i18next', () => { const t = (key: string) => key.split('.').at(-1)!; return { useTranslation: () => ({ t, i18n: { language: 'en' } }) }; });vi.mock('react-native', () => ({- Platform: { OS: 'ios' }, StyleSheet: { create: (value: any) => value, hairlineWidth: 1 },- View: 'div', Pressable: 'button', Switch: 'input', ScrollView: 'div', ActivityIndicator: 'span',+ Platform: { get OS() { return h.platform; } }, StyleSheet: { create: (value: any) => value, hairlineWidth: 1 },+ View: ({ children }: any) => <div>{children}</div>,+ Pressable: ({ children, onPress, disabled, testID }: any) => <button disabled={disabled} onClick={onPress} data-testid={testID}>{children}</button>,+ Switch: ({ value, onValueChange, disabled }: any) => <input type="checkbox" checked={value} disabled={disabled} onChange={e => onValueChange(e.currentTarget.checked)} />,+ ScrollView: 'div', ActivityIndicator: () => <span>Loading</span>,useWindowDimensions: () => ({ width: 402, height: 874 }), Alert: { alert: h.alert },AppState: { addEventListener: (_name: string, fn: any) => { h.foreground = fn; return { remove() {} }; } },}));-vi.mock('@/components/AppText', () => ({ Text: 'span', TextInput: () => { throw new Error('iOS automation must not mount the RN input path'); } }));+vi.mock('@/components/AppText', () => ({ Text: ({ children }: any) => <span>{children}</span>, TextInput: (p: any) => {+ if (h.platform === 'ios') throw new Error('iOS automation must not mount the RN input path');+ return <input aria-label={p.accessibilityLabel} value={p.value} disabled={p.editable === false} onInput={e => p.onChangeText(e.currentTarget.value)} onChange={() => {}} />;+} }));vi.mock('lucide-react-native', () => ({ ChevronRight: () => null, Clock3: () => null, Plus: () => null }));-vi.mock('expo-crypto', () => ({ randomUUID: () => 'created-trigger' }));+vi.mock('expo-crypto', () => ({ randomUUID: () => `creation-request-${++h.uuid}` }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: h.account }) }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink, subscribe: h.subscribe, unsubscribe: h.unsubscribe, onRemoteResourceChanged: h.changed, connectionEpoch: 1 }) }));vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));@@ -27,7 +33,10 @@ vi.mock('@/device-link/remoteResources', () => ({ getRemoteResource: (...args: avi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: (error: Error) => error.message }));vi.mock('@/theme', () => ({ iconSize: { action: 20, lg: 24, xs: 12 }, spacing: { xs: 4, sm: 8, md: 12 }, useTheme: () => ({ mode: 'light', colors: {} }), useThemedStyles: () => ({}) }));vi.mock('../session/CompanionChoice', () => ({ CompanionChoice: () => null }));-vi.mock('../session/CompanionSheet', () => ({ CompanionSheet: () => { throw new Error('legacy automation sheet mounted'); } }));+vi.mock('../session/CompanionSheet', () => ({ CompanionSheet: ({ children, footer }: any) => {+ if (h.platform === 'ios') throw new Error('legacy automation sheet mounted');+ return <div>{children}{footer}</div>;+} }));vi.mock('../session/CompanionAutomationNativeView', async () => import('../session/CompanionAutomationNativeView.ios'));vi.mock('../session/ComposerSheet', async () => import('../session/ComposerSheet.ios'));vi.mock('../session/ComposerNativeSection', () => ({ ComposerNativeSection: ({ title, children }: any) => <section aria-label={title}>{children}</section> }));@@ -60,11 +69,22 @@ vi.mock('@expo/ui/swift-ui', () => {});Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });let root: Root; let container: HTMLDivElement;-function resource(selected: boolean) {- return { ref: { collectionId: 'routines', kind: 'routine', id: selected ? 'bot:bot/new' : 'bot:bot' }, display: { title: 'Automations' }, links: [], revision: String(h.revision),- actions: [{ id: 'opaque-create', label: 'Create' }], blocks: [{ primitive: selected ? 'routine-detail' : 'routine-list', data: selected- ? { id: null, revision: h.revision, editable: true, input: h.definition, sources: [{ id: 'mail', name: 'Mail', status: 'ready', events: [{ type: 'received', name: 'Received', fields: ['sender', 'subject'] }] }], history: [], operationActions: { 'routine-create': 'opaque-create' } }- : { items: [], operationActions: { 'routine-create': 'opaque-create' } } }] };+let grantId = 0;+const grants = new Map<string, { operation: string; revision: number; expires: number }>();+function resource(id: string) {+ const selected = id.includes('/');+ const existing = selected && !id.endsWith('/new');+ const revision = existing ? h.revision : 0;+ const operations = existing ? ['routine-save', 'routine-run', 'routine-delete'] : ['routine-create'];+ const operationActions = Object.fromEntries(operations.map(operation => {+ const token = `opaque-${++grantId}`;+ grants.set(token, { operation, revision, expires: h.now + 15 * 60_000 });+ return [operation, token];+ }));+ 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 }+ : { 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" />)); }function input(label: string) { const node = container.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`); if (!node) throw new Error(`Missing ${label}`); return node; }@@ -73,10 +93,19 @@ async function click(label: string) { await act(async () => { const button = [..async function select(label: string, value: string) { await act(async () => { const node = container.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`)!; node.value = value; node.dispatchEvent(new Event('change', { bubbles: true })); }); }async function open() { await render(); await click('new'); }beforeEach(() => {- vi.clearAllMocks(); h.account = 1; h.revision = 1; h.definition = emptyRoutineDefinition();+ vi.resetAllMocks(); h.account = 1; h.revision = 0; h.existing = false; h.now = 0; h.uuid = 0; h.platform = 'ios'; h.definition = emptyRoutineDefinition();+ grants.clear(); grantId = 0;h.changed.mockReturnValue(() => {}); h.openLink.mockResolvedValue(undefined);- h.read.mockImplementation((_invoke, _target, ref) => Promise.resolve(resource(ref.id.endsWith('/new'))));- h.invoke.mockResolvedValue({ effects: [] });+ h.read.mockImplementation((_invoke, _target, ref) => Promise.resolve(resource(ref.id)));+ h.perform.mockResolvedValue({ effects: [] });+ h.invoke.mockImplementation(async (_invoke, _target, request) => {+ const grant = grants.get(request.actionId);+ if (!grant || grant.expires <= h.now || grant.revision !== request.input.revision)+ throw Object.assign(new Error('Refresh before retrying'), { code: 'PRECONDITION_FAILED' });+ // Host consumes before running business validation, including rejected operations.+ grants.delete(request.actionId);+ return h.perform({ ...request, actionId: grant.operation });+ });container = document.createElement('div'); document.body.append(container); root = createRoot(container);});afterEach(() => { act(() => root.unmount()); container.remove(); });@@ -97,7 +126,7 @@ it('keeps native editor identity through name changes and submits the edited timexpect(save?.closest('[data-testid="native-form"]')).toBe(hour.closest('[data-testid="native-form"]'));await click('save');expect(h.invoke).toHaveBeenCalledOnce();- expect(h.invoke.mock.calls[0][2]).toMatchObject({ actionId: 'opaque-create', input: { revision: 1, definition: { name: '应该', prompt: 'Check the inbox', triggers: [{ expression: '05 08 * * *' }] } } });+ expect(h.perform.mock.calls[0][0]).toMatchObject({ actionId: 'routine-create', input: { revision: 0, definition: { name: '应该', prompt: 'Check the inbox', triggers: [{ expression: '05 08 * * *' }] } } });});it('keeps editing and focus when a foreground refresh returns while the draft is dirty', async () => {@@ -116,14 +145,22 @@ it('loads fresh native field values when a clean remote draft changes', async ()expect(input('name')).not.toBe(name); expect(input('name').value).toBe('Remote'); expect(input('hour').value).toBe('17'); expect(input('minute').value).toBe('45');});-it('preserves values and shows the host error after an invalid time is rejected', async () => {- await open(); await type('name', 'Brief'); await type('instructions', 'Summarize'); await type('hour', '123');- h.invoke.mockRejectedValueOnce(new Error('Invalid cron hour'));+it.each(['ios', 'android'])('renews a consumed create action and keeps the draft and request ID on %s', async platform => {+ h.platform = platform;+ await open(); await type('name', 'Brief'); await type('instructions', 'Summarize'); await type('hour', '11');+ const hour = input('hour');+ h.perform.mockRejectedValueOnce(new Error('Host rejected the automation'));await click('save');- expect(input('hour').value).toBe('123');- expect([...container.querySelectorAll('[data-native-selectable="true"]')].some(node => node.textContent === 'Invalid cron hour')).toBe(true);+ expect(input('hour')).toBe(hour); expect(hour.value).toBe('11');+ expect(container.textContent).toContain('Host rejected the automation');+ if (platform === 'ios') expect([...container.querySelectorAll('[data-native-selectable="true"]')].some(node => node.textContent === 'Host rejected the automation')).toBe(true);+ expect(h.invoke).toHaveBeenCalledTimes(1);await type('hour', '12'); await click('save');+ expect(h.perform).toHaveBeenCalledTimes(2);+ expect(h.invoke.mock.calls[1][2].actionId).not.toBe(h.invoke.mock.calls[0][2].actionId);+ expect(h.invoke.mock.calls[1][2].input.requestId).toBe(h.invoke.mock.calls[0][2].input.requestId);expect(h.invoke.mock.calls[1][2].input.definition.triggers[0].expression).toBe('0 12 * * *');+ expect(container.querySelector('input[aria-label="hour"]')).toBeNull();});it('preserves each trigger kind and the remaining native filter values after removing a filter', async () => {@@ -137,3 +174,140 @@ it('preserves each trigger kind and the remaining native filter values after remawait type('hour', '18'); await type('minute', '30'); await click('save');expect(h.invoke.mock.calls[0][2].input.definition.triggers).toEqual([{ id: 'mail-trigger', kind: 'cron', expression: '30 18 * * 5', timezone: expect.any(String) }]);});++it.each(['ios', 'android'])('blocks invalid times before invoking and allows correction on %s', async platform => {+ h.platform = platform;+ await open(); await type('name', 'Brief'); await type('instructions', 'Summarize');+ for (const [field, invalid, corrected] of [['hour', '25', '12'], ['hour', '', '08'], ['minute', '60', '30'], ['minute', '', '05']]) {+ await type(field!, invalid!); await click('save');+ expect(h.invoke).not.toHaveBeenCalled();+ expect(input(field!).value).toBe(invalid);+ expect(container.textContent).toContain('invalid');+ await type(field!, corrected!);+ }+ await click('save');+ expect(h.perform).toHaveBeenCalledOnce();+ expect(h.perform.mock.calls[0][0].input.definition.triggers[0].expression).toBe('05 08 * * *');+});++async function openExisting() {+ h.existing = true; h.revision = 1;+ h.definition = { ...emptyRoutineDefinition(), name: 'Existing', prompt: 'Check the inbox' };+ await render(); await click('Existing');+}++it.each(['ios', 'android'])('renews a consumed save action without replacing edited fields on %s', async platform => {+ h.platform = platform;+ await openExisting(); await type('hour', '11');+ h.perform.mockRejectedValueOnce(new Error('Host rejected the automation'));+ await click('save');+ expect(input('hour').value).toBe('11');+ await type('hour', '12'); await click('save');+ expect(h.perform).toHaveBeenCalledTimes(2);+ expect(h.perform.mock.calls[1][0]).toMatchObject({ actionId: 'routine-save', input: { revision: 1, definition: { triggers: [{ expression: '0 12 * * *' }] } } });+ expect(h.invoke.mock.calls[1][2].actionId).not.toBe(h.invoke.mock.calls[0][2].actionId);+});++it('recovers from expiry without automatically repeating the write', async () => {+ await openExisting(); await type('hour', '12'); h.now += 16 * 60_000;+ await click('save');+ expect(h.invoke).toHaveBeenCalledOnce(); expect(h.perform).not.toHaveBeenCalled();+ expect(input('hour').value).toBe('12');+ await click('save');+ expect(h.perform).toHaveBeenCalledOnce();+});++it('reuses the creation intent after a lost acknowledgement without creating a duplicate', async () => {+ await open(); await type('name', 'Brief'); await type('instructions', 'Summarize');+ const created = new Map<string, unknown>();+ h.perform.mockImplementation(async request => {+ const { requestId, definition } = request.input;+ if (!created.has(requestId)) {+ created.set(requestId, definition);+ throw new Error('Response lost');+ }+ expect(definition).toEqual(created.get(requestId));+ return { effects: [] };+ });+ await click('save');+ expect(h.invoke).toHaveBeenCalledOnce(); expect(created.size).toBe(1);+ expect(input('name').value).toBe('Brief');+ await click('save');+ expect(created.size).toBe(1);+ expect(container.querySelector('input[aria-label="name"]')).toBeNull();+});++it('keeps a failed refresh retryable without letting save reuse a consumed action', async () => {+ await openExisting(); await type('hour', '12');+ h.perform.mockRejectedValueOnce(new Error('Save rejected'));+ h.read.mockRejectedValueOnce(new Error('Read unavailable'));+ await click('save');+ expect(container.textContent).toContain('Save rejected');+ expect(container.textContent).toContain('loadFailed');+ expect(container.querySelector<HTMLButtonElement>('[data-testid="companion.automation.save"]')!.disabled).toBe(true);+ await click('save'); expect(h.invoke).toHaveBeenCalledOnce();+ await click('retry');+ expect(input('hour').value).toBe('12');+ await click('save'); expect(h.perform).toHaveBeenCalledTimes(2);+});++it('preserves a dirty draft and blocks stale saves when the host version changed', async () => {+ await openExisting(); await type('hour', '12');+ h.perform.mockImplementationOnce(async () => {+ h.revision = 2;+ h.definition = { ...h.definition, name: 'Changed elsewhere' };+ throw new Error('Response lost');+ });+ await click('save');+ 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);+ await click('retry'); await click('save');+ expect(h.invoke).toHaveBeenCalledOnce();+});++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'));+ let finish!: (value: ReturnType<typeof resource>) => void;+ const oldResult = resource('bot:bot/rule');+ h.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ await click('save');+ expect(container.querySelector<HTMLButtonElement>('[data-testid="companion.automation.save"]')!.disabled).toBe(true);+ await click('save'); expect(h.invoke).toHaveBeenCalledOnce();+ h.account++; h.existing = false;+ await render();+ await act(async () => finish(oldResult));+ expect(container.querySelector('input[aria-label="hour"]')).toBeNull();+ expect(container.textContent).not.toContain('Save rejected');+});++it.each(['run', 'delete'])('renews a consumed %s action for an explicit retry', async operation => {+ await openExisting();+ const perform = async () => {+ await click(operation);+ if (operation === 'delete') await act(async () => h.alert.mock.calls.at(-1)![2].find((item: any) => item.style === 'destructive').onPress());+ };+ h.perform.mockRejectedValueOnce(new Error('Operation rejected'));+ await perform(); expect(h.invoke).toHaveBeenCalledOnce();+ expect(container.textContent).toContain('Operation rejected');+ await perform();+ expect(h.perform).toHaveBeenCalledTimes(2);+ expect(h.perform.mock.calls[1][0].actionId).toBe(`routine-${operation}`);+ expect(h.invoke.mock.calls[1][2].actionId).not.toBe(h.invoke.mock.calls[0][2].actionId);+});++it('keeps a successful save committed when the following run fails', async () => {+ await openExisting(); await type('hour', '12');+ h.perform.mockImplementationOnce(async request => {+ h.definition = request.input.definition; h.revision++;+ return { effects: [] };+ }).mockRejectedValueOnce(new Error('Run rejected'));+ await click('saveAndRun');+ expect(h.perform.mock.calls.map(([request]) => request.actionId)).toEqual(['routine-save', 'routine-run']);+ expect(input('hour').value).toBe('12');+ expect(container.textContent).toContain('Run rejected');+ await click('run');+ expect(h.perform.mock.calls.map(([request]) => request.actionId)).toEqual(['routine-save', 'routine-run', 'routine-run']);+ expect(h.perform.mock.calls[2][0].input.revision).toBe(2);+});diff --git a/apps/mobile/src/__tests__/companionRoutines.test.ts b/apps/mobile/src/__tests__/companionRoutines.test.tsindex 683f8a05c9..6400c8def0 100644--- a/apps/mobile/src/__tests__/companionRoutines.test.ts+++ b/apps/mobile/src/__tests__/companionRoutines.test.ts@@ -8,6 +8,15 @@ describe('companion automation data boundary', () => {expect(routineDraftValid(draft)).toBe(false);expect(routineDraftValid({ ...draft, name: 'Daily brief', prompt: 'Summarize my inbox' })).toBe(true);});+ it.each(['0 25 * * *', '60 9 * * *', '0 * * *', ' 9 * * *', '0 -1 * * *', '0 9.5 * * *', '0 9 32 * *', '0 9 * 13 *'])('rejects incomplete or out-of-range literal cron fields: %s', expression => {+ const draft = { ...emptyRoutineDefinition(), name: 'Brief', prompt: 'Check', triggers: [{ id: 'daily', kind: 'cron' as const, expression, timezone: 'UTC' }] };+ // Partial values remain editable; only submission is blocked.+ expect(parseRoutineDefinition(draft)).toEqual(draft);+ expect(routineDraftValid(draft)).toBe(false);+ });+ it.each(['00 00 * * *', '59 23 * * *', '05 08 * * 1-5', '0 9 31 * *', '0 9 * * 7', '*/15 8-18 * * 1,3,5'])('keeps valid presets and custom cron syntax available: %s', expression => {+ expect(routineDraftValid({ ...emptyRoutineDefinition(), name: 'Brief', prompt: 'Check', triggers: [{ id: 'daily', kind: 'cron', expression, timezone: 'UTC' }] })).toBe(true);+ });it('keeps mixed OR triggers and event filters intact while editing', () => {const draft = { name: 'Brief', prompt: 'Check', enabled: true, triggers: [{ id: 'a', kind: 'cron', expression: '30 8 * * 1-5', timezone: 'Asia/Shanghai' },diff --git a/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx b/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsxindex 49b7e211a3..0d018f2b2b 100644--- a/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx+++ b/apps/mobile/src/session/CompanionAutomationNativeView.ios.tsx@@ -133,7 +133,7 @@ export function CompanionAutomationNativeView(p: CompanionAutomationNativeViewPr</Section>)}{draft.triggers.length < 32 ? <Section><Action label={tr('addTrigger')} onPress={() => p.onChange(d => d && ({ ...d, triggers: [...d.triggers, { id: randomUUID(), kind: 'interval', intervalMs: 3_600_000 }] }))} blocked={p.busy} /></Section> : null}</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.online || !p.dirty} testID="companion.automation.save" /></Section> : null}+ {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}<Section title={tr('history')}>{detail.history.length ? detail.history.map(run => <VStack key={run.id} alignment="leading" spacing={spacing.sm}>diff --git a/apps/mobile/src/session/CompanionAutomationSheet.tsx b/apps/mobile/src/session/CompanionAutomationSheet.tsxindex 3f1a4e6d41..d9f584f06a 100644--- a/apps/mobile/src/session/CompanionAutomationSheet.tsx+++ b/apps/mobile/src/session/CompanionAutomationSheet.tsx@@ -65,11 +65,11 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdconst identity = `${accountGeneration}:${deviceId}:${collectionId}:${botId}`;const current = useRef({ identity, visible, selected }); current.current = { identity, visible, selected };const valid = (scope: string, page: string | null) => current.current.visible && current.current.identity === scope && current.current.selected === page;- const load = useCallback(async () => {+ const load = useCallback(async (actionError?: string) => {if (!visible || !online || !botId) return;const generation = ++seq.current;const scope = identity;- setLoading(true); setError(null);+ setLoading(true); setError(actionError ?? null);try {await openLink(deviceId);const result = await getRemoteResource(invoke, { deviceId, deviceName }, { collectionId, kind: 'routine', id: `bot:${botId}${selected ? `/${selected}` : ''}` }, i18n.language, ['routine-list', 'routine-detail']);@@ -80,6 +80,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdconst 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;}@@ -96,7 +97,8 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId} catch (e) {if (valid(scope, selected) && generation === seq.current) {const unsupported = t('devices.companions.automation.unsupported');- setError(e instanceof Error && e.message === unsupported ? unsupported : t('devices.resources.loadFailed'));+ const readError = e instanceof Error && e.message === unsupported ? unsupported : t('devices.resources.loadFailed');+ setError(actionError ? `${actionError}\n${readError}` : readError);}}finally { if (valid(scope, selected) && generation === seq.current) setLoading(false); }@@ -131,7 +133,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botId};const act = async (actionId: string) => {const capabilityId = getRoutineActionId(resource, actionId);- if (!valid(identity, selected) || inFlight.current || !online || !resource || !capabilityId) return;+ if (!valid(identity, selected) || inFlight.current || loading || !online || !resource || !capabilityId) return;if (actionId === 'routine-create' || actionId === 'routine-save' || actionId === 'routine-run' && dirty) {if (!draft || !routineDraftValid(draft)) { setError(tr('invalid')); return; }}@@ -165,7 +167,14 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdif (!valid(scope, page)) return;if (actionId === 'routine-run') { await load(); }else open(null);- } catch (e) { if (valid(scope, page)) setError(automationFailure(e, tr)); }+ } catch (e) {+ if (valid(scope, page)) {+ // The host consumes opaque actions even when validation or the response fails.+ // Reconcile by reading, never replay a write or renew a creation request ID.+ setResource(null);+ await load(automationFailure(e, tr));+ }+ }finally { if (operationGeneration.current === operation) { inFlight.current = false; if (current.current.identity === scope) setBusy(false); } }};const button = (label: string, onPress: () => void, destructive = false, disabled = false) => (@@ -198,7 +207,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdreturn <CompanionSheet visible={visible} onClose={() => leave(onClose)} preventDismiss={dirty || busy}title={selected ? draft?.name || tr('new') : t('devices.companionProfile.automation')}onBack={selected ? () => leave(() => open(null)) : undefined} testID="companion.automationSheet"- footer={selected && detail?.editable ? button(tr('save'), () => void act(selected === 'new' ? 'routine-create' : 'routine-save'), false, !online || !dirty) : undefined}>+ footer={selected && detail?.editable ? button(tr('save'), () => void act(selected === 'new' ? 'routine-create' : 'routine-save'), false, !online || !dirty || loading || !getRoutineActionId(resource, selected === 'new' ? 'routine-create' : 'routine-save')) : undefined}>{!online ? <Text style={styles.error}>{tr('offline')}</Text> : null}{error ? <View style={styles.field}><Text selectable style={styles.error}>{error}</Text>{button(tr('retry'), () => void load(), false, !online)}</View> : null}{loading ? <ActivityIndicator color={colors.textSecondary} style={styles.field} /> : null}diff --git a/apps/mobile/src/session/companionRoutines.ts b/apps/mobile/src/session/companionRoutines.tsindex 3c41388b13..eb3d17c01a 100644--- a/apps/mobile/src/session/companionRoutines.ts+++ b/apps/mobile/src/session/companionRoutines.ts@@ -95,5 +95,18 @@ export function emptyRoutineDefinition(): RoutineDefinition {}export function routineDraftValid(draft: RoutineDefinition): boolean {return Boolean(draft.name.trim() && draft.prompt.trim() && draft.triggers.length && parseRoutineDefinition(draft)+ && draft.triggers.every((t) => t.kind !== 'cron' || routineCronFieldsValid(t))&& draft.triggers.every((t) => t.kind !== 'event' || (t.sourceId && t.eventType && t.filters.every((f) => f.field && f.value))));}++/** Catch incomplete presets and literal field bounds; full cron semantics remain host-owned. */+function routineCronFieldsValid(trigger: Extract<RoutineTrigger, { kind: 'cron' }>): boolean {+ const fields = trigger.expression.trim().split(/\s+/);+ const ranges = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]] as const;+ return Boolean(trigger.timezone.trim()) && fields.length === ranges.length && fields.every((field, index) => {+ if (!/^[+-]?\d+(?:\.\d+)?$/.test(field)) return true;+ const value = Number(field);+ const [min, max] = ranges[index]!;+ return Number.isSafeInteger(value) && value >= min && value <= max;+ });+}