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): 统一验证码复制与清理的队列和凭据归属

Dashb6782a9639e6
diff --git a/apps/mobile/src/__tests__/copiedCodeClipboard.test.ts b/apps/mobile/src/__tests__/copiedCodeClipboard.test.ts
index e789a259af..e14ff690d1 100644
--- a/apps/mobile/src/__tests__/copiedCodeClipboard.test.ts
+++ b/apps/mobile/src/__tests__/copiedCodeClipboard.test.ts
@@ -6,6 +6,13 @@ const h = vi.hoisted(() => ({
count: 0,
// Simulates another app writing between our write and the next version read.
interleave: false,
+ version: vi.fn(async () => String(h.count)),
+ sync: vi.fn(async (json: string, version: string) => {
+ if (String(h.count) !== version) throw new Error("CLIPBOARD_CHANGED");
+ h.text = JSON.parse(json).text;
+ h.count++;
+ return String(h.count);
+ }),
getString: vi.fn(async () => h.text),
setString: vi.fn(async (value: string) => {
h.text = value;
@@ -31,53 +38,51 @@ vi.mock("expo-clipboard", () => ({
}));
vi.mock("../../modules/cindy-remote-presentation/src", () => ({
remotePresentation: {
- clipboardVersion: async () => String(h.count),
- syncClipboard: async (json: string, version: string) => {
- if (String(h.count) !== version) throw new Error("CLIPBOARD_CHANGED");
- h.text = JSON.parse(json).text;
- h.count++;
- return String(h.count);
- },
+ clipboardVersion: h.version,
+ syncClipboard: h.sync,
},
}));
-import { clearCopiedCode, copyCode } from "@/plugins/copiedCodeClipboard";
+import { createCopiedCodeClipboard } from "@/plugins/copiedCodeClipboard";
+
+let clipboard: ReturnType<typeof createCopiedCodeClipboard>;
beforeEach(() => {
vi.clearAllMocks();
Object.assign(h, { os: "ios", text: "before", count: 5, interleave: false });
+ clipboard = createCopiedCodeClipboard();
});
it("clears its own iOS write by change count without reading the clipboard", async () => {
- const copied = await copyCode("CODE-1");
+ const copied = await clipboard.copy("CODE-1");
expect(copied).toEqual({ code: "CODE-1", version: "6" });
- await clearCopiedCode(copied);
+ await clipboard.clear();
expect(h.text).toBe("");
expect(h.getString).not.toHaveBeenCalled();
});
it("keeps a later iOS copy, including one that lands before the version read", async () => {
- const later = await copyCode("CODE-1");
+ await clipboard.copy("CODE-1");
await h.setString("mine");
- await clearCopiedCode(later);
+ await clipboard.clear();
expect(h.text).toBe("mine");
h.interleave = true;
- const raced = await copyCode("CODE-2");
+ const raced = await clipboard.copy("CODE-2");
expect(raced.version).toBeUndefined();
- await clearCopiedCode(raced);
+ await clipboard.clear();
expect(h.text).toBe("other");
expect(h.getString).not.toHaveBeenCalled();
});
it("keeps the latest iOS copy clearable when the user taps copy twice quickly", async () => {
const [first, second] = await Promise.all([
- copyCode("CODE-1"),
- copyCode("CODE-1"),
+ clipboard.copy("CODE-1"),
+ clipboard.copy("CODE-1"),
]);
expect(first.version).toBe("6");
expect(second.version).toBe("7");
- await clearCopiedCode(second);
+ await clipboard.clear();
expect(h.text).toBe("");
});
@@ -91,11 +96,11 @@ it("settles copies in call order and lets a failed copy keep the earlier token",
h.setString.mockRejectedValueOnce(new Error("write failed"));
let token: { code: string; version?: string } | undefined;
await Promise.allSettled([
- copyCode("CODE-1").then((copied) => {
+ clipboard.copy("CODE-1").then((copied) => {
settled.push("first");
token = copied;
}),
- copyCode("CODE-1").then(
+ clipboard.copy("CODE-1").then(
(copied) => {
token = copied;
},
@@ -104,18 +109,132 @@ it("settles copies in call order and lets a failed copy keep the earlier token",
]);
expect(settled).toEqual(["first", "second-failed"]);
expect(token?.version).toBe("6");
- await clearCopiedCode(token!);
+ await clipboard.clear();
expect(h.text).toBe("");
});
it("compares contents on Android, so returning from the browser still clears the code", async () => {
h.os = "android";
- const copied = await copyCode("CODE-1");
- await clearCopiedCode(copied);
+ await clipboard.copy("CODE-1");
+ await clipboard.clear();
expect(h.text).toBe("");
- const replaced = await copyCode("CODE-2");
+ await clipboard.copy("CODE-2");
await h.setString("mine");
- await clearCopiedCode(replaced);
+ await clipboard.clear();
expect(h.text).toBe("mine");
});
+
+it.each(["before-read", "write", "after-read"])(
+ "releases pending copies when the form ends during %s, including repeated cleanup",
+ async (phase) => {
+ await clipboard.copy("CODE-1");
+ let resume!: () => void;
+ let started!: () => void;
+ const paused = new Promise<void>((resolve) => (started = resolve));
+ const wait = new Promise<void>((resolve) => (resume = resolve));
+ const version = async () => {
+ const value = String(h.count);
+ started();
+ await wait;
+ return value;
+ };
+ if (phase === "before-read") h.version.mockImplementationOnce(version);
+ else if (phase === "after-read") {
+ h.version.mockImplementationOnce(async () => String(h.count));
+ h.version.mockImplementationOnce(version);
+ } else {
+ h.setString.mockImplementationOnce(async (value) => {
+ started();
+ await wait;
+ h.text = value;
+ h.count++;
+ return true;
+ });
+ }
+ const copying = clipboard.copy("CODE-2");
+ await paused;
+ const clearing = clipboard.clear();
+ const clearingAgain = clipboard.clear();
+ resume();
+ const copied = await copying;
+ await Promise.all([clearing, clearingAgain]);
+ expect(copied.version).toBe("7");
+ expect(h.text).toBe("");
+ expect(h.sync).toHaveBeenCalledTimes(1);
+ expect(h.getString).not.toHaveBeenCalled();
+ },
+);
+
+it.each(["ios", "android"])(
+ "waits for %s cleanup before another form writes a new code",
+ async (os) => {
+ h.os = os;
+ await clipboard.copy("CODE-1");
+ let resume!: () => void;
+ let started!: () => void;
+ const paused = new Promise<void>((resolve) => (started = resolve));
+ const wait = new Promise<void>((resolve) => (resume = resolve));
+ if (os === "ios") {
+ h.sync.mockImplementationOnce(async (json, version) => {
+ started();
+ await wait;
+ if (String(h.count) !== version) throw new Error("CLIPBOARD_CHANGED");
+ h.text = JSON.parse(json).text;
+ return String(++h.count);
+ });
+ } else {
+ h.getString.mockImplementationOnce(async () => {
+ const value = h.text;
+ started();
+ await wait;
+ return value;
+ });
+ }
+ const clearing = clipboard.clear();
+ await paused;
+ const newerForm = createCopiedCodeClipboard();
+ const copying = newerForm.copy("CODE-2");
+ resume();
+ await clearing;
+ const copied = await copying;
+ expect(h.text).toBe("CODE-2");
+ if (os === "ios") expect(copied.version).toBe(String(h.count));
+ await newerForm.clear();
+ expect(h.text).toBe("");
+ },
+);
+
+it.each(["ios", "android"])(
+ "clears the first pending %s copy when released immediately",
+ async (os) => {
+ h.os = os;
+ await Promise.all([
+ clipboard.copy("CODE-1"),
+ clipboard.clear(),
+ clipboard.clear(),
+ ]);
+ expect(h.text).toBe("");
+ },
+);
+
+it("does not let an older iOS form clear the newer form's copy of the same code", async () => {
+ const newerForm = createCopiedCodeClipboard();
+ await clipboard.copy("CODE-1");
+ await newerForm.copy("CODE-1");
+ await clipboard.clear();
+ expect(h.text).toBe("CODE-1");
+ await newerForm.clear();
+ expect(h.text).toBe("");
+});
+
+it("continues after cleanup fails and still releases a queued copy", async () => {
+ await clipboard.copy("CODE-1");
+ h.sync.mockRejectedValueOnce(new Error("native unavailable"));
+ await Promise.all([
+ clipboard.clear(),
+ clipboard.copy("CODE-2"),
+ clipboard.clear(),
+ ]);
+ expect(h.text).toBe("");
+});
diff --git a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
index e5aa6cac5a..5b641de2d7 100644
--- a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
+++ b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
@@ -34,11 +34,7 @@ import { type MobilePluginSetupAction } from "./pluginSetupActions";
import type { authenticateMobilePluginOauth } from "./pluginOauthClient";
import { openMobilePluginOauthSession } from "./pluginOauthSession";
import { pluginOauthPlatformCrypto } from "./pluginOauthPlatformCrypto";
-import {
- clearCopiedCode,
- copyCode,
- type CopiedCode,
-} from "./copiedCodeClipboard";
+import { createCopiedCodeClipboard } from "./copiedCodeClipboard";
import { runMobilePluginAuthorization } from "./pluginAuthorizationController";
export default function PluginSetupNativeForm({
@@ -66,8 +62,8 @@ export default function PluginSetupNativeForm({
const owner = useRef(getMobileAuthOwner()).current,
alive = useRef(true),
lock = useRef(false),
- operation = useRef(0),
- copiedCode = useRef<CopiedCode | undefined>(undefined);
+ operation = useRef(0);
+ const [codeClipboard] = useState(createCopiedCodeClipboard);
const live = useRef({ focused, epoch: link.connectionEpoch });
live.current = { focused, epoch: link.connectionEpoch };
const [selected, setSelected] = useState<MobilePluginSetupAction | undefined>(
@@ -81,15 +77,10 @@ export default function PluginSetupNativeForm({
() => () => {
alive.current = false;
operation.current++;
- void releaseCopiedCode();
+ void codeClipboard.clear();
},
[],
);
- const releaseCopiedCode = async () => {
- const copied = copiedCode.current;
- copiedCode.current = undefined;
- if (copied) await clearCopiedCode(copied);
- };
const clear = () => {
setSecret("");
setHost("");
@@ -99,7 +90,7 @@ export default function PluginSetupNativeForm({
clear();
setSelected(undefined);
setBrowser(undefined);
- void releaseCopiedCode();
+ void codeClipboard.clear();
onClosed();
};
useEffect(() => {
@@ -238,7 +229,7 @@ export default function PluginSetupNativeForm({
}
} finally {
client?.dispose();
- void releaseCopiedCode();
+ void codeClipboard.clear();
lock.current = false;
if (alive.current) {
setBusy(false);
@@ -337,15 +328,7 @@ export default function PluginSetupNativeForm({
style={styles.row}
accessibilityRole="button"
onPress={() => {
- const code = browser.code!;
- // Copies settle in order; a failed copy keeps the
- // previous successful token.
- void copyCode(code)
- .then((copied) => {
- copiedCode.current = copied;
- if (!alive.current) void releaseCopiedCode();
- })
- .catch(() => {});
+ void codeClipboard.copy(browser.code!).catch(() => {});
}}
>
<Text style={styles.body}>
diff --git a/apps/mobile/src/plugins/copiedCodeClipboard.ts b/apps/mobile/src/plugins/copiedCodeClipboard.ts
index 9432ad4f28..70355cce29 100644
--- a/apps/mobile/src/plugins/copiedCodeClipboard.ts
+++ b/apps/mobile/src/plugins/copiedCodeClipboard.ts
@@ -2,7 +2,7 @@ import { Platform } from "react-native";
import * as Clipboard from "expo-clipboard";
import { remotePresentation } from "../../modules/cindy-remote-presentation/src";
-export interface CopiedCode {
+interface CopiedCode {
code: string;
/** iOS change count right after our write; absent when ownership is unproven. */
version?: string;
@@ -12,17 +12,31 @@ const iosVersion = () =>
remotePresentation?.clipboardVersion?.().catch(() => undefined) ??
Promise.resolve(undefined);
-// Our own copies run one at a time, so their writes never fall between
-// another copy's version reads.
-let copying: Promise<unknown> = Promise.resolve();
+// All forms share one queue: neither copies nor cleanup may interrupt
+// another operation's version reads or ownership check.
+let pending: Promise<unknown> = Promise.resolve();
-/** Copy a device code and remember enough to clear it later only if it is still ours. */
-export function copyCode(code: string): Promise<CopiedCode> {
- const result = copying.then(() => writeCode(code));
- copying = result.catch(() => {});
+function enqueue<T>(operation: () => Promise<T>): Promise<T> {
+ const result = pending.then(operation);
+ pending = result.catch(() => {});
return result;
}
+/** One form owns its token; releasing it also waits for already requested copies. */
+export function createCopiedCodeClipboard() {
+ let copied: CopiedCode | undefined;
+ return {
+ copy: (code: string) =>
+ enqueue(async () => (copied = await writeCode(code))),
+ clear: () =>
+ enqueue(async () => {
+ const token = copied;
+ copied = undefined;
+ if (token) await clearCopiedCode(token);
+ }),
+ };
+}
+
async function writeCode(code: string): Promise<CopiedCode> {
if (Platform.OS !== "ios") {
await Clipboard.setStringAsync(code);
@@ -40,7 +54,7 @@ async function writeCode(code: string): Promise<CopiedCode> {
}
/** Clear the clipboard only while it still holds the copied code. */
-export async function clearCopiedCode(copied: CopiedCode): Promise<void> {
+async function clearCopiedCode(copied: CopiedCode): Promise<void> {
if (Platform.OS === "ios") {
// Reading the contents would trigger the iOS paste prompt. The native
// write compares the change count and clears in one main-queue step.