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
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,19 @@ internal fun ChatMessageBubble(
downloadEnabled = downloadEnabled,
),
)
if (row.typing) ChatTypingDots(Modifier)
MessageImageGallery(images = row.images, userStyle = false)
}

if (row.showRetry) {
ChatMessageRetryAction(
fromUser = fromUser,
enabled = enabled,
onRetry = { onRetry(row) },
modifier = Modifier,
)
}

row.timestampMs?.let { timestamp ->
val locale = LocalConfiguration.current.locales[0]
Text(
Expand All @@ -131,19 +141,6 @@ internal fun ChatMessageBubble(
modifier = Modifier.testTag("chat-message-timestamp"),
)
}

// Two mutually exclusive footnotes about delivery: nothing has arrived
// yet, or the send was refused.
when {
row.showRetry -> ChatMessageRetryAction(
fromUser = fromUser,
enabled = enabled,
onRetry = { onRetry(row) },
modifier = Modifier,
)

row.typing -> ChatTypingDots(Modifier)
}
}
}

Expand Down Expand Up @@ -172,6 +169,7 @@ private fun AssistantContent(row: ConversationRow, callbacks: MessageBlockCallba
onOpenLink = callbacks.onOpenLink,
modifier = Modifier,
streaming = row.streaming,
streamKey = row.id,
)
FileReferenceCards(
text = row.text,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
Expand Down Expand Up @@ -54,7 +58,10 @@ import com.openbitfun.mobile.core.feature.markdown.MarkdownBlock
import com.openbitfun.mobile.core.feature.markdown.MarkdownInline
import com.openbitfun.mobile.core.feature.markdown.MarkdownListItem
import com.openbitfun.mobile.core.feature.markdown.MarkdownParser
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.ceil
import kotlin.math.min

internal const val MARKDOWN_TEST_TAG: String = "markdown"

Expand All @@ -80,6 +87,63 @@ internal fun MarkdownContent(
onOpenLink: (String, String) -> Unit,
modifier: Modifier,
streaming: Boolean = false,
streamKey: String = "",
) {
if (streaming) {
StreamingMarkdownContent(text, onOpenLink, modifier, streamKey)
return
}
MarkdownContentBody(text, onOpenLink, modifier, copyFullText = null)
}

private val streamingMarkdownCache = mutableMapOf<String, String>()

@Composable
private fun StreamingMarkdownContent(
text: String,
onOpenLink: (String, String) -> Unit,
modifier: Modifier,
streamKey: String,
) {
val key = streamKey.ifBlank { "default" }
var visible by remember(key) { mutableStateOf(streamingMarkdownCache[key].orEmpty()) }
var target by remember(key) { mutableStateOf(visible) }

LaunchedEffect(key, text) {
if (!text.startsWith(visible) || !text.startsWith(target)) {
visible = text
target = text
streamingMarkdownCache[key] = text
return@LaunchedEffect
}
target = text
while (visible != target) {
delay(40)
if (!text.startsWith(visible)) {
visible = text
target = text
break
}
val visiblePoints = visible.codePointCount(0, visible.length)
val targetPoints = target.codePointCount(0, target.length)
val remaining = targetPoints - visiblePoints
val step = maxOf(1, ceil(remaining.toDouble() / 35.0).toInt())
val nextPoints = min(targetPoints, visiblePoints + step)
visible = target.substring(0, target.offsetByCodePoints(0, nextPoints))
streamingMarkdownCache[key] = visible
}
streamingMarkdownCache[key] = visible
}

MarkdownContentBody(visible, onOpenLink, modifier, copyFullText = target)
}

@Composable
private fun MarkdownContentBody(
text: String,
onOpenLink: (String, String) -> Unit,
modifier: Modifier,
copyFullText: String?,
) {
val blocks = remember(text) { MarkdownParser.parse(text) }
Column(
Expand All @@ -90,7 +154,7 @@ internal fun MarkdownContent(
MarkdownBlockView(
block = block,
onOpenLink = onOpenLink,
copyFullText = if (streaming) text else null,
copyFullText = copyFullText,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ private fun MessageBlockView(block: MessageBlock, callbacks: MessageBlockCallbac
onOpenLink = callbacks.onOpenLink,
modifier = Modifier,
streaming = block.streaming,
streamKey = block.id,
)
FileReferenceCards(
text = block.text,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,11 @@ export class ChatTimelineRevisionTracker {
`${message ? ChatTimelineRevisionTracker.textSignature(message.text) : ''}:` +
`${message && message.error ? ChatTimelineRevisionTracker.textSignature(message.error) : ''}:` +
`${message && message.thinking ? ChatTimelineRevisionTracker.textSignature(message.thinking) : ''}:` +
`${message && message.detail ? ChatTimelineRevisionTracker.textSignature(message.detail) : ''}:` +
`${message && message.appCard ? JSON.stringify(message.appCard) : ''}:` +
`${message && message.items ? message.items.length : 0}:${message && message.tools ? message.tools.length : 0}`;
`${message && message.items ? JSON.stringify(message.items) : ''}:` +
`${message && message.tools ? JSON.stringify(message.tools) : ''}:` +
`${message && message.images ? JSON.stringify(message.images) : ''}`;
}

update(items: ChatTimelineItem[]): number {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ export struct ChatMessageBubble {
}

private shouldShowTypingDots(item: ConversationUiMessage): boolean {
if (item.role === 'user' || (item.status || '').toLowerCase() !== 'active') {
if (item.role === 'user' || (!this.isStreaming && (item.status || '').toLowerCase() !== 'active')) {
return false;
}
return this.visibleMessageText(item).length === 0 &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export class AppRootRuntime extends AppRootRuntimeComposition {

constructor(host: AppRootHostPort) {
super(host);
this.localGenUIViewModel.setBackgroundKeepAlive(this.localGenUIBackgroundPort);
}

subscribeToDesktopLaunch(onLaunch: () => void): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ export abstract class AppRootRuntimeComposition {
readonly localGenUIViewModel: LocalGenUIViewModel = new LocalGenUIViewModel((): Context => this.host.context());
readonly taskCompletionNotificationPort: HarmonyTaskCompletionNotificationPort =
new HarmonyTaskCompletionNotificationPort((): Context => this.host.context());
/** Separate suspend-delay lease so local GenUI never cancels remote task observation. */
readonly localGenUIBackgroundPort: HarmonyTaskCompletionNotificationPort =
new HarmonyTaskCompletionNotificationPort((): Context => this.host.context());
readonly taskCompletionNotificationController: TaskCompletionNotificationController =
new TaskCompletionNotificationController(
this.taskCompletionNotificationPort,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
LocalGenUIPresentationSource,
LocalGenUISessionController
} from '../../services/local-genui/LocalGenUISessionController';
import { LocalGenUIBackgroundKeepAlive } from '../../services/local-genui/LocalGenUIBackgroundKeepAlive';
import { LocalGenUIActions, LocalGenUIModelEditorInput, LocalGenUIState } from '../state/LocalGenUIState';
import { ConversationIntent, ConversationIntentType, MessageCopyScope } from '../actions/ConversationIntent';
import { ConversationViewModel } from './ConversationViewModel';
Expand Down Expand Up @@ -70,6 +71,7 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG
private showActiveTurn: boolean = true;
private readonly orientation: LocalGenUIOrientation;
private preferredOrientation: string = 'auto';
private backgroundKeepAlive?: LocalGenUIBackgroundKeepAlive;

readonly actions: LocalGenUIActions = {
open: (): void => {
Expand Down Expand Up @@ -229,9 +231,19 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG
/** The phone app went to the background or came back. */
setForeground(foreground: boolean): void {
this.foreground = foreground;
if (foreground) {
this.controller?.onForeground();
} else {
this.controller?.onBackground();
}
this.syncDeviceVisibility();
}

setBackgroundKeepAlive(backgroundKeepAlive: LocalGenUIBackgroundKeepAlive): void {
this.backgroundKeepAlive = backgroundKeepAlive;
this.controller?.setBackgroundKeepAlive(backgroundKeepAlive);
}

/** Camera surface from the preview leaf; recognition starts once it exists. */
attachCameraSurface(surfaceId: string): void {
if (this.devices) this.devices.attachSurface(surfaceId);
Expand Down Expand Up @@ -604,6 +616,9 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG
this.devices = devices;
this.syncDeviceVisibility();
this.controller = new LocalGenUISessionController(repository, provider, contract, this.bridge, this, this, models, thumbnails, devices, desktopCards, calendar, collaboration, photos);
if (this.backgroundKeepAlive) {
this.controller.setBackgroundKeepAlive(this.backgroundKeepAlive);
}
await this.controller.refreshModels();
RemoteLogger.info(`local genui ready renderer=${contract.manifest.rendererRevision} models=${models.list().length}`);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export class ChatSessionController {
let active: ChatMessage | undefined = undefined;
this.completedTurnId = '';
this.subagents.decorate(transcript).forEach((message: ChatMessage) => {
if (message.role === 'assistant' && (message.status === 'active' || message.status === 'running')) active = message;
if (message.role === 'assistant' && ChatSessionController.isActiveTurnStatus(message.status)) active = message;
else {
persisted.push(message);
if (message.role === 'assistant') {
Expand All @@ -246,4 +246,10 @@ export class ChatSessionController {
promptSuggestion: active ? '' : suggestion
});
}

private static isActiveTurnStatus(status: string): boolean {
return ['active', 'inprogress', 'starting', 'running', 'streaming', 'thinking',
'tool_calling', 'pending_confirmation', 'capability_required', 'finishing']
.indexOf((status || '').toLowerCase()) >= 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ export class ChatTimelineProjector {
// one visual row and share one stable turn key, so retaining both would
// violate the uniqueness contract required by Repeat.virtualScroll().
const timelineMessages = shouldRenderActiveTurn ? persistedMessages.filter((message: ChatMessage) => {
return !ChatTimelineProjector.isMatchingAssistantTurn(activeTurn, message);
if (!ChatTimelineProjector.isMatchingAssistantTurn(activeTurn, message)) return true;
return !(ChatTimelineProjector.isStreamingStatus((activeTurn.status || '').toLowerCase()) ||
ChatTimelineProjector.hasDisplayableAssistantFinal(message));
}) : persistedMessages;
const pendingItems = ChatTimelineProjector.pendingMessagesNotPersisted(pendingMessages, timelineMessages);
const anchorIndex = ChatTimelineProjector.anchorIndex(pendingItems, activeTurnAnchorId);
Expand Down Expand Up @@ -91,17 +93,25 @@ export class ChatTimelineProjector {

private static activeTurnItem(activeTurn: ChatMessage): ChatTimelineItem {
const turnKey = ChatTimelineProjector.activeTurnKey(activeTurn);
const status = (activeTurn.status || '').toLowerCase();
const item: ChatTimelineItem = {
id: `active-${turnKey}`,
type: 'assistant_live_turn',
message: activeTurn,
isStreaming: (activeTurn.status || '').toLowerCase() === 'active',
isFinalizing: (activeTurn.status || '').toLowerCase() === 'completed',
isStreaming: ChatTimelineProjector.isStreamingStatus(status),
isFinalizing: status === 'completed',
showRetryAction: false
};
return item;
}

private static isStreamingStatus(status: string): boolean {
return [
'active', 'inprogress', 'starting', 'running', 'streaming', 'thinking',
'tool_calling', 'pending_confirmation', 'capability_required', 'finishing'
].indexOf(status) >= 0;
}

private static markLatestFailedMessageRetryable(items: ChatTimelineItem[]): void {
for (let index = items.length - 1; index >= 0; index--) {
const message = items[index].message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,8 @@ export class ChatTimelineStore {
return fallback === 'sending' ? 'sending' : 'idle';
}
const status = (activeTurn.status || '').toLowerCase();
if (status === 'active') {
if (['active', 'inprogress', 'starting', 'running', 'streaming', 'thinking',
'tool_calling', 'pending_confirmation', 'capability_required', 'finishing'].indexOf(status) >= 0) {
return 'streaming';
}
if (status === 'completed') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
import { notificationManager } from '@kit.NotificationKit';
import { RemoteI18n } from '../i18n/RemoteI18n';
import { RemoteLogger } from './RemoteLogger';
import { LocalGenUIBackgroundKeepAlive } from './local-genui/LocalGenUIBackgroundKeepAlive';
import {
TaskCompletionNotificationPort,
TaskCompletionObservation
Expand All @@ -12,7 +13,7 @@ import {
const BACKGROUND_REASON: string = 'Waiting for an active OpenBitFun task to finish';

/** HarmonyOS platform leaf for task-completion notifications. */
export class HarmonyTaskCompletionNotificationPort implements TaskCompletionNotificationPort {
export class HarmonyTaskCompletionNotificationPort implements TaskCompletionNotificationPort, LocalGenUIBackgroundKeepAlive {
private readonly contextProvider: () => Context;
private permissionPrepared: boolean = false;
private suspendRequestId: number = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** Platform-neutral lease used to keep a local provider request alive in background. */
export interface LocalGenUIBackgroundKeepAlive {
keepAlive(onExpired: () => void): boolean;
releaseKeepAlive(): void;
}
Loading
Loading