Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 去掉任务页资源卡片的「操作失败 / 重试」卡片 (#5391)
Dashbb0762e80dac
diff --git a/apps/mobile/src/__tests__/SessionResourceCards.test.tsx b/apps/mobile/src/__tests__/SessionResourceCards.test.tsxnew file mode 100644index 0000000000..eb8091711c--- /dev/null+++ b/apps/mobile/src/__tests__/SessionResourceCards.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom+import { act, createElement, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { RemoteResource } from "@cindy/device-link";+import { SessionResourceCards } from "@/session/SessionResourceCards";+import type { useSessionResourceCards } from "@/session/useSessionResourceCards";++vi.mock("react-native", async () => {+ const { createElement } = await import("react");+ const View = ({ children }: { children?: ReactNode }) =>+ createElement("div", null, children);+ return {+ View,+ Text: View,+ ScrollView: View,+ ActivityIndicator: () => createElement("progress"),+ StyleSheet: { create: (value: unknown) => value },+ useWindowDimensions: () => ({ width: 390, height: 844 }),+ };+});+vi.mock("@/components/AppText", async () => ({+ Text: (await import("react-native")).Text,+}));+vi.mock("@/components/MobilePrimitives", async () => {+ const { createElement } = await import("react");+ return {+ MainWindowActionButton: ({+ action,+ }: {+ action: { label: string; onPress(): void; disabled?: boolean };+ }) =>+ createElement(+ "button",+ { onClick: action.onPress, disabled: action.disabled },+ action.label,+ ),+ };+});+vi.mock("@/theme", async () => {+ const tokens = await import("@/theme/tokens");+ return {+ useTheme: () => ({ colors: tokens.lightColors }),+ useThemedStyles: (make: (value: typeof tokens.lightColors) => unknown) =>+ make(tokens.lightColors),+ };+});+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),+}));++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+type State = ReturnType<typeof useSessionResourceCards>;+const card: RemoteResource = {+ ref: { collectionId: "workflow", kind: "session", id: "task" },+ revision: "1",+ display: { title: "Preparing test" },+ links: [],+ blocks: [+ {+ id: "controls",+ primitive: "session-controls",+ fallbackMarkdown: "Preparing test",+ data: { input: "blocked" },+ },+ ],+ actions: [{ id: "start", label: "Start" }],+};+const state = (patch: Partial<State>): State => ({+ resources: [],+ failed: false,+ fresh: true,+ pending: null,+ act: vi.fn(),+ openLink: vi.fn(),+ blocked: false,+ blockedReason: undefined,+ ...patch,+});+let root: Root | undefined;+let host: HTMLDivElement;+function render(value: State) {+ host = document.createElement("div");+ root = createRoot(host);+ act(() =>+ root!.render(createElement(SessionResourceCards, { state: value })),+ );+}+afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+});++describe("SessionResourceCards failure presentation", () => {+ it("renders nothing when the first manifest read fails", () => {+ render(state({ failed: true, fresh: false }));+ expect(host.textContent).toBe("");+ });+ it("shows a failed read of known cards as syncing, without a retry card", () => {+ render(+ state({ resources: [card], failed: true, fresh: false, blocked: true }),+ );+ expect(host.textContent).toContain("Preparing test");+ expect(host.textContent).toContain("shared.syncing");+ expect(host.querySelector("progress")).not.toBeNull();+ expect(host.textContent).not.toContain("session.screen.operationFailed");+ expect(host.textContent).not.toContain("devices.resources.retry");+ expect(host.querySelector("button")?.disabled).toBe(true);+ });+ it("shows syncing while input stays blocked before any card is readable", () => {+ render(state({ failed: true, fresh: false, blocked: true }));+ expect(host.textContent).toBe("shared.syncing");+ expect(host.querySelector("button")).toBeNull();+ });+});diff --git a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsxindex 1d60578ee4..432cd49da0 100644--- a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx+++ b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx@@ -65,6 +65,9 @@ vi.mock('@/device-link/remoteResources', () => ({loadRemoteResourceManifest: h.manifest,invokeRemoteResourceAction: h.action,}));+vi.mock('@/device-link/remoteStatus', () => ({+ humanizeRemoteError: (error: unknown) => String(error),+}));vi.mock('@/device-link/focusedTopicSubscription', () => ({startFocusedTopicSubscription: () => () => {},}));@@ -150,7 +153,6 @@ it('does not discover host-wide cards or retry them for a shared-task guest', asawait act(async () => root!.render(createElement(Probe, { device: peer })));expect(h.manifest).not.toHaveBeenCalled();expect(views.get(peer)).toMatchObject({ resources: [], failed: false, blocked: false });- act(() => views.get(peer)!.refresh());foreground('background'); foreground('active');await advance(10_000);expect(h.manifest).not.toHaveBeenCalled();@@ -330,7 +332,7 @@ describe('host task cards on Mobile', () => {await act(async () => slow.resolve(resource('slow')));expect(views.get('mac')?.fresh).toBe(true);});- it('keeps another device usable when one read fails; retries reads only', async () => {+ it('keeps another device usable when one read fails; polls reads only', async () => {await render('task', true);h.get.mockImplementation(async (_invoke, target) => {if (target.deviceId === 'mac') throw new Error('timeout');@@ -343,9 +345,17 @@ describe('host task cards on Mobile', () => {expect(views.get('pc')?.blocked).toBe(false);expect(h.action).not.toHaveBeenCalled();h.get.mockResolvedValue(resource('recovered', 'available'));- act(() => views.get('mac')?.refresh());- await advance();+ await advance(5_200);+ expect(views.get('mac')?.failed).toBe(false);+ });+ it('retries a failed manifest read without a manual retry', async () => {+ h.manifest.mockRejectedValueOnce(new Error('timeout'));+ await render();+ expect(views.get('mac')).toMatchObject({ resources: [], failed: true, blocked: false });+ await advance(5_200);+ expect(h.manifest).toHaveBeenCalledTimes(2);expect(views.get('mac')?.failed).toBe(false);+ expect(views.get('mac')?.resources).toHaveLength(1);});it.each(['account', 'session', 'reconnect'])('ignores late results after %s changes',@@ -361,6 +371,21 @@ describe('host task cards on Mobile', () => {expect(views.get('mac')?.resources[0].revision).toBe('current');},);+ it('does not alert an action failure that settles after the app left the foreground', async () => {+ await render();+ const pending = deferred<{ effects: [] }>();+ h.action.mockReturnValueOnce(pending.promise);+ let run!: Promise<void>;+ act(() => {+ run = views.get('mac')!.act(views.get('mac')!.resources[0], 'start');+ });+ foreground('background');+ await act(async () => {+ pending.reject(new Error('timeout'));+ await run;+ });+ expect(h.alert).not.toHaveBeenCalled();+ });it('refreshes after foreground and reconnect without replaying a timed-out action', async () => {await render();h.action.mockRejectedValueOnce(new Error('timeout after host accepted'));@@ -368,7 +393,11 @@ describe('host task cards on Mobile', () => {views.get('mac')!.act(views.get('mac')!.resources[0], 'start'),);await advance();- expect(views.get('mac')?.failed).toBe(true);+ expect(h.alert).toHaveBeenCalledExactlyOnceWith(+ 'session.screen.operationFailed',+ expect.any(String),+ );+ expect(views.get('mac')?.failed).toBe(false);expect(h.action).toHaveBeenCalledOnce();foreground('background');const before = h.get.mock.calls.length;@@ -383,9 +412,8 @@ describe('host task cards on Mobile', () => {h.link.connectionEpoch += 1;await render();expect(h.action).toHaveBeenCalledOnce();- act(() => views.get('mac')!.refresh());- await advance();- expect(views.get('mac')?.failed).toBe(false);+ await advance(5_200);+ expect(views.get('mac')?.fresh).toBe(true);});it('prevents a double tap and does not carry its pending state to another task', async () => {await render();diff --git a/apps/mobile/src/session/SessionResourceCards.tsx b/apps/mobile/src/session/SessionResourceCards.tsxindex c8b6136df6..b037c50e18 100644--- a/apps/mobile/src/session/SessionResourceCards.tsx+++ b/apps/mobile/src/session/SessionResourceCards.tsx@@ -26,14 +26,15 @@ export function SessionResourceCards({const cards = state.resources.filter((resource) => resource.blocks?.length || resource.actions?.length,);- if (!cards.length && !state.failed && !state.blocked) return null;+ // Failed reads keep polling, so they present as syncing instead of a manual retry.+ if (!cards.length && !state.blocked) return null;return (<ScrollViewstyle={{ maxHeight: height * 0.4 }}contentContainerStyle={styles.stack}keyboardShouldPersistTaps="handled">- {!cards.length && state.blocked && !state.failed ? (+ {!cards.length && state.blocked ? (<View style={[styles.card, styles.heading]}><ActivityIndicator color={colors.textSecondary} /><Text style={styles.body}>{t('shared.syncing')}</Text>@@ -58,12 +59,12 @@ export function SessionResourceCards({testID="session.resourceCard"><View style={styles.heading}>- {(busy && state.fresh) || (!state.fresh && !state.failed) ? (+ {busy || !state.fresh ? (<ActivityIndicator color={colors.textSecondary} />) : null}<Text style={styles.title}>{title}</Text></View>- {!state.fresh && !state.failed ? (+ {!state.fresh ? (<Text style={styles.body}>{t('shared.syncing')}</Text>) : null}{body ? (@@ -109,17 +110,6 @@ export function SessionResourceCards({</View>);})}- {state.failed ? (- <View style={styles.card}>- <Text style={styles.body}>{t('session.screen.operationFailed')}</Text>- <MainWindowActionButton- action={{- label: t('devices.resources.retry'),- onPress: state.refresh,- }}- />- </View>- ) : null}</ScrollView>);}diff --git a/apps/mobile/src/session/useSessionResourceCards.ts b/apps/mobile/src/session/useSessionResourceCards.tsindex 747eee2109..4f038a8e42 100644--- a/apps/mobile/src/session/useSessionResourceCards.ts+++ b/apps/mobile/src/session/useSessionResourceCards.ts@@ -16,6 +16,7 @@ import {getRemoteResource,invokeRemoteResourceAction,} from '@/device-link/remoteResources';+import { humanizeRemoteError } from '@/device-link/remoteStatus';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';export function sessionResourceInputBlocked(@@ -71,7 +72,6 @@ export function useSessionResourceCards(const refresh = useRef<() => void>(() => undefined);const [state, setState] = useState<Snapshot>();const [pending, setPending] = useState<{ binding: string; id: string }>();- const [actionError, setActionError] = useState<string>();const request = useRef<{ binding: string } | null>(null);useFocusEffect(useCallback(() => {@@ -206,9 +206,10 @@ export function useSessionResourceCards(: previous,);});- // Poll only discovered cards in the foreground; a slow read is never superseded by a timer.+ // Poll discovered cards, or a manifest read that failed, in the foreground;+ // a slow read is never superseded by a timer.const poll = setInterval(() => {- if (collections?.length) schedule(false);+ if (!collections || collections.length) schedule(false);}, 5000);return () => {disposed = true;@@ -269,7 +270,6 @@ export function useSessionResourceCards(const token = { binding };request.current = token;setPending({ binding, id: actionId });- setActionError(undefined);try {if (action.confirmation) {const confirmation = action.confirmation;@@ -332,8 +332,14 @@ export function useSessionResourceCards(},i18n.language,);- } catch {- if (current.current === scope) setActionError(binding);+ } catch (error) {+ // Only surface the failure where the user still is; the card itself recovers by polling.+ if (+ current.current === scope &&+ focused.current &&+ AppState.currentState === 'active'+ )+ Alert.alert(t('session.screen.operationFailed'), humanizeRemoteError(error));} finally {if (request.current === token) {request.current = null;@@ -344,7 +350,7 @@ export function useSessionResourceCards(};return {resources: visible?.resources ?? [],- failed: visible?.failed === true || actionError === binding,+ failed: visible?.failed === true,fresh: !!fresh,pending: pendingId,act,@@ -362,10 +368,6 @@ export function useSessionResourceCards(params: { deviceId, sessionId: link.target.sessionId },});},- refresh: () => {- setActionError(undefined);- refresh.current();- },blocked:sessionResourceInputBlocked(visible?.resources ?? []) ||!!pendingId ||