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): align rich share snapshots with chat origin

zqchrisa9ea83cef21a
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index f87d39899e..cc103a431f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -6326,8 +6326,16 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
textTertiary: colors.textTertiary,
dark: mode === 'dark',
}), [colors, mode, userBubbleColors]);
- const snapshotShareRichValues = useCallback((message: ConversationShareMessage) => snapshotRichAnswerValues(message.body,
- `${auth.user?.id ?? 'signed-out'}:${deviceId}:${sessionId}:${message.richStateKey ?? message.clientId}`), [auth.user?.id, deviceId, sessionId]);
+ // File context and rich-answer memory must agree even when no workdir/device exists.
+ const chatFilePathOrigin = useMemo(() => {
+ const workdir = currentSession?.workingDir?.trim();
+ return deviceId && workdir ? { deviceId, sessionId, workdir } : null;
+ }, [currentSession?.workingDir, deviceId, sessionId]);
+ const snapshotShareRichValues = useCallback((message: ConversationShareMessage) => snapshotRichAnswerValues(message.body, {
+ userId: auth.user?.id,
+ origin: chatFilePathOrigin,
+ messageKey: message.richStateKey ?? message.clientId,
+ }), [auth.user?.id, chatFilePathOrigin]);
const shareImages = useConversationShareImages(selectedShareMessages, resolveRemoteMedia, {
snapshotRichValues: snapshotShareRichValues,
workdir: currentSession?.workingDir ?? undefined,
@@ -9142,8 +9150,8 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
// connectionEpoch 在 deps 里确保同 deviceId 断线重连时 memo 重建、linkReady 作废,
// 避免复用旧 transport epoch 上已 resolve 的握手 promise。
const chatFilePathContextValue = useMemo<ChatFilePathContextValue | null>(() => {
- const workdir = currentSession?.workingDir?.trim();
- if (!deviceId || !workdir) return null;
+ if (!chatFilePathOrigin) return null;
+ const { deviceId, sessionId, workdir } = chatFilePathOrigin;
let linkReady: Promise<void> | null = null;
const ensureLink = () => {
if (!linkReady) {
@@ -9188,15 +9196,13 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
},
};
}, [
+ chatFilePathOrigin,
connectionEpoch,
currentSession?.remoteHostId,
- currentSession?.workingDir,
- deviceId,
maker,
mode,
openChatPathTarget,
openLink,
- sessionId,
t,
]);
diff --git a/apps/mobile/src/__tests__/richAnswer.test.tsx b/apps/mobile/src/__tests__/richAnswer.test.tsx
index 5c9c52b22d..b940aa99ee 100644
--- a/apps/mobile/src/__tests__/richAnswer.test.tsx
+++ b/apps/mobile/src/__tests__/richAnswer.test.tsx
@@ -2,8 +2,11 @@
import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { RichAnswer } from '@/session/RichAnswer';
+import { RichAnswer, snapshotRichAnswerValues } from '@/session/RichAnswer';
import { SessionQuickSendProvider } from '@/session/SessionQuickSendContext';
+import { buildConversationShareHtml } from '@/session/conversationShareWebViewHtml';
+import { buildConversationShareSvgLayout } from '@/session/conversationShareSvgLayout';
+import { lightColors } from '@/theme/tokens';
vi.mock('react-native', () => ({
View: ({ children }: any) => <div>{children}</div>,
@@ -22,6 +25,7 @@ vi.mock('lucide-react-native', () => Object.fromEntries(['Mail', 'CalendarDays',
vi.mock('react-native-svg', () => Object.fromEntries(['default', 'Path', 'Rect', 'Ellipse', 'Polygon', 'Polyline', 'Line', 'Circle', 'Text'].map(name => [name, () => null])));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'mobile-rich-test' } }) }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('@/theme', () => ({
useTheme: () => ({ colors: {} }),
useThemedStyles: () => ({ text: {}, heading: {}, caption: {}, iconTitle: {}, statValue: {}, buttonText: {}, input: {} }),
@@ -69,6 +73,41 @@ it('keeps incomplete and read-only answers from sending', async () => {
expect(send).not.toHaveBeenCalled();
});
+// Unit regression: route ids used to miss the live memory entry when file origin was null.
+// Edit the production control, then read its real memory through both export builders.
+it.each([null, { deviceId: 'desktop', sessionId: 'task' }])(
+ 'exports edited controls using the live file origin %j', async (origin) => {
+ const messageKey = origin ? 'scoped-share' : 'originless-share';
+ // This is the stateKey supplied by MessageRenderer, including the rich part offset.
+ const stateKey = `${origin?.deviceId ?? ''}:${origin?.sessionId ?? ''}:${messageKey}:1`;
+ await render(stateKey, null);
+ const input = container.querySelector('input')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'Suzhou');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ const body = `\n\`\`\`cindy-ui\n${source}\n\`\`\``;
+ const scope = { userId: 'mobile-rich-test', origin, messageKey };
+ const richValues = snapshotRichAnswerValues(body, scope);
+ expect(richValues[1]?.name).toBe('Suzhou');
+ expect(snapshotRichAnswerValues(body, { ...scope, userId: 'other-account' })[1]).toEqual({});
+ const messages = [{ clientId: messageKey, kind: 'assistant' as const, body, richValues }];
+ const colors = {
+ ...lightColors, background: lightColors.surface,
+ codeSurface: lightColors.chatCodeSurface, inlineCode: lightColors.chatInlineCodeText,
+ syntax: {},
+ };
+ const html = buildConversationShareHtml({ selectedMessages: messages, allShareableIds: [messageKey], colors, contentWidth: 390 });
+ const layout = buildConversationShareSvgLayout({ messages, allShareableIds: [messageKey], colors, width: 390 });
+ const text = layout.bubbles.flatMap(b => b.textBlocks.flatMap(block => block.lines)).join('\n');
+ for (const output of [html, text]) {
+ expect(output).toContain('Suzhou');
+ expect(output).not.toContain('Hangzhou');
+ }
+ expect(input.value).toBe('Suzhou');
+ },
+);
+
// Tier 1: a completed-looking partial snapshot used to poison the mounted parser.
// The same answer must recover on its final snapshot without leaving/reopening it.
it('replaces the incomplete notice with the late full answer without remounting', async () => {
diff --git a/apps/mobile/src/session/RichAnswer.tsx b/apps/mobile/src/session/RichAnswer.tsx
index d6ae8123dd..fe02fed550 100644
--- a/apps/mobile/src/session/RichAnswer.tsx
+++ b/apps/mobile/src/session/RichAnswer.tsx
@@ -87,6 +87,7 @@ import {
type RichValue,
} from "@cindy/maker-shared/rich-answer";
import { useSessionQuickSend } from './SessionQuickSendContext';
+import type { ChatFilePathContextValue } from './chatFilePathContext';
/** Answer colors are Cindy theme colors; the model only names a role. */
const richPalette = (colors: ThemeColors): RichPalette => ({
@@ -125,8 +126,13 @@ const memory = new RichInteractionMemory({
/** Click-time copy: an export never changes the conversation's local controls. */
export function snapshotRichAnswerValues(
source: string,
- stateKey: string,
+ scope: {
+ userId: string | undefined;
+ origin: Pick<ChatFilePathContextValue, 'deviceId' | 'sessionId'> | null;
+ messageKey: string;
+ },
): Readonly<Record<number, RichValues>> {
+ const stateKey = `${scope.userId ?? 'signed-out'}:${scope.origin?.deviceId ?? ''}:${scope.origin?.sessionId ?? ''}:${scope.messageKey}`;
return Object.fromEntries(
splitRichAnswer(source)
.filter((part) => part.kind === "rich")