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): 稳定列表手势并通过真实入口验证待发送操作

Dash0d4867ed9c5d
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 7851c23d73..c164bb3e14 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -45,7 +45,7 @@ import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { mobileDurableOutbox, durableOutboxDisplayItem, getCurrentMobileOutboxRecords, reconcileMobileOutboxDrafts } from '@/session/mobileDurableOutbox';
import { retainOutboxFile, durableOutboxUploadUri, removeOutboxFiles, outboxAttachmentNeedsLocalBytes } from '@/session/durableOutboxFiles';
-import { isDurableOutboxSettled, isDurableOutboxUnsent, observeDurableOutboxSending, type DurableOutboxRecord } from '@/session/durableOutbox';
+import { isDurableOutboxSettled, observeDurableOutboxSending, type DurableOutboxRecord } from '@/session/durableOutbox';
import { isInFlightDeviceLinkError, isSharedTaskPeer, resolveRemoteText } from '@cindy/device-link';
import { takeRefinementContextTail, truncateRefinementReply } from '@cindy/voice-input-core';
import {
@@ -446,7 +446,7 @@ import {
reconcileOptimisticUserMessages,
type OptimisticUserMessage,
} from '@/session/optimisticUserMessages';
-import type { PendingSendBubbleActions } from '@/session/PendingSendBubble';
+import { usePendingOutboxActions, usePendingSendActions } from '@/session/usePendingSendActions';
import {
acquireQueueEditLock,
commitQueueEdit,
@@ -6067,55 +6067,10 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
return outboxConnectionBlockedNow() || isRemoteSessionMissing(row) || row?.cacheSeeded === true
|| getNewSessionCreationTask(sessionId) !== null;
};
- const findDurableOutboxRecord = useCallback((clientId: string) => getCurrentMobileOutboxRecords().find((r) =>
- r.deviceId === deviceId && r.item.sessionId === sessionId && r.item.clientId === clientId), [deviceId, sessionId]);
- const retryOutboxItem = useCallback((clientId: string) => {
- const record = findDurableOutboxRecord(clientId);
- if (!record || record.state !== 'failed') return;
- if (record.creation && !record.prepared && !record.template) {
- const owner = getMobileAuthOwner();
- void mobileDurableOutbox.update(record, { suspended: true }).then(() => {
- if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) {
- router.push({ pathname: '/sessions/new', params: { recoverySessionId: sessionId, deviceId, deviceName } });
- }
- }).catch((err) => setError(formatRemoteError(err)));
- return;
- }
- setQueueSelectedClientId(null);
- void mobileDurableOutbox.update(record, {
- state: record.prepared ? 'confirming' : 'queued', error: undefined,
- }).catch((err) => setError(formatRemoteError(err)));
- }, [deviceId, deviceName, findDurableOutboxRecord, router, sessionId]);
- const removeOutboxItem = useCallback((clientId: string) => {
- const record = findDurableOutboxRecord(clientId);
- if (!record) return;
- // Until creation succeeds, this row also owns the recovery form for every later message.
- if (record.creation && !record.prepared && !record.template) {
- setError(t('session.outbox.creationRecoveryRequired'));
- return;
- }
- // 删除发送失败的消息不可撤销:先确认(破坏性按钮),确认后才真正移除。
- const confirmRemove = () => {
- setQueueSelectedClientId(null);
- const owner = getMobileAuthOwner();
- const remove = async () => {
- if (isDurableOutboxUnsent(record)) {
- await mobileDurableOutbox.update(record, { state: 'host-owned', cleanupOutcome: 'cancelled', cancelRequested: true, error: undefined });
- } else await mobileDurableOutbox.update(record, { cancelRequested: true, state: 'confirming' });
- };
- void remove().catch((err) => {
- if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) setError(formatRemoteError(err));
- });
- };
- Alert.alert(
- t('session.outbox.deleteConfirmTitle'),
- t('session.outbox.deleteConfirmBody'),
- [
- { text: t('session.common.cancel'), style: 'cancel' },
- { text: t('session.common.delete'), style: 'destructive', onPress: confirmRemove },
- ],
- );
- }, [findDurableOutboxRecord, sessionId, t]);
+ const { findDurableOutboxRecord, retryOutboxItem, removeOutboxItem } = usePendingOutboxActions({
+ deviceId, deviceName, sessionId, router, outboxSessionAliveRef,
+ setError, setQueueSelectedClientId, t,
+ });
const outboxDisplayItems = useMemo(() => outboxItems.map((item) => {
const record = findDurableOutboxRecord(item.clientId);
return {
@@ -7963,34 +7918,11 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
}, [applyComposerDocument, discardQueueEditTransientAttachments, pendingUploads.length,
queueAvailabilityReason, queueBusy, setQueueEditLock, t]);
- /** 放弃排队消息编辑:解锁 + 回收编辑期新增附件 + 恢复进入前的草稿与附件托盘。 */
- const pendingSendActions = useMemo<PendingSendBubbleActions>(
- () => ({
- busy: queueBusy,
- selectedClientId: queueSelectedClientId,
- onSelect: setQueueSelectedClientId,
- onRemove: (clientId: string) => {
- setQueueSelectedClientId(null);
- removeQueueItem(clientId);
- },
- onBeginEdit: (clientId: string) => {
- const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue
- .find((entry) => entry.clientId === clientId);
- if (target) beginQueueEdit(target);
- },
- onSteer: (clientId: string) => {
- const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue
- .find((entry) => entry.clientId === clientId);
- if (!target) return;
- setQueueSelectedClientId(null);
- steerQueueItem(target);
- },
- onMove: moveQueueItem,
- onRetryOutbox: retryOutboxItem,
- onRemoveOutbox: removeOutboxItem,
- }),
- [beginQueueEdit, moveQueueItem, queueBusy, queueSelectedClientId, removeQueueItem, removeOutboxItem, retryOutboxItem, sessionId, steerQueueItem],
- );
+ const pendingSendActions = usePendingSendActions({
+ beginQueueEdit, moveQueueItem, queueBusy, queueSelectedClientId,
+ removeQueueItem, removeOutboxItem, retryOutboxItem, sessionId,
+ setQueueSelectedClientId, steerQueueItem,
+ });
// ⚠️ 临时取证(定位「气泡凭空消失」,定位完成后删):会话页实例身份 + 挂载/卸载。
// settlingDiag 只在两次「首帧」打出 prev=0,之后再没跑过 —— 强烈指向组件被换了实例
diff --git a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
index 9630c70a19..147c574708 100644
--- a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
+++ b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
@@ -9,6 +9,16 @@ import { MessageBodyText } from '@/session/ShareMessageCheckbox';
import { buildQueueRowPresentation, EMPTY_INPUT_PROJECTION } from '@/session/inputProjection';
import type { MobilePendingSendItem } from '@/session/pendingSendItems';
import { collectMobileMessageGalleryImages, lightboxImagesForPayload } from '@/session/messageGallery';
+import { usePendingOutboxActions, usePendingSendActions } from '@/session/usePendingSendActions';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { DurableOutboxRecord } from '@/session/durableOutbox';
+import type { TFunction } from 'i18next';
+
+const outbox = vi.hoisted(() => ({ records: [] as DurableOutboxRecord[], update: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('@/session/mobileDurableOutbox', () => ({
+ getCurrentMobileOutboxRecords: () => outbox.records,
+ mobileDurableOutbox: { update: outbox.update },
+}));
const { handlers, frames, durableThumbs } = vi.hoisted(() => ({
handlers: new Map<string, Record<string, unknown>>(),
@@ -154,6 +164,66 @@ it('lets a real body link consume the pending tap before the frame commits', ()
act(() => host.querySelector<HTMLElement>('[data-testid="link"]')!.click());
flush(); expect(openLink).toHaveBeenCalledOnce(); expect(select).not.toHaveBeenCalled();
});
+
+// #7083 unit regression: the production hooks feed the real bubble. Existing
+// touch tests inject static callbacks, so they cannot catch callback churn or
+// a retry/edit routed to the previous task after a task switch. Minimal input:
+// two tasks with the same client ID, plus an unrelated parent render.
+it('keeps pending actions stable and routes bubble actions to the current task', async () => {
+ outbox.records = ['task-a', 'task-b'].map((sessionId): DurableOutboxRecord => ({
+ version: 1, accountId: 'test', deviceId: 'pc', createdAt: 1, state: 'failed', uploads: [],
+ item: { clientId: 'a', sessionId, text: sessionId, quotesEncoded: false,
+ agentReferences: [], pastedTextRanges: [], slashCommandRanges: [], permissionModeAtSend: 'plan',
+ attachmentSlots: [], slotMeta: [], slotByLocalId: {}, waitingIds: [], failedIds: [],
+ enqueueError: null, phase: 'uploading' },
+ }));
+ const bindings = {
+ deviceId: 'pc', deviceName: 'Computer', router: { push: vi.fn() },
+ outboxSessionAliveRef: { current: 'task-a' }, setError: vi.fn(),
+ setQueueSelectedClientId: select, t: ((key: string) => key) as TFunction,
+ };
+ const renderText = vi.fn(() => <span>pending message</span>);
+ const renderMedia = () => null;
+ const failedItem: MobilePendingSendItem = { ...item, phase: 'failed', actions: null };
+ let actions!: PendingSendBubbleActions;
+ function Screen({ sessionId, queueBusy = false, queued = false }: {
+ sessionId: string; queueBusy?: boolean; queued?: boolean;
+ }) {
+ const { retryOutboxItem, removeOutboxItem } = usePendingOutboxActions({ ...bindings, sessionId });
+ actions = usePendingSendActions({
+ retryOutboxItem, removeOutboxItem, sessionId, queueBusy, queueSelectedClientId: null,
+ setQueueSelectedClientId: select, beginQueueEdit: edit, steerQueueItem: steer,
+ removeQueueItem: remove, moveQueueItem: move,
+ });
+ return <PendingSendBubble item={queued ? item : failedItem} actions={actions}
+ renderText={renderText} renderFile={renderMedia} renderImage={renderMedia} />;
+ }
+ const showScreen = (sessionId = 'task-a', queueBusy = false, queued = false) =>
+ act(() => root.render(<Screen {...{ sessionId, queueBusy, queued }} />));
+ try {
+ showScreen();
+ const initial = actions;
+ for (let n = 0; n < 30; n++) showScreen();
+ expect(actions).toBe(initial);
+ await act(async () => host.querySelector<HTMLElement>('[data-testid="pendingSend.outboxRetry.a"]')!.click());
+ expect(outbox.update).toHaveBeenLastCalledWith(outbox.records[0], expect.objectContaining({ state: 'queued' }));
+ showScreen('task-b');
+ await act(async () => host.querySelector<HTMLElement>('[data-testid="pendingSend.outboxRetry.a"]')!.click());
+ expect(outbox.update).toHaveBeenLastCalledWith(outbox.records[1], expect.objectContaining({ state: 'queued' }));
+ const queued = { clientId: 'a', text: 'new task message', persistedContent: 'new task message',
+ model: 'model', workingDir: '/synthetic', createOpts: {}, chatMessage: { role: 'user' as const } };
+ remoteSessionStore.setInputProjection('task-b', { ...EMPTY_INPUT_PROJECTION, pendingQueue: [queued] });
+ showScreen('task-b', false, true);
+ const menu = handlers.get('pendingSend.queueMenu.a')!;
+ act(() => (menu.onPressAction as (e: { nativeEvent: { event: string } }) => void)({ nativeEvent: { event: 'edit' } }));
+ expect(edit).toHaveBeenLastCalledWith(queued);
+ showScreen('task-b', true, true);
+ expect(actions.busy).toBe(true);
+ } finally {
+ outbox.records = [];
+ remoteSessionStore.clear();
+ }
+});
it.each(['queued', 'uploading', 'sending', 'settling', 'editing', 'failed'] as const)(
'previews a %s image without changing queue selection or cancelling the send', (phase) => {
show({ phase, thumbs: [{ key: 'a-slot-0', uri: 'file:///photo.jpg', ossRef: null,
diff --git a/apps/mobile/src/__tests__/homeAutomationWindow.test.tsx b/apps/mobile/src/__tests__/homeAutomationWindow.test.tsx
index 3f18c69c73..5dfac722bd 100644
--- a/apps/mobile/src/__tests__/homeAutomationWindow.test.tsx
+++ b/apps/mobile/src/__tests__/homeAutomationWindow.test.tsx
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
import { resolve } from 'node:path';
import * as jsxRuntime from 'react/jsx-runtime';
import { act, Children, createContext, forwardRef, Fragment, isValidElement, useContext, useRef, useState, type ReactElement, type ReactNode } from 'react';
@@ -20,6 +21,59 @@ const compiled = ts.transpileModule(declaration.getText(source), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },
}).outputText;
+// Unit regression for #7083: the native drag callback must transfer only its
+// small payload, not the project's task/history tree. Existing window tests
+// count mounted rows but never exercise Babel's actual worklet closure.
+it('keeps task data out of the project drag worklet while preserving drag actions', () => {
+ const projectRow = source.statements.find((node): node is ts.FunctionDeclaration => ts.isFunctionDeclaration(node)
+ && node.name?.text === 'ProjectRow')!;
+ let gesture!: ts.VariableDeclaration;
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'dragGesture') gesture = node;
+ ts.forEachChild(node, visit);
+ }
+ visit(projectRow);
+ const require = createRequire(import.meta.url);
+ const { transformSync } = require('@babel/core');
+ const code = transformSync(`function build(project, onDragStart, onDragMove, onDragEnd) {
+ const kind = 'project', displayTitle = project.title;
+ return ${gesture.initializer!.getText(source)};
+ }`, {
+ filename: __filename, babelrc: false, configFile: false,
+ plugins: [require.resolve('react-native-worklets/plugin')],
+ }).code;
+ const callbacks: Record<string, ((event?: unknown) => void) & { __closure?: object }> = {};
+ const pan: Record<string, (...args: any[]) => unknown> = {};
+ for (const method of ['activateAfterLongPress', 'activeOffsetY', 'failOffsetX', 'onStart', 'onUpdate', 'onFinalize']) {
+ pan[method] = (value: any) => {
+ if (method.startsWith('on')) callbacks[method] = value;
+ return pan;
+ };
+ }
+ const build = new Function('Gesture', 'useMemo', 'runOnJS', `${code}; return build;`)(
+ { Pan: () => pan }, (factory: () => unknown) => factory(), (callback: unknown) => callback,
+ );
+ const start = vi.fn(), move = vi.fn(), finish = vi.fn();
+ const project = { key: 'project', title: 'Project', sessionCount: 1,
+ get sessions(): never { throw new Error('task data crossed into a gesture worklet'); } };
+ build(project, start, move, finish);
+ // Serializable conversion enumerates captured objects, including their
+ // nested fields. A single sentinel task collection catches the old transfer.
+ const visited = new Set<object>();
+ function inspect(value: unknown) {
+ if (!value || typeof value !== 'object' || visited.has(value)) return;
+ visited.add(value);
+ Object.values(value).forEach(inspect);
+ }
+ expect(() => Object.values(callbacks).forEach(callback => inspect(callback.__closure))).not.toThrow();
+ callbacks.onStart({ absoluteY: 140 });
+ callbacks.onUpdate({ absoluteY: 160 });
+ callbacks.onFinalize();
+ expect(start).toHaveBeenCalledWith({ absoluteY: 140, count: 1, key: 'project', title: 'Project' });
+ expect(move).toHaveBeenCalledWith(160);
+ expect(finish).toHaveBeenCalledOnce();
+});
+
function renderChildren(count: number, anchor: number, old = false) {
const now = Date.now();
const items = Array.from({ length: count }, (_, i) => toRemoteSessionListItem({
diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
index a4f47afe63..9d52c328ba 100644
--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
@@ -23,8 +23,8 @@ const SCREEN = 'app/sessions/[sessionId].tsx';
describe('mobile optimistic composer while session is not ready', () => {
it('uses the shared unsent proof to cancel locally before requiring a remote receipt', () => {
- const source = readSource(SCREEN);
- const remove = source.slice(source.indexOf('const removeOutboxItem ='), source.indexOf('const outboxDisplayItems ='));
+ const source = readSource('src/session/usePendingSendActions.ts');
+ const remove = source.slice(source.indexOf('const removeOutboxItem ='), source.indexOf('return { findDurableOutboxRecord'));
expect(remove).toContain('if (isDurableOutboxUnsent(record))');
expect(remove).toContain("cleanupOutcome: 'cancelled'");
expect(remove).toContain("else await mobileDurableOutbox.update(record, { cancelRequested: true, state: 'confirming' })");
diff --git a/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx b/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx
deleted file mode 100644
index a674914dfc..0000000000
--- a/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-// @vitest-environment jsdom
-import React, { act } from 'react';
-import { createRoot } from 'react-dom/client';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
-import { expect, it, vi } from 'vitest';
-import { remoteSessionStore } from '@/session/remoteSessionStore';
-import type { PendingSendBubbleActions } from '@/session/PendingSendBubble';
-
-// Unit regression: execute the page's real callbacks/memo with React. Native
-// transport and composer boundaries are substituted, not the callback bodies.
-const source = ts.createSourceFile('page.tsx', readFileSync(resolve(process.cwd(),
- 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-const names = ['findDurableOutboxRecord', 'retryOutboxItem', 'removeOutboxItem',
- 'steerQueueItem', 'removeQueueItem', 'beginQueueEdit', 'pendingSendActions'];
-const declarations = new Map<string, ts.VariableDeclaration>();
-function visit(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && names.includes(node.name.getText(source))) {
- declarations.set(node.name.getText(source), node);
- }
- ts.forEachChild(node, visit);
-}
-visit(source);
-const code = names.map(name => {
- const node = declarations.get(name);
- if (!node) throw new Error(`Missing production declaration: ${name}`);
- return `const ${node.getText(source)};`;
-}).join('\n');
-
-it('retains actions on unrelated renders, but uses current task and edit guards after changes', async () => {
- Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
- const records = [
- { deviceId: 'pc', state: 'failed', item: { sessionId: 'a', clientId: 'send' } },
- { deviceId: 'pc', state: 'failed', item: { sessionId: 'b', clientId: 'send' } },
- ];
- const setError = vi.fn();
- const update = vi.fn().mockResolvedValue(undefined);
- const bindings = {
- useCallback: React.useCallback, useMemo: React.useMemo, remoteSessionStore,
- deviceId: 'pc', deviceName: 'Computer', router: {},
- getCurrentMobileOutboxRecords: () => records, mobileDurableOutbox: { update },
- setError, formatRemoteError: String, t: (key: string) => key,
- queueSelectedClientId: null, setQueueSelectedClientId: vi.fn(),
- moveQueueItem: vi.fn(), maker: {}, invoke: vi.fn(),
- runQueueAction: vi.fn(), runOptimisticQueueAction: vi.fn(), showTransientNotice: vi.fn(),
- applyComposerDocument: vi.fn(), discardQueueEditTransientAttachments: vi.fn(),
- setQueueEditLock: vi.fn(), queueEditSaveInFlightRef: { current: null },
- };
- const compiled = ts.transpileModule(`return function Probe({ sessionId, queueBusy, pendingUploads, queueAvailabilityReason, capture }) {
- ${code}
- capture(pendingSendActions);
- return null;
- }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const Probe = new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
- const root = createRoot(document.createElement('div'));
- let actions!: PendingSendBubbleActions;
- const capture = (value: PendingSendBubbleActions) => { actions = value; };
- const show = (sessionId = 'a', queueBusy = false, pendingUploads: unknown[] = [], queueAvailabilityReason: string | null = null) =>
- act(() => root.render(<Probe {...{ sessionId, queueBusy, pendingUploads, queueAvailabilityReason, capture }} />));
- remoteSessionStore.clear();
- try {
- show();
- const initial = actions;
- for (let n = 0; n < 30; n += 1) show();
- expect(actions).toBe(initial);
- await act(async () => actions.onRetryOutbox?.('send'));
- expect(update).toHaveBeenLastCalledWith(records[0], expect.objectContaining({ state: 'queued' }));
- show('b');
- await act(async () => actions.onRetryOutbox?.('send'));
- expect(update).toHaveBeenLastCalledWith(records[1], expect.objectContaining({ state: 'queued' }));
- remoteSessionStore.setInputProjection('b', {
- ...remoteSessionStore.getInputProjection('b'),
- pendingQueue: [{ clientId: 'queued', text: 'message', persistedContent: 'message',
- model: 'model', workingDir: '/synthetic', createOpts: {}, chatMessage: { role: 'user' } }],
- });
- show('b', false, [{}]);
- actions.onBeginEdit?.('queued');
- expect(setError).toHaveBeenLastCalledWith('session.screen.attachmentsUploadingBeforeEdit');
- setError.mockClear();
- show('b', true, [{}]);
- expect(actions.busy).toBe(true);
- actions.onBeginEdit?.('queued');
- expect(setError).not.toHaveBeenCalled();
- show('b', false, [{}], 'offline');
- actions.onBeginEdit?.('queued');
- expect(setError).not.toHaveBeenCalled();
- } finally {
- act(() => root.unmount());
- remoteSessionStore.clear();
- Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
- }
-});
diff --git a/apps/mobile/src/__tests__/swipeableProjectHeader.test.tsx b/apps/mobile/src/__tests__/swipeableProjectHeader.test.tsx
index 9129063a52..a6a4399c1d 100644
--- a/apps/mobile/src/__tests__/swipeableProjectHeader.test.tsx
+++ b/apps/mobile/src/__tests__/swipeableProjectHeader.test.tsx
@@ -6,6 +6,7 @@ import { SwipeableProjectHeader } from "@/session/SwipeableProjectHeader";
import { createSwipeRowRegistry } from "@/session/swipeRowRegistry";
const native = vi.hoisted(() => ({
+ width: 400,
props: null as any,
offset: { value: 0 },
close: vi.fn(),
@@ -22,7 +23,7 @@ vi.mock("react-native", async () => {
children,
),
StyleSheet: { create: (value: unknown) => value },
- useWindowDimensions: () => ({ width: 400 }),
+ useWindowDimensions: () => ({ width: native.width }),
};
});
vi.mock("react-native-reanimated", async () => {
@@ -109,6 +110,7 @@ function render(projectKey = "project-a") {
}
beforeEach(() => {
vi.clearAllMocks();
+ native.width = 400;
native.offset.value = 0;
registry = createSwipeRowRegistry();
destination = "home";
@@ -124,6 +126,24 @@ afterEach(() => act(() => root.unmount()));
// The requested side swap moves new-task and its full-swipe trigger to the right
// panel; clicking the revealed left panel must still open tasks/search (unit).
describe("project header navigation and swipe lifecycle", () => {
+ // #7083 unit: repeated parent renders/rotation must retain the native gesture
+ // inputs; full-swipe still uses the latest width and current project action.
+ it("does not re-register gestures on refresh or rotation", () => {
+ render();
+ const initial = native.props;
+ native.width = 800;
+ render("project-b");
+ for (const key of ["onSwipeableOpenStartDrag", "onSwipeableClose", "onSwipeableWillOpen", "hitSlop"]) {
+ expect(native.props[key]).toBe(initial[key]);
+ }
+ native.offset.value = -260;
+ act(() => native.props.onSwipeableWillOpen("left"));
+ expect(destination).toBe("home");
+ native.offset.value = -500;
+ act(() => native.props.onSwipeableWillOpen("left"));
+ expect(destination).toBe("new");
+ expect(registry.closeOpenRow()).toBe(false);
+ });
it.each([
["left", -260, "new"],
["left", -100, "home"],
diff --git a/apps/mobile/src/__tests__/swipeableSessionRowIos.test.tsx b/apps/mobile/src/__tests__/swipeableSessionRowIos.test.tsx
index f1b5ec109f..df2ff148e4 100644
--- a/apps/mobile/src/__tests__/swipeableSessionRowIos.test.tsx
+++ b/apps/mobile/src/__tests__/swipeableSessionRowIos.test.tsx
@@ -7,6 +7,7 @@ import type { RemoteSession } from "@/session/types";
import { SwipeableSessionRow } from "@/session/SwipeableSessionRow.ios";
const runtime = vi.hoisted(() => ({
+ width: 400,
translation: { value: 0 },
props: null as SwipeableProps | null,
reset: vi.fn(),
@@ -31,7 +32,7 @@ vi.mock("react-native", () => ({
</button>
),
StyleSheet: { create: (value: unknown) => value },
- useWindowDimensions: () => ({ width: 400 }),
+ useWindowDimensions: () => ({ width: runtime.width }),
}));
vi.mock("@/platform/gestureHandler", async () => {
const { forwardRef, useImperativeHandle } = await import("react");
@@ -168,6 +169,7 @@ function release(direction: "left" | "right") {
}
beforeEach(() => {
vi.clearAllMocks();
+ runtime.width = 400;
runtime.translation.value = 0;
runtime.styles = [];
runtime.reactions.clear();
@@ -177,6 +179,25 @@ beforeEach(() => {
afterEach(() => act(() => root.unmount()));
describe("iOS swipe runtime contracts (mocked native boundary)", () => {
+ // #7083: refreshed row objects and rotation must not rebuild RNGH's worklet
+ // graph. Existing release tests do not compare the native callback boundary.
+ it("keeps gesture callbacks stable while using the current width and recycled task", () => {
+ render("a");
+ const initial = runtime.props!;
+ render("a");
+ expect(runtime.props!.onSwipeableWillOpen).toBe(initial.onSwipeableWillOpen);
+ runtime.width = 800;
+ render("b");
+ expect(runtime.props!.onSwipeableWillOpen).toBe(initial.onSwipeableWillOpen);
+ expect(runtime.props!.onSwipeableOpenStartDrag).toBe(initial.onSwipeableOpenStartDrag);
+ expect(runtime.props!.onSwipeableClose).toBe(initial.onSwipeableClose);
+ drag(-260);
+ release("left");
+ expect(controls.onArchive).not.toHaveBeenCalled();
+ drag(-500);
+ release("left");
+ expect(controls.onArchive).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: "b" }));
+ });
it.each([
["left", -260, "onArchive"],
["right", 260, "onMarkRead"],
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 43f69a7394..4b13537b04 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -3961,6 +3961,9 @@ function ProjectRow({
const start = onDragStart;
const move = onDragMove;
const finish = onDragEnd;
+ // Worklets serialize captured objects recursively. Capture the two scalar
+ // fields here so registering a drag never copies all project task data.
+ const { key: projectKey, sessionCount } = project;
return Gesture.Pan()
.activateAfterLongPress(380)
.activeOffsetY([-8, 8])
@@ -3968,8 +3971,8 @@ function ProjectRow({
.onStart((event) => {
runOnJS(start)({
absoluteY: event.absoluteY,
- count: project.sessionCount,
- key: project.key,
+ count: sessionCount,
+ key: projectKey,
title: displayTitle,
});
})
diff --git a/apps/mobile/src/session/SwipeableProjectHeader.tsx b/apps/mobile/src/session/SwipeableProjectHeader.tsx
index 94fc47239e..8e84071762 100644
--- a/apps/mobile/src/session/SwipeableProjectHeader.tsx
+++ b/apps/mobile/src/session/SwipeableProjectHeader.tsx
@@ -1,4 +1,4 @@
-import { memo, useCallback, useEffect, useRef, type ReactNode } from "react";
+import { memo, useCallback, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native";
import Animated, {
interpolate,
@@ -27,6 +27,7 @@ const ACTION_SIZE = 56;
const GAP = spacing.md;
const LEADING_WIDTH = ACTION_SIZE * 2 + GAP * 3;
const TRAILING_WIDTH = ACTION_SIZE + GAP * 2;
+const EDGE_HIT_SLOP = { left: -spacing.xl };
interface Props {
projectKey: string;
@@ -66,6 +67,27 @@ export const SwipeableProjectHeader = memo(function SwipeableProjectHeader({
},
[close, registry, rowKey],
);
+ // Keep RNGH's worklet graph registered across list updates and rotation.
+ // Release actions read the current committed project and full-swipe width.
+ const gestureInputs = useRef({ registry, rowKey, width, run, onNewTask });
+ useLayoutEffect(() => {
+ gestureInputs.current = { registry, rowKey, width, run, onNewTask };
+ });
+ const handleOpenStartDrag = useCallback(() => {
+ const { registry, rowKey } = gestureInputs.current;
+ registry.onRowOpen(rowKey, close);
+ }, [close]);
+ const handleClose = useCallback(() => {
+ const { registry, rowKey } = gestureInputs.current;
+ registry.onRowClose(rowKey);
+ }, []);
+ const handleWillOpen = useCallback((direction: (typeof SwipeDirection)[keyof typeof SwipeDirection]) => {
+ const { width, run, onNewTask } = gestureInputs.current;
+ // Release only. Right swipes always require an explicit action tap.
+ if (direction === SwipeDirection.LEFT && -(translation.current?.value ?? 0) >= width * 0.55) {
+ run(onNewTask);
+ }
+ }, []);
return (
<ReanimatedSwipeable
@@ -74,19 +96,11 @@ export const SwipeableProjectHeader = memo(function SwipeableProjectHeader({
containerStyle={styles.surface}
childrenContainerStyle={styles.surface}
// Leave the screen edge available to native back navigation.
- hitSlop={{ left: -spacing.xl }}
+ hitSlop={EDGE_HIT_SLOP}
overshootLeft={false}
- onSwipeableOpenStartDrag={() => registry.onRowOpen(rowKey, close)}
- onSwipeableClose={() => registry.onRowClose(rowKey)}
- onSwipeableWillOpen={(direction) => {
- // Release only. Right swipes always require an explicit action tap.
- if (
- direction === SwipeDirection.LEFT &&
- -(translation.current?.value ?? 0) >= width * 0.55
- ) {
- run(onNewTask);
- }
- }}
+ onSwipeableOpenStartDrag={handleOpenStartDrag}
+ onSwipeableClose={handleClose}
+ onSwipeableWillOpen={handleWillOpen}
renderLeftActions={(_progress, offset) => {
translation.current = offset;
return (
diff --git a/apps/mobile/src/session/SwipeableSessionRow.ios.tsx b/apps/mobile/src/session/SwipeableSessionRow.ios.tsx
index bd9512694e..2b8ffdd8e0 100644
--- a/apps/mobile/src/session/SwipeableSessionRow.ios.tsx
+++ b/apps/mobile/src/session/SwipeableSessionRow.ios.tsx
@@ -20,7 +20,7 @@
* - 全滑判定在 onSwipeableWillOpen(松手后的 JS 回调)同步读 translation,不在
* worklet 拖动中触发 —— 手指还按着时行被移除会拆手势树。
*/
-import { memo, useCallback, useEffect, useRef, type ReactNode } from "react";
+import { memo, useCallback, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native";
import {
ReanimatedSwipeable as Swipeable,
@@ -155,18 +155,27 @@ function SwipeableSessionRowInner({
methodsRef.current?.close();
}, []);
+ // RNGH rebuilds its serialized worklet graph when these JS callbacks change.
+ // Row refreshes and rotation only update the action's committed inputs.
+ const gestureInputs = useRef({ registry, rowKey, fullSwipeThreshold, onMarkRead, onArchive, session });
+ useLayoutEffect(() => {
+ gestureInputs.current = { registry, rowKey, fullSwipeThreshold, onMarkRead, onArchive, session };
+ });
const handleOpenStartDrag = useCallback(() => {
+ const { registry, rowKey } = gestureInputs.current;
registry.onRowOpen(rowKey, close);
- }, [registry, rowKey, close]);
+ }, [close]);
const handleClose = useCallback(() => {
+ const { registry, rowKey } = gestureInputs.current;
registry.onRowClose(rowKey);
- }, [registry, rowKey]);
+ }, []);
// 全滑判定:松手瞬间(库在 release 时派发 WillOpen)读当前位移,超阈值即触发。
// direction 语义:RIGHT = 右滑(露出左面板/置顶),LEFT = 左滑(露出右面板/归档)。
const handleWillOpen = useCallback(
(direction: (typeof SwipeDirection)[keyof typeof SwipeDirection]) => {
+ const { fullSwipeThreshold, onMarkRead, onArchive, session } = gestureInputs.current;
const translation = translationRef.current;
if (!translation) return;
if (direction === SwipeDirection.RIGHT) {
@@ -182,7 +191,7 @@ function SwipeableSessionRowInner({
onArchive(session);
}
},
- [fullSwipeThreshold, close, onMarkRead, onArchive, session],
+ [close],
);
const handleReadPress = useCallback(() => {
diff --git a/apps/mobile/src/session/usePendingSendActions.ts b/apps/mobile/src/session/usePendingSendActions.ts
new file mode 100644
index 0000000000..51fff63f8e
--- /dev/null
+++ b/apps/mobile/src/session/usePendingSendActions.ts
@@ -0,0 +1,123 @@
+import { useCallback, useMemo, type RefObject } from 'react';
+import { Alert } from 'react-native';
+import type { useRouter } from 'expo-router';
+import type { TFunction } from 'i18next';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { formatRemoteError } from '@/device-link/remoteStatus';
+import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';
+import { isDurableOutboxUnsent } from './durableOutbox';
+import { remoteSessionStore } from './remoteSessionStore';
+import type { PendingSendBubbleActions } from './PendingSendBubble';
+import type { QueuedRemoteMessage } from './types';
+
+/** Keep outbox callbacks stable without capturing records from an earlier task. */
+export function usePendingOutboxActions({
+ deviceId, deviceName, sessionId, router, outboxSessionAliveRef,
+ setError, setQueueSelectedClientId, t,
+}: {
+ deviceId: string;
+ deviceName: string;
+ sessionId: string;
+ router: Pick<ReturnType<typeof useRouter>, 'push'>;
+ outboxSessionAliveRef: RefObject<string | null>;
+ setError(error: string): void;
+ setQueueSelectedClientId(clientId: string | null): void;
+ t: TFunction;
+}) {
+ const findDurableOutboxRecord = useCallback((clientId: string) => getCurrentMobileOutboxRecords().find((r) =>
+ r.deviceId === deviceId && r.item.sessionId === sessionId && r.item.clientId === clientId), [deviceId, sessionId]);
+ const retryOutboxItem = useCallback((clientId: string) => {
+ const record = findDurableOutboxRecord(clientId);
+ if (!record || record.state !== 'failed') return;
+ if (record.creation && !record.prepared && !record.template) {
+ const owner = getMobileAuthOwner();
+ void mobileDurableOutbox.update(record, { suspended: true }).then(() => {
+ if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) {
+ router.push({ pathname: '/sessions/new', params: { recoverySessionId: sessionId, deviceId, deviceName } });
+ }
+ }).catch((err) => setError(formatRemoteError(err)));
+ return;
+ }
+ setQueueSelectedClientId(null);
+ void mobileDurableOutbox.update(record, {
+ state: record.prepared ? 'confirming' : 'queued', error: undefined,
+ }).catch((err) => setError(formatRemoteError(err)));
+ }, [deviceId, deviceName, findDurableOutboxRecord, outboxSessionAliveRef, router, sessionId, setError, setQueueSelectedClientId]);
+ const removeOutboxItem = useCallback((clientId: string) => {
+ const record = findDurableOutboxRecord(clientId);
+ if (!record) return;
+ // Until creation succeeds, this row also owns the recovery form for every later message.
+ if (record.creation && !record.prepared && !record.template) {
+ setError(t('session.outbox.creationRecoveryRequired'));
+ return;
+ }
+ // 删除发送失败的消息不可撤销:先确认(破坏性按钮),确认后才真正移除。
+ const confirmRemove = () => {
+ setQueueSelectedClientId(null);
+ const owner = getMobileAuthOwner();
+ const remove = async () => {
+ if (isDurableOutboxUnsent(record)) {
+ await mobileDurableOutbox.update(record, { state: 'host-owned', cleanupOutcome: 'cancelled', cancelRequested: true, error: undefined });
+ } else await mobileDurableOutbox.update(record, { cancelRequested: true, state: 'confirming' });
+ };
+ void remove().catch((err) => {
+ if (isMobileAuthOwnerCurrent(owner) && outboxSessionAliveRef.current === sessionId) setError(formatRemoteError(err));
+ });
+ };
+ Alert.alert(
+ t('session.outbox.deleteConfirmTitle'),
+ t('session.outbox.deleteConfirmBody'),
+ [
+ { text: t('session.common.cancel'), style: 'cancel' },
+ { text: t('session.common.delete'), style: 'destructive', onPress: confirmRemove },
+ ],
+ );
+ }, [findDurableOutboxRecord, outboxSessionAliveRef, sessionId, setError, setQueueSelectedClientId, t]);
+ return { findDurableOutboxRecord, retryOutboxItem, removeOutboxItem };
+}
+
+/** Shared action object for message rows; look up queue entries when clicked. */
+export function usePendingSendActions({
+ beginQueueEdit, moveQueueItem, queueBusy, queueSelectedClientId,
+ removeQueueItem, removeOutboxItem, retryOutboxItem, sessionId,
+ setQueueSelectedClientId, steerQueueItem,
+}: {
+ beginQueueEdit(item: QueuedRemoteMessage): void;
+ moveQueueItem: PendingSendBubbleActions['onMove'];
+ queueBusy: boolean;
+ queueSelectedClientId: string | null;
+ removeQueueItem: PendingSendBubbleActions['onRemove'];
+ removeOutboxItem: PendingSendBubbleActions['onRemoveOutbox'];
+ retryOutboxItem: PendingSendBubbleActions['onRetryOutbox'];
+ sessionId: string;
+ setQueueSelectedClientId: PendingSendBubbleActions['onSelect'];
+ steerQueueItem(item: QueuedRemoteMessage): void;
+}) {
+ return useMemo<PendingSendBubbleActions>(
+ () => ({
+ busy: queueBusy,
+ selectedClientId: queueSelectedClientId,
+ onSelect: setQueueSelectedClientId,
+ onRemove: (clientId: string) => {
+ setQueueSelectedClientId(null);
+ removeQueueItem(clientId);
+ },
+ onBeginEdit: (clientId: string) => {
+ const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue
+ .find((entry) => entry.clientId === clientId);
+ if (target) beginQueueEdit(target);
+ },
+ onSteer: (clientId: string) => {
+ const target = remoteSessionStore.getInputProjection(sessionId).pendingQueue
+ .find((entry) => entry.clientId === clientId);
+ if (!target) return;
+ setQueueSelectedClientId(null);
+ steerQueueItem(target);
+ },
+ onMove: moveQueueItem,
+ onRetryOutbox: retryOutboxItem,
+ onRemoveOutbox: removeOutboxItem,
+ }),
+ [beginQueueEdit, setQueueSelectedClientId, moveQueueItem, queueBusy, queueSelectedClientId, removeQueueItem, removeOutboxItem, retryOutboxItem, sessionId, steerQueueItem],
+ );
+}