Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 速度面板渲染到全窗口浮层,轻点判断核对终点与时长
Dashaa1d298b36f9
diff --git a/apps/mobile/src/__tests__/outsideTap.test.tsx b/apps/mobile/src/__tests__/outsideTap.test.tsxindex 7e54300ac3..9b025987c9 100644--- a/apps/mobile/src/__tests__/outsideTap.test.tsx+++ b/apps/mobile/src/__tests__/outsideTap.test.tsx@@ -2,19 +2,29 @@import { act, createElement } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { OutsideTapProvider, useOutsideTap } from "@/platform/OutsideTap";+import {+ OutsideTapProvider,+ RootOverlay,+ useOutsideTap,+} from "@/platform/OutsideTap";const harness = vi.hoisted(() => ({root: {} as Record<string, (event: any) => void>,}));vi.mock("react-native", () => ({+ StyleSheet: { absoluteFill: {} },View: (props: any) => {- harness.root = props;- return createElement("div", {}, props.children);+ if (props.onTouchStart) harness.root = props;+ return createElement(+ "div",+ { "data-layer": props.pointerEvents === "box-none" ? "" : undefined },+ props.children,+ );},}));let root: Root;+let host: HTMLDivElement;const onOutsideTap = vi.fn();function Floating({ active }: { active: boolean }) {// The floating card occupies x/y 100..200.@@ -25,16 +35,18 @@ function Floating({ active }: { active: boolean }) {);return null;}-const render = (active = true) =>+const render = (active = true, overlay?: string) =>act(async () =>root.render(createElement(OutsideTapProvider,null,createElement(Floating, { active }),+ overlay ? createElement(RootOverlay, null, overlay) : null,),),);+let now = 0;const touch = (name: "onTouchStart" | "onTouchMove" | "onTouchEnd" | "onTouchCancel",pageX = 0,@@ -42,17 +54,24 @@ const touch = (fingers = name === "onTouchEnd" || name === "onTouchCancel" ? 0 : 1,) =>harness.root[name]({- nativeEvent: { pageX, pageY, touches: Array.from({ length: fingers }) },+ nativeEvent: {+ pageX,+ pageY,+ timestamp: now,+ touches: Array.from({ length: fingers }),+ },});const tap = (x: number, y: number) => {touch("onTouchStart", x, y);+ now += 80;touch("onTouchEnd", x, y);};beforeEach(() => {Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });onOutsideTap.mockReset();- root = createRoot(document.createElement("div"));+ host = document.createElement("div");+ root = createRoot(host);});afterEach(async () => {await act(async () => root.unmount());@@ -66,12 +85,15 @@ it("reports taps outside the floating area and ignores taps inside it", async ()expect(onOutsideTap).toHaveBeenCalledTimes(1);});-it("lets scrolls, drags, pinches and cancelled touches pass without closing", async () => {+it("lets scrolls, drags, pinches, long presses and cancelled touches pass without closing", async () => {await render();// Scroll the conversation underneath.touch("onTouchStart", 20, 400);touch("onTouchMove", 20, 300);touch("onTouchEnd", 20, 300);+ // A scroll container that reports only the end point.+ touch("onTouchStart", 20, 400);+ touch("onTouchEnd", 20, 320);// A native scroll view taking over the gesture.touch("onTouchStart", 20, 400);touch("onTouchCancel");@@ -81,6 +103,10 @@ it("lets scrolls, drags, pinches and cancelled touches pass without closing", astouch("onTouchStart", 60, 400, 2);touch("onTouchEnd", 60, 400, 1);touch("onTouchEnd", 20, 400);+ // Long press on a message.+ touch("onTouchStart", 20, 400);+ now += 600;+ touch("onTouchEnd", 20, 400);expect(onOutsideTap).not.toHaveBeenCalled();// Small jitter still counts as a tap.touch("onTouchStart", 20, 400);@@ -97,3 +123,13 @@ it("stops listening once the floating area closes", async () => {tap(20, 400);expect(onOutsideTap).not.toHaveBeenCalled();});++it("renders overlays in the window-sized layer and removes them on unmount", async () => {+ const layer = () => host.querySelector("[data-layer]")!.textContent;+ await render(false, "card");+ expect(layer()).toBe("card");+ await render(false, "updated card");+ expect(layer()).toBe("updated card");+ await render(false);+ expect(layer()).toBe("");+});diff --git a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsxindex 709799c9f6..d7ba33f375 100644--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx@@ -12,10 +12,16 @@ import { resolve } from "node:path";import ts from "typescript";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { clearRateHistoryCache, loadCachedRateHistory } from "@cindy/maker-shared/usage-format";+import {+ clearRateHistoryCache,+ loadCachedRateHistory,+} from "@cindy/maker-shared/usage-format";import { useRunningTokenRateHistory } from "../session/useRunningTokenRateHistory";import { RunningTokenRatePopover } from "@/session/RunningTokenRatePopover";-import { keyboardControlRegion, type ReservedRegion } from "@/platform/windowGeometry";+import {+ keyboardControlRegion,+ type ReservedRegion,+} from "@/platform/windowGeometry";const harness = vi.hoisted(() => ({viewport: { x: 0, y: 0, width: 320, height: 800 },@@ -66,6 +72,7 @@ vi.mock("react-native", () => {vi.mock("@/platform/OutsideTap", async () => {const { useEffect } = await import("react");return {+ RootOverlay: ({ children }: any) => children,useOutsideTap: (active: boolean,contains: (x: number, y: number) => boolean,@@ -146,11 +153,16 @@ const statusSource = route.statements.find(node.name?.text === "ComposerActivityStatus",)!;const rateSource = route.statements.find(- (node) => ts.isFunctionDeclaration(node) && node.name?.text === "formatComposerActivityRateValue",+ (node) =>+ ts.isFunctionDeclaration(node) &&+ node.name?.text === "formatComposerActivityRateValue",)!;-const compiledStatus = ts.transpileModule(statusSource.getText(route) + "\n" + rateSource.getText(route), {- compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },-}).outputText;+const compiledStatus = ts.transpileModule(+ statusSource.getText(route) + "\n" + rateSource.getText(route),+ {+ compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },+ },+).outputText;const bindings = {React: { createElement, Fragment: "div" },useEffect,@@ -176,32 +188,70 @@ const ActivityStatus = new Function(`${compiledStatus}; return ComposerActivityStatus;`,)(...Object.values(bindings));-it.each(["onPress", "onLongPress"])("records the first completed interval before enabling %s, without sampling inactive gaps", async (open) => {- const renderStatus = (props = {}) => act(async () => root.render(createElement(ActivityStatus, {- ...base, visible: true, tokenUsage: 100, sideTaskRunning: false,- reconnectAttempt: null, ...props,- })));- await renderStatus();- expect(host.querySelector('[data-testid="session.tokenRate.trigger"]')).toBeNull();- // The only paired report may arrive at completion, after startedAt clears.- await renderStatus({ startedAt: null, outputTokens: 100, generationDurationMs: 1000 });- await gesture("onPressIn");- await gesture(open);- expect(card()!.textContent).toContain("100 tok/s");- expect(loadCachedRateHistory(base.sessionKey)?.samples.map(s => s.rate)).toEqual([100]);- for (const inactive of [{ sideTaskRunning: true }, { reconnectAttempt: { attempt: 1, maxAttempts: 3 } }, { generationReliable: false }]) {- await renderStatus({ outputTokens: 500, generationDurationMs: 2000, ...inactive });- expect(card()).toBeNull();- await renderStatus({ outputTokens: 600, generationDurationMs: 3000 });- expect(card()).toBeNull();- expect(loadCachedRateHistory(base.sessionKey)?.samples.map(s => s.rate)).toEqual([100]);- }- await renderStatus({ outputTokens: 650, generationDurationMs: 4000 });- expect(loadCachedRateHistory(base.sessionKey)?.samples.map(s => s.rate)).toEqual([100, 50]);- await renderStatus({ sessionKey: "another-task" });- await renderStatus({ sessionKey: "another-task", outputTokens: 20, generationDurationMs: 1000 });- expect(loadCachedRateHistory("another-task")?.samples.map(s => s.rate)).toEqual([20]);-});+it.each(["onPress", "onLongPress"])(+ "records the first completed interval before enabling %s, without sampling inactive gaps",+ async (open) => {+ const renderStatus = (props = {}) =>+ act(async () =>+ root.render(+ createElement(ActivityStatus, {+ ...base,+ visible: true,+ tokenUsage: 100,+ sideTaskRunning: false,+ reconnectAttempt: null,+ ...props,+ }),+ ),+ );+ await renderStatus();+ expect(+ host.querySelector('[data-testid="session.tokenRate.trigger"]'),+ ).toBeNull();+ // The only paired report may arrive at completion, after startedAt clears.+ await renderStatus({+ startedAt: null,+ outputTokens: 100,+ generationDurationMs: 1000,+ });+ await gesture("onPressIn");+ await gesture(open);+ expect(card()!.textContent).toContain("100 tok/s");+ expect(+ loadCachedRateHistory(base.sessionKey)?.samples.map((s) => s.rate),+ ).toEqual([100]);+ for (const inactive of [+ { sideTaskRunning: true },+ { reconnectAttempt: { attempt: 1, maxAttempts: 3 } },+ { generationReliable: false },+ ]) {+ await renderStatus({+ outputTokens: 500,+ generationDurationMs: 2000,+ ...inactive,+ });+ expect(card()).toBeNull();+ await renderStatus({ outputTokens: 600, generationDurationMs: 3000 });+ expect(card()).toBeNull();+ expect(+ loadCachedRateHistory(base.sessionKey)?.samples.map((s) => s.rate),+ ).toEqual([100]);+ }+ await renderStatus({ outputTokens: 650, generationDurationMs: 4000 });+ expect(+ loadCachedRateHistory(base.sessionKey)?.samples.map((s) => s.rate),+ ).toEqual([100, 50]);+ await renderStatus({ sessionKey: "another-task" });+ await renderStatus({+ sessionKey: "another-task",+ outputTokens: 20,+ generationDurationMs: 1000,+ });+ expect(+ loadCachedRateHistory("another-task")?.samples.map((s) => s.rate),+ ).toEqual([20]);+ },+);it.each(["onPress", "onLongPress"])("removes the %s rate panel whenever rate metadata becomes unavailable, then restores a closed trigger",@@ -244,7 +294,10 @@ it.each(["onPress", "onLongPress"])().toBeNull();if (!("visible" in inactive)) {expect(host.textContent).toContain("1s");- if (!("sideTaskRunning" in inactive) && !("reconnectAttempt" in inactive)) {+ if (+ !("sideTaskRunning" in inactive) &&+ !("reconnectAttempt" in inactive)+ ) {expect(host.textContent).toContain("session.screen.tokenCount");}}@@ -308,8 +361,8 @@ it("floats without a backdrop and dismisses only on taps outside the card and trharness.card.onLayout({ nativeEvent: { layout: { height: 120 } } }),);const style = Object.assign({}, ...(harness.card as any).style);- const cardX = style.left + harness.anchor.x;- const cardY = style.top + harness.anchor.y;+ const cardX = style.left;+ const cardY = style.top;const tap = harness.outsideTap!;// Taps on the card or its trigger keep it open.expect(tap.contains(cardX + 10, cardY + 10)).toBe(true);@@ -371,8 +424,8 @@ it.each(["onPress", "onLongPress"])(harness.card.onLayout({ nativeEvent: { layout: { height } } }),);const style = Object.assign({}, ...(harness.card as any).style);- const x = style.left + harness.anchor.x;- const top = style.top + y;+ const x = style.left;+ const top = style.top;expect(x).toBeGreaterThanOrEqual(harness.insets.left);expect(x + style.width).toBeLessThanOrEqual(800 - harness.insets.right);expect(top).toBeGreaterThanOrEqual(harness.insets.top);@@ -385,37 +438,70 @@ it.each(["onPress", "onLongPress"])(},);-it.each(["onPress", "onLongPress"])("keeps %s in the composer's fold/occlusion region and closes on region changes", async (open) => {- const scenarios: { regions: ReservedRegion[]; keyboard: number }[] = [- { regions: [{ kind: "division", x: 0, y: 380, width: 800, height: 40 }], keyboard: 0 },- { regions: [{ kind: "division", x: 0, y: 380, width: 800, height: 40 }], keyboard: 420 },- { regions: [{ kind: "division", x: 380, y: 0, width: 40, height: 800 }], keyboard: 0 },- { regions: [{ kind: "occlusion", x: 200, y: 0, width: 400, height: 100 }], keyboard: 0 },- ];- harness.window = { width: 800, height: 800 };- harness.viewport = { x: 0, y: 0, ...harness.window };- for (const [index, scenario] of scenarios.entries()) {- const region = keyboardControlRegion({ ...harness.window, insets: harness.insets,- regularWidth: true, regularHeight: true, barEdge: "none", reservedRegionsSupported: true,- regions: scenario.regions }, scenario.keyboard);- harness.anchor = { x: region.x + region.width - 80, y: region.y + 30, width: 80 };- await render({ key: String(index), availableRegion: region });- await gesture("onPressIn");- await gesture(open);- let style = Object.assign({}, ...(harness.card as any).style);- const height = style.maxHeight;- await act(async () => harness.card.onLayout({ nativeEvent: { layout: { height } } }));- style = Object.assign({}, ...(harness.card as any).style);- const x = style.left + harness.anchor.x;- const y = style.top + harness.anchor.y;- expect(x).toBeGreaterThanOrEqual(region.x);- expect(y).toBeGreaterThanOrEqual(region.y);- expect(x + style.width).toBeLessThanOrEqual(region.x + region.width);- expect(y + height).toBeLessThanOrEqual(region.y + region.height);- await render({ key: String(index), availableRegion: { ...region, height: region.height - 20 } });- expect(card()).toBeNull();- }-});+it.each(["onPress", "onLongPress"])(+ "keeps %s in the composer's fold/occlusion region and closes on region changes",+ async (open) => {+ const scenarios: { regions: ReservedRegion[]; keyboard: number }[] = [+ {+ regions: [{ kind: "division", x: 0, y: 380, width: 800, height: 40 }],+ keyboard: 0,+ },+ {+ regions: [{ kind: "division", x: 0, y: 380, width: 800, height: 40 }],+ keyboard: 420,+ },+ {+ regions: [{ kind: "division", x: 380, y: 0, width: 40, height: 800 }],+ keyboard: 0,+ },+ {+ regions: [{ kind: "occlusion", x: 200, y: 0, width: 400, height: 100 }],+ keyboard: 0,+ },+ ];+ harness.window = { width: 800, height: 800 };+ harness.viewport = { x: 0, y: 0, ...harness.window };+ for (const [index, scenario] of scenarios.entries()) {+ const region = keyboardControlRegion(+ {+ ...harness.window,+ insets: harness.insets,+ regularWidth: true,+ regularHeight: true,+ barEdge: "none",+ reservedRegionsSupported: true,+ regions: scenario.regions,+ },+ scenario.keyboard,+ );+ harness.anchor = {+ x: region.x + region.width - 80,+ y: region.y + 30,+ width: 80,+ };+ await render({ key: String(index), availableRegion: region });+ await gesture("onPressIn");+ await gesture(open);+ let style = Object.assign({}, ...(harness.card as any).style);+ const height = style.maxHeight;+ await act(async () =>+ harness.card.onLayout({ nativeEvent: { layout: { height } } }),+ );+ style = Object.assign({}, ...(harness.card as any).style);+ const x = style.left;+ const y = style.top;+ expect(x).toBeGreaterThanOrEqual(region.x);+ expect(y).toBeGreaterThanOrEqual(region.y);+ expect(x + style.width).toBeLessThanOrEqual(region.x + region.width);+ expect(y + height).toBeLessThanOrEqual(region.y + region.height);+ await render({+ key: String(index),+ availableRegion: { ...region, height: region.height - 20 },+ });+ expect(card()).toBeNull();+ }+ },+);it("uses paired generation samples, expires recent speed, and isolates a different task", async () => {vi.useFakeTimers();diff --git a/apps/mobile/src/platform/OutsideTap.tsx b/apps/mobile/src/platform/OutsideTap.tsxindex bbe1997654..884b6bbc9f 100644--- a/apps/mobile/src/platform/OutsideTap.tsx+++ b/apps/mobile/src/platform/OutsideTap.tsx@@ -1,11 +1,13 @@import {createContext,+ Fragment,useContext,useEffect,useRef,+ useState,type ReactNode,} from "react";-import { View, type GestureResponderEvent } from "react-native";+import { StyleSheet, View, type GestureResponderEvent } from "react-native";type OutsideTapListener = {/** Window coordinates, same space as `measureInWindow` and touch pageX/pageY. */@@ -14,65 +16,124 @@ type OutsideTapListener = {};type Subscribe = (listener: OutsideTapListener) => () => void;+type SetOverlay = (id: number, node: ReactNode | null) => void;const OutsideTapContext = createContext<Subscribe>(() => () => {});+const OverlayContext = createContext<SetOverlay | null>(null);/** Movement beyond this is a drag or scroll, not a tap. */export const OUTSIDE_TAP_SLOP = 8;+/** Holding longer than this is a long press (Pressable's default), not a tap. */+export const OUTSIDE_TAP_MAX_MS = 500;++let nextOverlayId = 0;/*** Observes raw touches without claiming the responder, so floating panels can* close on an outside tap while everything underneath keeps scrolling normally.+ * It also hosts a window-sized, touch-transparent layer for those panels, so a+ * panel is always inside a hit-testable parent on every platform.*/export function OutsideTapProvider({ children }: { children: ReactNode }) {const listeners = useRef(new Set<OutsideTapListener>());- const touch = useRef<{ x: number; y: number; moved: boolean } | null>(null);+ const touch = useRef<{+ x: number;+ y: number;+ at: number;+ moved: boolean;+ } | null>(null);const subscribe = useRef<Subscribe>((listener) => {listeners.current.add(listener);return () => listeners.current.delete(listener);}).current;+ const [overlays, setOverlays] = useState(() => new Map<number, ReactNode>());+ const setOverlay = useRef<SetOverlay>((id, node) =>+ setOverlays((previous) => {+ if (node === null && !previous.has(id)) return previous;+ const next = new Map(previous);+ if (node === null) next.delete(id);+ else next.set(id, node);+ return next;+ }),+ ).current;+ const movedFrom = (+ start: { x: number; y: number },+ event: GestureResponderEvent,+ ) =>+ Math.hypot(+ event.nativeEvent.pageX - start.x,+ event.nativeEvent.pageY - start.y,+ ) > OUTSIDE_TAP_SLOP;return (<OutsideTapContext.Provider value={subscribe}>- <View- style={{ flex: 1 }}- onTouchStart={(event: GestureResponderEvent) => {- const { pageX, pageY, touches } = event.nativeEvent;- // A second finger turns the gesture into a pinch; never a tap.- if (touches.length > 1 && touch.current) touch.current.moved = true;- else- touch.current = { x: pageX, y: pageY, moved: touches.length > 1 };- }}- onTouchMove={(event: GestureResponderEvent) => {- const start = touch.current;- if (- start &&- Math.hypot(- event.nativeEvent.pageX - start.x,- event.nativeEvent.pageY - start.y,- ) > OUTSIDE_TAP_SLOP- )- start.moved = true;- }}- onTouchEnd={(event: GestureResponderEvent) => {- if (event.nativeEvent.touches.length > 0) return;- const start = touch.current;- touch.current = null;- if (!start || start.moved) return;- for (const listener of [...listeners.current]) {- if (!listener.contains(start.x, start.y)) listener.onOutsideTap();- }- }}- // Native scroll views cancel JS touches when they take over the gesture.- onTouchCancel={() => {- touch.current = null;- }}- >- {children}- </View>+ <OverlayContext.Provider value={setOverlay}>+ <View+ style={{ flex: 1 }}+ onTouchStart={(event: GestureResponderEvent) => {+ const { pageX, pageY, touches, timestamp } = event.nativeEvent;+ // A second finger turns the gesture into a pinch; never a tap.+ if (touches.length > 1 && touch.current) touch.current.moved = true;+ else+ touch.current = {+ x: pageX,+ y: pageY,+ at: timestamp,+ moved: touches.length > 1,+ };+ }}+ onTouchMove={(event: GestureResponderEvent) => {+ const start = touch.current;+ if (start && movedFrom(start, event)) start.moved = true;+ }}+ onTouchEnd={(event: GestureResponderEvent) => {+ if (event.nativeEvent.touches.length > 0) return;+ const start = touch.current;+ touch.current = null;+ // Some scroll containers skip move events, so the end point is+ // checked as well.+ if (+ !start ||+ start.moved ||+ movedFrom(start, event) ||+ event.nativeEvent.timestamp - start.at > OUTSIDE_TAP_MAX_MS+ )+ return;+ for (const listener of [...listeners.current]) {+ if (!listener.contains(start.x, start.y)) listener.onOutsideTap();+ }+ }}+ // Native scroll views cancel JS touches when they take over the gesture.+ onTouchCancel={() => {+ touch.current = null;+ }}+ >+ {children}+ <View pointerEvents="box-none" style={StyleSheet.absoluteFill}>+ {[...overlays].map(([id, node]) => (+ <Fragment key={id}>{node}</Fragment>+ ))}+ </View>+ </View>+ </OverlayContext.Provider></OutsideTapContext.Provider>);}+/**+ * Renders `children` in the window-sized layer above the app, positioned in+ * window coordinates. Content must not depend on context below the provider.+ */+export function RootOverlay({ children }: { children: ReactNode }) {+ const setOverlay = useContext(OverlayContext);+ const id = useRef(0);+ if (!id.current) id.current = ++nextOverlayId;+ useEffect(() => {+ setOverlay?.(id.current, children);+ }, [setOverlay, children]);+ useEffect(() => () => setOverlay?.(id.current, null), [setOverlay]);+ return null;+}+/** While active, calls `onOutsideTap` for taps that start outside `contains`. */export function useOutsideTap(active: boolean,diff --git a/apps/mobile/src/session/RunningTokenRatePopover.tsx b/apps/mobile/src/session/RunningTokenRatePopover.tsxindex 39ea5aa799..d0f3a6b6f4 100644--- a/apps/mobile/src/session/RunningTokenRatePopover.tsx+++ b/apps/mobile/src/session/RunningTokenRatePopover.tsx@@ -28,7 +28,7 @@ import {typeScale,} from "@/theme/tokens";import { usePaneViewport } from "@/platform/AdaptiveWindowContext";-import { useOutsideTap } from "@/platform/OutsideTap";+import { RootOverlay, useOutsideTap } from "@/platform/OutsideTap";import { useSafeAreaInsets } from "react-native-safe-area-context";import type { LayoutRect } from "@/platform/windowGeometry";@@ -246,8 +246,8 @@ export function RunningTokenRatePopover({{width: cardWidth,maxHeight: maxCardHeight,- left: cardLeft - anchor.x,- top: cardTop - anchor.y,+ left: cardLeft,+ top: cardTop,opacity: cardHeight > 0 ? 1 : 0,},]}@@ -378,7 +378,9 @@ export function RunningTokenRatePopover({>{children}</Pressable>- {mode !== "closed" && card}+ {/* A window-sized host keeps the card hit-testable on Android, where+ touches outside a parent's bounds never reach its children. */}+ {mode !== "closed" && <RootOverlay>{card}</RootOverlay>}</View>);}