Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8369: fix(mobile): preserve runs while stop requests are pending (#9670)
Jiahao139b13a462c9
diff --git a/apps/mobile/components/issue/run-cancel-button.test.ts b/apps/mobile/components/issue/run-cancel-button.test.tsnew file mode 100644index 0000000000..7df7f6b265--- /dev/null+++ b/apps/mobile/components/issue/run-cancel-button.test.ts@@ -0,0 +1,94 @@+// @vitest-environment node+import { Alert } from "react-native";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useCancelTask } from "@/data/mutations/issues";+import { RunCancelButton } from "./run-cancel-button";++const state = vi.hoisted(() => ({ submitted: { current: false } }));+vi.mock("react", async (importOriginal) => ({+ ...await importOriginal<typeof import("react")>(),+ useRef: () => state.submitted,+}));+vi.mock("react-native", () => ({+ Alert: { alert: vi.fn() }, Pressable: "Pressable", View: "View",+}));+vi.mock("@/components/ui/text", () => ({ Text: "Text" }));+vi.mock("@/lib/i18n", () => ({ useT: () => ({ t: (key: string) => key }) }));+vi.mock("@/data/mutations/issues", () => ({ useCancelTask: vi.fn() }));++const mutation = {+ isPending: false, isPaused: false, isSuccess: false, isError: false,+ mutate: vi.fn(),+};++// Inspect props and invoke callbacks without pretending to render native UI.+function render() {+ const tree = RunCancelButton({ taskId: "task-1", issueId: "issue-1" });+ return { button: tree.props.children[0], error: tree.props.children[1] };+}++function confirm() {+ const buttons = vi.mocked(Alert.alert).mock.lastCall?.[2];+ buttons?.find((button) => button.style === "destructive")?.onPress?.();+}++describe("RunCancelButton wiring", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ state.submitted.current = false;+ Object.assign(mutation, { isPending: false, isPaused: false, isSuccess: false, isError: false });+ vi.mocked(useCancelTask).mockReturnValue(mutation as unknown as ReturnType<typeof useCancelTask>);+ });++ it("confirms the specific run and prevents repeated native callbacks before a rerender", () => {+ const { button } = render();+ expect(useCancelTask).toHaveBeenCalledWith("issue-1");+ expect(button.props.disabled).toBe(false);+ button.props.onPress();+ expect(mutation.mutate).not.toHaveBeenCalled();+ confirm();+ confirm();+ button.props.onPress();+ expect(mutation.mutate).toHaveBeenCalledExactlyOnceWith("task-1", expect.any(Object));+ expect(Alert.alert).toHaveBeenCalledOnce();+ });++ it.each([+ [{ isPending: true }, "cancel.stopping", true],+ [{ isPending: true, isPaused: true }, "cancel.waiting_for_connection", true],+ [{ isSuccess: true }, "cancel.stopping", false],+ ])("shows a disabled waiting state for %j", (flags, label, busy) => {+ Object.assign(mutation, flags);+ const { button, error } = render();+ expect(button.props.disabled).toBe(true);+ expect(button.props.accessibilityLabel).toBe(label);+ expect(button.props.children.props.children).toBe(label);+ expect(button.props.accessibilityState).toEqual({ disabled: true, busy });+ button.props.onPress();+ expect(Alert.alert).not.toHaveBeenCalled();+ expect(error).toBe(null);+ });++ it("shows an actionable failure and allows confirmation again after rejection", () => {+ render().button.props.onPress();+ confirm();+ mutation.mutate.mock.calls[0][1].onError(new Error("denied"));+ mutation.isError = true;+ const { button, error } = render();+ expect(error.props.accessibilityRole).toBe("alert");+ expect(error.props.children).toBe("cancel.failed");+ expect(button.props.disabled).toBe(false);+ button.props.onPress();+ confirm();+ expect(mutation.mutate).toHaveBeenCalledTimes(2);+ });++ it("keeps the native keep-running action free of writes", () => {+ render().button.props.onPress();+ const buttons = vi.mocked(Alert.alert).mock.lastCall?.[2];+ expect(buttons?.find((button) => button.style === "cancel")).toMatchObject({+ text: "cancel.keep_running",+ });+ expect(mutation.mutate).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/components/issue/run-cancel-button.tsx b/apps/mobile/components/issue/run-cancel-button.tsxnew file mode 100644index 0000000000..1e8297f6d8--- /dev/null+++ b/apps/mobile/components/issue/run-cancel-button.tsx@@ -0,0 +1,52 @@+import { useRef } from "react";+import { Alert, Pressable, View } from "react-native";+import { Text } from "@/components/ui/text";+import { useCancelTask } from "@/data/mutations/issues";+import { useT } from "@/lib/i18n";++export function RunCancelButton({ taskId, issueId }: { taskId: string; issueId: string }) {+ const mutation = useCancelTask(issueId);+ const { t } = useT("issues");+ // Native alert callbacks can run before React commits the pending state.+ const submitted = useRef(false);+ const disabled = mutation.isPending || mutation.isSuccess;++ const confirm = () => {+ if (submitted.current || disabled) return;+ submitted.current = true;+ mutation.mutate(taskId, {+ onError: () => { submitted.current = false; },+ });+ };++ const onPress = () => {+ if (submitted.current || disabled) return;+ Alert.alert(t("cancel.title"), t("cancel.message"), [+ { text: t("cancel.keep_running"), style: "cancel" },+ { text: t("cancel.cancel_task"), style: "destructive", onPress: confirm },+ ]);+ };++ const label = mutation.isPaused ? t("cancel.waiting_for_connection")+ : disabled ? t("cancel.stopping") : t("common:actions.cancel");++ return (+ <View className="items-end gap-1 shrink max-w-[50%]">+ <Pressable+ onPress={onPress}+ disabled={disabled}+ accessibilityRole="button"+ accessibilityLabel={label}+ accessibilityState={{ disabled, busy: mutation.isPending }}+ className="px-3 py-1.5 rounded-md bg-secondary active:opacity-70"+ >+ <Text className="text-xs font-medium text-foreground">{label}</Text>+ </Pressable>+ {mutation.isError ? (+ <Text accessibilityRole="alert" className="text-xs text-destructive">+ {t("cancel.failed")}+ </Text>+ ) : null}+ </View>+ );+}diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsxindex 81b9bc64a2..23ecfd0e2c 100644--- a/apps/mobile/components/issue/run-row.tsx+++ b/apps/mobile/components/issue/run-row.tsx@@ -8,14 +8,14 @@* Terminal runs open their persisted execution record. Active rows keep the* cancel affordance and are not links: this route is for historical records.*/-import { Alert, Pressable, View } from "react-native";+import { Pressable, View } from "react-native";import { Ionicons } from "@expo/vector-icons";import { useColorScheme } from "nativewind";import { router } from "expo-router";import type { AgentTask } from "@multica/core/types";import { Text } from "@/components/ui/text";import { ActorAvatar } from "@/components/ui/actor-avatar";-import { useCancelTask } from "@/data/mutations/issues";+import { RunCancelButton } from "./run-cancel-button";import { useActorLookup } from "@/data/use-actor-name";import { runFailureBadgeLabel } from "@/lib/run-failure-badge";import { timeAgo } from "@/lib/time-ago";@@ -68,7 +68,7 @@ export function RunRow({ task, issueId }: Props) {</Text></View></View>- {isActive ? <CancelButton taskId={task.id} issueId={issueId} /> : null}+ {isActive ? <RunCancelButton taskId={task.id} issueId={issueId} /> : null}{isTerminal ? (<Ioniconsname="chevron-forward"@@ -114,44 +114,6 @@ function StatusBadge({ task }: { task: AgentTask }) {return <Text className={`text-xs ${cls}`}>{label}</Text>;}-function CancelButton({- taskId,- issueId,-}: {- taskId: string;- issueId: string;-}) {- const mutation = useCancelTask(issueId);- const { t } = useT("issues");-- const onPress = () => {- Alert.alert(- t("cancel.title"),- t("cancel.message"),- [- { text: t("cancel.keep_running"), style: "cancel" },- {- text: t("cancel.cancel_task"),- style: "destructive",- onPress: () => mutation.mutate(taskId),- },- ],- );- };-- return (- <Pressable- onPress={onPress}- disabled={mutation.isPending}- className="px-3 py-1.5 rounded-md bg-secondary active:opacity-70"- >- <Text className="text-xs font-medium text-foreground">- {t("common:actions.cancel")}- </Text>- </Pressable>- );-}-function fallbackSummary(task: AgentTask,t: (key: string) => string,diff --git a/apps/mobile/data/mutations/issues.test.ts b/apps/mobile/data/mutations/issues.test.tsindex 06dba7dadb..385e229431 100644--- a/apps/mobile/data/mutations/issues.test.ts+++ b/apps/mobile/data/mutations/issues.test.ts@@ -1,16 +1,21 @@-import { QueryClient } from "@tanstack/react-query";+// @vitest-environment node+import { MutationObserver, onlineManager, QueryClient } from "@tanstack/react-query";import { EMPTY_APP_CONFIG } from "@multica/core/api/schemas";import type { AppConfigResponse } from "@multica/core/api/schemas";-import type { Issue, TimelineEntry } from "@multica/core/types";-import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AgentTask, Issue, TimelineEntry } from "@multica/core/types";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { api } from "@/data/api";import { appConfigOptions } from "@/data/queries/billing";import { issueKeys } from "@/data/queries/issue-keys";-import { useDeleteComment } from "./issues";+import { useCancelTask, useDeleteComment } from "./issues";const state = vi.hoisted(() => ({qc: undefined as unknown as QueryClient,+ wsId: "workspace-1",+ observer: undefined as unknown as MutationObserver<unknown, unknown, unknown, unknown>,+ reuseObserver: false,+ result: () => ({} as { isPending: boolean; isPaused: boolean; isSuccess: boolean; isError: boolean }),}));vi.mock("@tanstack/react-query", async (importOriginal) => {@@ -23,14 +28,22 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {useMutation: (options: ConstructorParameters<typeof actual.MutationObserver>[1],) => {- const observer = new actual.MutationObserver(state.qc, options);+ const observer = state.reuseObserver+ ? state.observer+ : new actual.MutationObserver(state.qc, options);+ observer.setOptions(options);+ state.observer = observer;+ state.result = () => observer.getCurrentResult();return { mutateAsync: (variables: unknown) => observer.mutate(variables) };},};});vi.mock("@/data/api", () => ({- api: { deleteComment: vi.fn(async () => undefined) },+ api: {+ deleteComment: vi.fn(async () => undefined),+ cancelTaskById: vi.fn(async () => undefined),+ },}));vi.mock("@/data/auth-store", () => ({ useAuthStore: vi.fn() }));@@ -38,7 +51,7 @@ vi.mock("@/data/auth-store", () => ({ useAuthStore: vi.fn() }));vi.mock("@/data/workspace-store", () => ({useWorkspaceStore: (selector: (s: { currentWorkspaceId: string }) => unknown,- ) => selector({ currentWorkspaceId: "workspace-1" }),+ ) => selector({ currentWorkspaceId: state.wsId }),}));const wsId = "workspace-1";@@ -119,3 +132,111 @@ describe("useDeleteComment", () => {}});});++function deferred() {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+}++const activeKey = issueKeys.activeTasks(wsId, issueId);+const tasksKey = issueKeys.tasks(wsId, issueId);+const run = { id: "task-1", status: "running" } as AgentTask;+const otherRun = { id: "task-2", status: "queued" } as AgentTask;++describe("useCancelTask", () => {+ beforeEach(() => {+ onlineManager.setOnline(true);+ state.wsId = wsId;+ state.reuseObserver = false;+ state.qc = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ state.qc.mount();+ state.qc.setQueryData(activeKey, [run, otherRun]);+ state.qc.setQueryData(tasksKey, [run, otherRun]);+ vi.mocked(api.cancelTaskById).mockReset();+ });++ afterEach(() => {+ onlineManager.setOnline(true);+ state.qc.unmount();+ state.qc.clear();+ state.reuseObserver = false;+ state.wsId = wsId;+ });++ it("keeps the run visible while the API is pending and refreshes both lists after acknowledgement", async () => {+ const request = deferred();+ vi.mocked(api.cancelTaskById).mockReturnValue(request.promise);+ const pending = useCancelTask(issueId).mutateAsync(run.id);+ await vi.waitFor(() => expect(api.cancelTaskById).toHaveBeenCalledWith(run.id));+ const visibleBeforeAcknowledgement = state.qc.getQueryData(activeKey);+ expect(state.result().isPending).toBe(true);+ request.resolve();+ await pending;++ expect(visibleBeforeAcknowledgement).toEqual([run, otherRun]);+ // The cached list changes only when an authoritative refetch/WS update arrives.+ expect(state.qc.getQueryData(activeKey)).toEqual([run, otherRun]);+ expect(state.result().isSuccess).toBe(true);+ expect(state.qc.getQueryState(activeKey)?.isInvalidated).toBe(true);+ expect(state.qc.getQueryState(tasksKey)?.isInvalidated).toBe(true);+ });++ it("exposes rejection without rolling a newer authoritative cache update back", async () => {+ const request = deferred();+ vi.mocked(api.cancelTaskById).mockReturnValue(request.promise);+ const pending = useCancelTask(issueId).mutateAsync(run.id);+ const rejected = expect(pending).rejects.toThrow("Stop rejected");+ await vi.waitFor(() => expect(api.cancelTaskById).toHaveBeenCalledOnce());+ // Another run completes while this request is in flight.+ state.qc.setQueryData(activeKey, [run]);+ request.reject(new Error("Stop rejected"));+ await rejected;++ expect(state.result().isError).toBe(true);+ expect(state.qc.getQueryData(activeKey)).toEqual([run]);+ expect(state.qc.getQueryState(activeKey)?.isInvalidated).toBe(true);+ expect(state.qc.getQueryState(tasksKey)?.isInvalidated).toBe(true);+ });++ it("keeps offline-paused runs visible before any request and resumes on reconnect", async () => {+ onlineManager.setOnline(false);+ vi.mocked(api.cancelTaskById).mockResolvedValue(undefined);+ const pending = useCancelTask(issueId).mutateAsync(run.id);+ await vi.waitFor(() => expect(state.result().isPaused).toBe(true));+ // Let async onMutate finish even though the mutation is already paused.+ await new Promise((resolve) => setTimeout(resolve, 0));+ const visibleWhileOffline = state.qc.getQueryData(activeKey);+ expect(api.cancelTaskById).not.toHaveBeenCalled();+ onlineManager.setOnline(true);+ await pending;++ expect(visibleWhileOffline).toEqual([run, otherRun]);+ expect(api.cancelTaskById).toHaveBeenCalledExactlyOnceWith(run.id);+ expect(state.result().isSuccess).toBe(true);+ });++ it("invalidates only the originating workspace and issue after a workspace switch", async () => {+ const otherWorkspace = issueKeys.activeTasks("workspace-2", issueId);+ const otherIssue = issueKeys.activeTasks(wsId, "issue-2");+ state.qc.setQueryData(otherWorkspace, [otherRun]);+ state.qc.setQueryData(otherIssue, [otherRun]);+ const request = deferred();+ vi.mocked(api.cancelTaskById).mockReturnValue(request.promise);+ const pending = useCancelTask(issueId).mutateAsync(run.id);+ await vi.waitFor(() => expect(api.cancelTaskById).toHaveBeenCalledOnce());+ state.wsId = "workspace-2";+ // A real mounted hook updates its pending mutation options on rerender.+ state.reuseObserver = true;+ useCancelTask(issueId);+ request.resolve();+ await pending;++ expect(state.qc.getQueryState(activeKey)?.isInvalidated).toBe(true);+ for (const key of [otherWorkspace, otherIssue]) {+ expect(state.qc.getQueryData(key)).toEqual([otherRun]);+ expect(state.qc.getQueryState(key)?.isInvalidated).toBe(false);+ }+ });+});diff --git a/apps/mobile/data/mutations/issues.ts b/apps/mobile/data/mutations/issues.tsindex 795c5109aa..5e12aaaaff 100644--- a/apps/mobile/data/mutations/issues.ts+++ b/apps/mobile/data/mutations/issues.ts@@ -15,7 +15,6 @@*/import { useMutation, useQueryClient } from "@tanstack/react-query";import type {- AgentTask,CreateIssueRequest,Issue,IssueReaction,@@ -695,13 +694,6 @@ export function useCreateIssue() {});}-/**- * Cancel an in-flight agent task. Optimistically removes the task from the- * active-tasks cache so the RunRow disappears immediately; the WS- * `task:cancelled` event then invalidates both task queries (see- * `use-issue-realtime.ts`) so the task reappears in the past list with the- * authoritative server state. On error we restore the snapshot.- *//*** Delete an issue. Mirrors `useDeleteProject` (mutations/projects.ts:103-128)* but the cache surface is wider:@@ -772,21 +764,15 @@ export function useCancelTask(issueId: string) {return useMutation({mutationFn: (taskId: string) => api.cancelTaskById(taskId),- onMutate: async (taskId) => {- const activeKey = issueKeys.activeTasks(wsId, issueId);- await qc.cancelQueries({ queryKey: activeKey });- const prev = qc.getQueryData<AgentTask[]>(activeKey);- qc.setQueryData<AgentTask[]>(activeKey, (old) =>- old ? old.filter((t) => t.id !== taskId) : old,- );- return { prev, activeKey };- },- onError: (_err, _taskId, ctx) => {- if (ctx?.prev) qc.setQueryData(ctx.activeKey, ctx.prev);- },- onSettled: () => {- qc.invalidateQueries({ queryKey: issueKeys.activeTasks(wsId, issueId) });- qc.invalidateQueries({ queryKey: issueKeys.tasks(wsId, issueId) });+ // Pending mutation options can change when the workspace changes.+ onMutate: () => ({+ activeKey: issueKeys.activeTasks(wsId, issueId),+ tasksKey: issueKeys.tasks(wsId, issueId),+ }),+ onSettled: (_data, _err, _taskId, context) => {+ if (!context) return;+ qc.invalidateQueries({ queryKey: context.activeKey });+ qc.invalidateQueries({ queryKey: context.tasksKey });},});}diff --git a/apps/mobile/locales/en/issues.json b/apps/mobile/locales/en/issues.jsonindex 81cf811823..cda2b6e4e6 100644--- a/apps/mobile/locales/en/issues.json+++ b/apps/mobile/locales/en/issues.json@@ -148,7 +148,10 @@"title": "Cancel run?","message": "The agent will stop after the current step.","keep_running": "Keep running",- "cancel_task": "Cancel run"+ "cancel_task": "Cancel run",+ "waiting_for_connection": "Waiting for connection...",+ "stopping": "Stopping...",+ "failed": "Couldn’t stop the run. Try again."},"form": {"discard_title": "Discard changes?",diff --git a/apps/mobile/locales/zh-Hans/issues.json b/apps/mobile/locales/zh-Hans/issues.jsonindex 950e793557..3be529a3d6 100644--- a/apps/mobile/locales/zh-Hans/issues.json+++ b/apps/mobile/locales/zh-Hans/issues.json@@ -146,7 +146,10 @@"title": "取消运行?","message": "智能体会在当前步骤结束后停止。","keep_running": "继续运行",- "cancel_task": "取消运行"+ "cancel_task": "取消运行",+ "waiting_for_connection": "等待网络连接...",+ "stopping": "正在停止...",+ "failed": "无法停止运行,请重试。"},"form": {"discard_title": "放弃修改?",diff --git a/apps/mobile/locales/zh-Hant/issues.json b/apps/mobile/locales/zh-Hant/issues.jsonindex aa56e8d3f9..a05df2e314 100644--- a/apps/mobile/locales/zh-Hant/issues.json+++ b/apps/mobile/locales/zh-Hant/issues.json@@ -146,7 +146,10 @@"title": "取消執行?","message": "智慧體會在當前步驟結束後停止。","keep_running": "繼續執行",- "cancel_task": "取消執行"+ "cancel_task": "取消執行",+ "waiting_for_connection": "等待網路連線...",+ "stopping": "正在停止...",+ "failed": "無法停止執行,請重試。"},"form": {"discard_title": "放棄修改?",diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.tsindex 41d2aabd74..40824ed8a6 100644--- a/apps/mobile/vitest.config.ts+++ b/apps/mobile/vitest.config.ts@@ -13,6 +13,8 @@ import path from "node:path";//// Co-located test files (foo.ts + foo.test.ts) match how the rest of the// monorepo organises vitest suites.+// The run cancel button has headless callback/prop tests with native modules+// mocked; these do not verify native rendering.// App configuration tests also run here to cover native prebuild options// across environment variants without loading React Native.export default defineConfig({@@ -24,7 +26,12 @@ export default defineConfig({test: {environment: "node",globals: true,- include: ["app.config.test.ts", "lib/**/*.test.ts", "data/**/*.test.ts"],+ include: [+ "app.config.test.ts",+ "lib/**/*.test.ts",+ "data/**/*.test.ts",+ "components/issue/run-cancel-button.test.ts",+ ],passWithNoTests: true,},});