Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions __tests__/chatReplyService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,35 @@ describe('generateChatReply', () => {
expect(mockGenerateReplyFn).toHaveBeenCalledWith({ prompt: 'hi', referenceId: 'abc' })
})

it('omits undefined optional fields from the callable payload', async () => {
mockGenerateReplyFn.mockResolvedValue({
data: {
reply: 'Hello',
verifiedAt: '2026-01-01T00:00:00.000Z',
},
})

const resultPromise = generateChatReply({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
systemInstruction: 'Be concise.',
})

if (!resolveAppCheck) {
throw new Error('Expected appCheckReady resolver to be set')
}
resolveAppCheck()

await resultPromise

expect(mockGenerateReplyFn).toHaveBeenCalledWith({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
systemInstruction: 'Be concise.',
})
expect(mockGenerateReplyFn.mock.calls[0][0]).not.toHaveProperty('unsyncedHistory')
expect(mockGenerateReplyFn.mock.calls[0][0]).not.toHaveProperty('characterId')
expect(mockGenerateReplyFn.mock.calls[0][0]).not.toHaveProperty('referenceId')
})

it('forwards structured contents and systemInstruction to the callable payload', async () => {
mockGenerateReplyFn.mockResolvedValue({
data: {
Expand Down
28 changes: 28 additions & 0 deletions functions/src/generateReply.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,34 @@ test("generateReplyHandler rejects unsyncedHistory entries with non-user roles",
});
});

test("generateReplyHandler treats null unsyncedHistory as absent (Firebase web encodes undefined as null)", async () => {
const auth = buildAuth();

await withServiceMocks(async () => {
const user = buildUser(auth);

userRepository.getOrCreateUserByFirebaseIdentity = async () => user;
subscriptionService.getSubscription = async () => buildSubscription(user.id, "payg", 5);
creditService.spendCredits = async () => 'mock-tx-id';
creditService.getCredits = async () => 4;

const result = await generateReplyHandler(
{
auth,
data: {
...buildStructuredRequestData('hello'),
unsyncedHistory: null,
},
} as never,
{
generateText: async () => ({ text: "reply" }),
}
);

assert.equal(result.reply, "reply");
});
});

test("generateReplyHandler validates character ownership before bulk inserting unsyncedHistory", async () => {
const auth = buildAuth();

Expand Down
100 changes: 72 additions & 28 deletions functions/src/generateReply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,23 @@ export function buildToolsForRequest(tools?: ToolDeclaration[]): Tool[] {
return buildAuthorizedToolsArray([googleSearchManifest], []).map(toGenAITool);
}

const NON_RETRYABLE_EMPTY_RESPONSE_FINISH_REASONS = new Set([
"MAX_TOKENS",
"SAFETY",
"RECITATION",
"BLOCKLIST",
"PROHIBITED_CONTENT",
"SPII",
"MALFORMED_FUNCTION_CALL",
]);

function isRetryableEmptyResponseFinishReason(finishReason: string | undefined): boolean {
if (!finishReason || finishReason === "FINISH_REASON_UNSPECIFIED" || finishReason === "OTHER") {
return true;
}
return !NON_RETRYABLE_EMPTY_RESPONSE_FINISH_REASONS.has(finishReason);
}

function getTextGenerator(): GenerateTextFn {
if (textGenerator) {
return textGenerator;
Expand All @@ -327,38 +344,65 @@ function getTextGenerator(): GenerateTextFn {
const ai = getGenAIClient();
const tools = buildToolsForRequest(input.tools);

const result = await ai.models.generateContent({
model: DEFAULT_MODEL,
contents: input.contents as Content[],
config: {
systemInstruction: input.systemInstruction,
maxOutputTokens: MAX_OUTPUT_TOKENS,
thinkingConfig: { thinkingBudget: 0 },
tools,
},
});
for (let attempt = 0; attempt < 2; attempt++) {
const result = await ai.models.generateContent({
model: DEFAULT_MODEL,
contents: input.contents as Content[],
config: {
systemInstruction: input.systemInstruction,
maxOutputTokens: MAX_OUTPUT_TOKENS,
thinkingConfig: { thinkingBudget: 0 },
tools,
},
});

if (result.functionCalls && result.functionCalls.length > 0) {
return {
functionCalls: result.functionCalls.map((fc) => ({
name: fc.name ?? "",
args: fc.args as Record<string, unknown> | undefined,
})),
};
}

if (result.functionCalls && result.functionCalls.length > 0) {
return {
functionCalls: result.functionCalls.map((fc) => ({
name: fc.name ?? "",
args: fc.args as Record<string, unknown> | undefined,
})),
};
}
const candidates = result.candidates ?? [];

const candidates = result.candidates ?? [];
for (const candidate of candidates) {
const parts = candidate.content?.parts ?? [];
const text = parts
.map((part) => (typeof part.text === "string" ? part.text : ""))
.join("")
.trim();

if (text.length > 0) {
return { text, groundingMetadata: candidate.groundingMetadata };
}
}

for (const candidate of candidates) {
const parts = candidate.content?.parts ?? [];
const text = parts
.map((part) => (typeof part.text === "string" ? part.text : ""))
.join("")
.trim();
const finishReasons = candidates.map((c) => c.finishReason ?? null);
const shouldRetry =
attempt === 0 &&
(candidates.length === 0 ||
candidates.some((candidate) => isRetryableEmptyResponseFinishReason(candidate.finishReason)));

if (text.length > 0) {
return { text, groundingMetadata: candidate.groundingMetadata };
if (shouldRetry) {
logger.warn("generateReply empty model response, retrying once", {
finishReasons,
candidateCount: candidates.length,
});
continue;
}

logger.error(
attempt === 0
? "generateReply model returned empty response with non-retryable finish reason"
: "generateReply model returned empty response after retry",
{
finishReasons,
candidateCount: candidates.length,
},
);
break;
}
Comment thread
equationalapplications marked this conversation as resolved.

throw new HttpsError("internal", "Model returned an empty response.");
Expand Down Expand Up @@ -455,7 +499,7 @@ function parseInput(data: unknown): {
const rawHistory = payload?.unsyncedHistory;
let unsyncedHistory: SyncMessage[] | undefined;

if (rawHistory !== undefined) {
if (rawHistory != null) {
if (!Array.isArray(rawHistory)) {
throw new HttpsError("invalid-argument", "unsyncedHistory must be an array when provided.");
}
Expand Down
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

94 changes: 74 additions & 20 deletions src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { useCallback, useState } from 'react'
import { router } from 'expo-router'
import { useNavigation } from 'expo-router/react-navigation'
import { View, Text as RNText, StyleSheet, Platform, TouchableOpacity, Linking } from 'react-native'
import type { FlatListProps, TextStyle } from 'react-native'
import { GiftedChat, Bubble, InputToolbar, Send, MessageText } from 'react-native-gifted-chat'
import type { IMessage, User, ComposerProps, SendProps, InputToolbarProps, MessageTextProps } from 'react-native-gifted-chat'
import { useSelector } from '@xstate/react'
Expand All @@ -20,6 +21,15 @@ import type { Character } from '~/services/characterService'

const defaultAvatarUrl = 'https://via.placeholder.com/150'

const webMessageTextWrapStyle = {
wordBreak: 'break-word',
overflowWrap: 'anywhere',
} as TextStyle

/** Native WebViews in inverted lists can paint over sibling rows unless clipping is disabled. */
const groundingListViewProps: Pick<FlatListProps<unknown>, 'removeClippedSubviews'> | undefined =
Platform.OS === 'web' ? undefined : { removeClippedSubviews: false }

interface ChatViewProps {
characterId: string
}
Expand Down Expand Up @@ -132,24 +142,60 @@ function ChatViewContent({
)

const renderBubble = useCallback(
(props: any) => (
<Bubble
{...props}
wrapperStyle={{
left: { backgroundColor: colors.secondary, borderRadius: roundness },
right: { backgroundColor: colors.primary, borderRadius: roundness },
}}
textStyle={{
left: { color: colors.onSecondary },
right: { color: colors.onPrimary },
}}
renderMessageText={(msgProps: MessageTextProps<IMessage>) => (
<View style={{ paddingVertical: 10 }}>
<MessageText {...msgProps} />
</View>
)}
/>
),
(props: any) => {
const hasGrounding = Boolean(
(props.currentMessage as GroundedIMessage | undefined)?.groundingMetadata,
)
const webBubbleConstraints =
Platform.OS === 'web'
? ({ maxWidth: '80%', minWidth: 0, overflow: 'hidden' } as const)
: {}

return (
<Bubble
{...props}
touchableProps={
Platform.OS === 'web' && hasGrounding ? { disabled: true } : undefined
}
wrapperStyle={{
left: {
backgroundColor: colors.secondary,
borderRadius: roundness,
...webBubbleConstraints,
},
right: {
backgroundColor: colors.primary,
borderRadius: roundness,
...webBubbleConstraints,
},
}}
textStyle={{
left: { color: colors.onSecondary },
right: { color: colors.onPrimary },
}}
renderMessageText={(msgProps: MessageTextProps<IMessage>) => (
<View
style={{
paddingVertical: 10,
...(Platform.OS === 'web' ? { minWidth: 0, maxWidth: '100%' } : {}),
}}
>
<MessageText
{...msgProps}
textStyle={
Platform.OS === 'web'
? {
left: [msgProps.textStyle?.left, webMessageTextWrapStyle],
right: [msgProps.textStyle?.right, webMessageTextWrapStyle],
}
: msgProps.textStyle
}
/>
</View>
)}
/>
)
},
[colors, roundness],
)

Expand Down Expand Up @@ -332,6 +378,7 @@ function ChatViewContent({
renderCustomView={renderCustomView}
isCustomViewBottom
messageIdGenerator={() => `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`}
listViewProps={groundingListViewProps}
renderAvatarOnTop
messagesContainerStyle={styles.messagesContainer}
minInputToolbarHeight={56}
Expand Down Expand Up @@ -445,8 +492,12 @@ const styles = StyleSheet.create({
},
groundingContainer: {
paddingHorizontal: 8,
paddingBottom: 8,
paddingBottom: Platform.OS === 'web' ? 0 : 8,
gap: 6,
overflow: 'hidden',
width: '100%',
maxWidth: '100%',
minWidth: 0,
},
citationRow: {
flexDirection: 'row',
Expand All @@ -464,8 +515,11 @@ const styles = StyleSheet.create({
fontSize: 12,
},
searchSuggestions: {
height: 85,
backgroundColor: 'transparent',
width: '100%',
maxWidth: '100%',
minWidth: 0,
alignSelf: 'stretch',
},
headerTitle: {
flexDirection: 'row',
Expand Down
Loading