From 1b0c9196922875949edda6c9e65b5fac539756fd Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 31 Oct 2026 09:41:57 +0800 Subject: [PATCH 1/4] fix(remote): allow explicit file reads outside the workspace --- src/crates/assembly/core/AGENTS.md | 7 + .../core/src/service_agent_runtime.rs | 45 ++++- .../services/services-integrations/AGENTS.md | 4 +- .../src/remote_connect/file_projection.rs | 168 ++++++++++++++++-- 4 files changed, 200 insertions(+), 24 deletions(-) diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 7ba5636425..32a127f339 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -406,6 +406,13 @@ cargo test --locked -p openbitfun-core --no-default-features --features remote-c cargo test --locked -p openbitfun-core --no-default-features --features remote-connect --lib service_agent_runtime::tests::remote_workspace_catalog_tracks_opened_rows_and_assistant_identity ``` +For explicit mobile file preview/download outside the selected workspace: +`cargo test --locked -p openbitfun-core --no-default-features --features remote-connect,git --lib service_agent_runtime::tests::controller_file_reads_support_absolute_and_relative_paths_outside_workspace`. +Provider isolation and automatic delivery confinement are covered by +`cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::file_projection::tests`. +These fixtures cover local IO and a simulated remote filesystem, not live SSH, +relay, Peer Device, or Detached Dispatch connections. + Focused workspace-IO and snapshot regression entry points (use the matching filter rather than a product-wide build): diff --git a/src/crates/assembly/core/src/service_agent_runtime.rs b/src/crates/assembly/core/src/service_agent_runtime.rs index b0e56f04b7..db66b67827 100644 --- a/src/crates/assembly/core/src/service_agent_runtime.rs +++ b/src/crates/assembly/core/src/service_agent_runtime.rs @@ -40,7 +40,7 @@ use openbitfun_runtime_ports::{ #[cfg(feature = "remote-connect")] use openbitfun_services_integrations::remote_connect::{ agent_input_attachment_from_remote_image_context, build_remote_chat_messages, - build_remote_model_catalog, + build_remote_model_catalog, file_projection::controller_file_read_scope, normalize_remote_model_selection as normalize_remote_model_selection_contract, normalize_remote_session_model_id, project_remote_chat_user, remote_dialog_submit_outcome_from_scheduler, remote_model_selection_needs_config, ChatMessage, @@ -3343,7 +3343,7 @@ impl RemoteWorkspaceFileRuntimeHost for CoreRemoteWorkspaceFileRuntimeHost { ) -> Result, String> { CoreServiceAgentRuntime::remote_file_target(path, session_id) .await? - .read(max_bytes) + .read_with_scope(max_bytes, controller_file_read_scope(path)?) .await .map(Some) } @@ -3366,7 +3366,7 @@ impl RemoteWorkspaceFileRuntimeHost for CoreRemoteWorkspaceFileRuntimeHost { remote_connection_id, ) .await? - .read_chunk(offset, limit) + .read_chunk_with_scope(offset, limit, controller_file_read_scope(path)?) .await .map(Some) } @@ -3387,7 +3387,7 @@ impl RemoteWorkspaceFileRuntimeHost for CoreRemoteWorkspaceFileRuntimeHost { remote_connection_id, ) .await? - .info() + .info_with_scope(controller_file_read_scope(path)?) .await .map(Some) } @@ -4081,6 +4081,43 @@ mod tests { ); } + #[tokio::test] + async fn controller_file_reads_support_absolute_and_relative_paths_outside_workspace() { + use openbitfun_services_integrations::remote_connect::file_projection::controller_file_read_scope; + let tmp = tempfile::tempdir().unwrap(); + let workspace = tmp.path().join("project"); + std::fs::create_dir(&workspace).unwrap(); + let file = tmp.path().join("qr.png"); + std::fs::write(&file, b"png-data").unwrap(); + for reference in [file.to_string_lossy().into_owned(), "../qr.png".to_string()] { + let target = CoreServiceAgentRuntime::file_target_for_binding( + &reference, + None, + WorkspaceBinding::new(None, workspace.clone()), + ) + .await + .unwrap(); + let scope = controller_file_read_scope(&reference).unwrap(); + assert_eq!(target.info_with_scope(scope).await.unwrap().name, "qr.png"); + assert_eq!( + target.read_with_scope(100, scope).await.unwrap().bytes, + b"png-data" + ); + assert_eq!( + target + .read_chunk_with_scope(4, 100, scope) + .await + .unwrap() + .bytes, + b"data" + ); + assert!( + target.read(100).await.is_err(), + "automatic delivery keeps its scope" + ); + } + } + #[tokio::test] async fn missing_output_session_cannot_borrow_the_selected_workspace() { let missing = "missing-output-session-route-test"; diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index 6866609a87..041b85928e 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -50,7 +50,9 @@ slices that are outside pure product logic but still platform-neutral. session-selected `WorkspaceFileSystem`; `remote-connect` therefore selects `runtime-ports/workspace-ports` without enabling an SSH implementation. Core supplies the session root and provider. IM adapters consume authorized bytes - and must not re-resolve paths on the bot host. + and must not re-resolve paths on the bot host. Explicit controller file reads may use + provider scope outside the workspace; automatic output delivery and runtime + artifact URIs retain workspace/root confinement. - Remote workspace facts, session metadata, file projection DTOs, and workspace/projection host traits belong in `openbitfun-runtime-ports`. - Workspace-root source selection, persistence/workspace service reads, diff --git a/src/crates/services/services-integrations/src/remote_connect/file_projection.rs b/src/crates/services/services-integrations/src/remote_connect/file_projection.rs index 417f78a44a..e8be3339bf 100644 --- a/src/crates/services/services-integrations/src/remote_connect/file_projection.rs +++ b/src/crates/services/services-integrations/src/remote_connect/file_projection.rs @@ -7,6 +7,24 @@ use openbitfun_runtime_ports::{WorkspaceFileSystem, WorkspaceMetadata, Workspace use std::{path::Path, sync::Arc}; use tokio::io::{AsyncReadExt, AsyncSeekExt}; +/// Explicit controller reads may address any file on the selected provider. +/// Automatic output delivery and runtime artifact URIs retain their root boundary. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum FileReadScope { + Workspace, + Provider, +} + +pub fn controller_file_read_scope(reference: &str) -> Result { + Ok( + if normalize_file_reference(reference)?.starts_with("openbitfun://") { + FileReadScope::Workspace + } else { + FileReadScope::Provider + }, + ) +} + /// Assembly selects the provider and allowed root. This layer owns IO and confinement. pub struct SessionFileTarget { pub fs: Arc, @@ -62,22 +80,27 @@ fn posix_path(path: &str) -> Result { } impl SessionFileTarget { - async fn checked_path(&self) -> Result { + async fn checked_path(&self, scope: FileReadScope) -> Result { if !self.remote { - let root = tokio::fs::canonicalize(&self.root) - .await - .map_err(|e| format!("Cannot resolve file workspace: {e}"))?; let path = tokio::fs::canonicalize(&self.path) .await .map_err(|e| format!("Cannot resolve output file: {e}"))?; - if !path.starts_with(root) { - return Err("Output file is outside its session workspace".to_string()); + if scope == FileReadScope::Workspace { + let root = tokio::fs::canonicalize(&self.root) + .await + .map_err(|e| format!("Cannot resolve file workspace: {e}"))?; + if !path.starts_with(root) { + return Err("Output file is outside its session workspace".to_string()); + } } return Ok(path.to_string_lossy().into_owned()); } // Remote syntax stays POSIX even on Windows. Never probe controller paths. - let root = posix_path(&self.root)?; let path = posix_path(&self.path)?; + if scope == FileReadScope::Provider { + return Ok(path); + } + let root = posix_path(&self.root)?; if root != "/" && path != root && !path.starts_with(&format!("{root}/")) { return Err("Output file is outside its session workspace".to_string()); } @@ -96,10 +119,14 @@ impl SessionFileTarget { Ok(path) } - async fn metadata_at(&self, path: &str) -> Result { + async fn metadata_at( + &self, + path: &str, + scope: FileReadScope, + ) -> Result { let metadata = self .fs - .metadata(path, false) + .metadata(path, scope == FileReadScope::Provider) .await .map_err(|e| e.to_string())? .ok_or_else(|| "Output file not found".to_string())?; @@ -112,8 +139,13 @@ impl SessionFileTarget { Ok(metadata) } - async fn unchanged(&self, path: &str, before: &WorkspaceMetadata) -> Result<(), String> { - let after = self.metadata_at(path).await?; + async fn unchanged( + &self, + path: &str, + before: &WorkspaceMetadata, + scope: FileReadScope, + ) -> Result<(), String> { + let after = self.metadata_at(path, scope).await?; if after.size != before.size || after.modified != before.modified { return Err( "Output file changed during transfer; retry when generation finishes".to_string(), @@ -123,8 +155,15 @@ impl SessionFileTarget { } pub async fn info(&self) -> Result { - let path = self.checked_path().await?; - let metadata = self.metadata_at(&path).await?; + self.info_with_scope(FileReadScope::Workspace).await + } + + pub async fn info_with_scope( + &self, + scope: FileReadScope, + ) -> Result { + let path = self.checked_path(scope).await?; + let metadata = self.metadata_at(&path, scope).await?; // A POSIX basename is independent of the controller OS. let name = path .rsplit(if self.remote { @@ -143,8 +182,17 @@ impl SessionFileTarget { } pub async fn read(&self, max_bytes: u64) -> Result { - let path = self.checked_path().await?; - let before = self.metadata_at(&path).await?; + self.read_with_scope(max_bytes, FileReadScope::Workspace) + .await + } + + pub async fn read_with_scope( + &self, + max_bytes: u64, + scope: FileReadScope, + ) -> Result { + let path = self.checked_path(scope).await?; + let before = self.metadata_at(&path, scope).await?; let size = before.size.unwrap(); if size > max_bytes { return Err(format!( @@ -159,7 +207,7 @@ impl SessionFileTarget { .await .map_err(|e| e.to_string())? .ok_or_else(|| "Output file grew beyond the transfer limit".to_string())?; - self.unchanged(&path, &before).await?; + self.unchanged(&path, &before, scope).await?; if bytes.len() as u64 != size { return Err("Output file transfer was truncated".to_string()); } @@ -190,6 +238,17 @@ impl SessionFileTarget { .map(|(chunk, _)| chunk) } + pub async fn read_chunk_with_scope( + &self, + offset: u64, + limit: u64, + scope: FileReadScope, + ) -> Result { + self.read_chunk_with_revision_and_scope(offset, limit, None, scope) + .await + .map(|(chunk, _)| chunk) + } + /// Binds separate chunk requests to one file revision without retaining a /// stream or requiring the observer to stay connected between requests. pub async fn read_chunk_with_revision( @@ -198,8 +257,24 @@ impl SessionFileTarget { limit: u64, expected_revision: Option<&str>, ) -> Result<(RemoteWorkspaceFileChunk, String), String> { - let path = self.checked_path().await?; - let before = self.metadata_at(&path).await?; + self.read_chunk_with_revision_and_scope( + offset, + limit, + expected_revision, + FileReadScope::Workspace, + ) + .await + } + + async fn read_chunk_with_revision_and_scope( + &self, + offset: u64, + limit: u64, + expected_revision: Option<&str>, + scope: FileReadScope, + ) -> Result<(RemoteWorkspaceFileChunk, String), String> { + let path = self.checked_path(scope).await?; + let before = self.metadata_at(&path, scope).await?; let total_size = before.size.unwrap(); let modified = before .modified @@ -232,7 +307,7 @@ impl SessionFileTarget { .read_to_end(&mut bytes) .await .map_err(|e| e.to_string())?; - self.unchanged(&path, &before).await?; + self.unchanged(&path, &before, scope).await?; if bytes.len() as u64 != count { return Err("Output file chunk was truncated".to_string()); } @@ -408,6 +483,61 @@ mod tests { .contains("truncated")); } + #[tokio::test] + async fn explicit_reads_outside_workspace_keep_the_selected_remote_provider() { + let local = tempfile::tempdir().unwrap(); + let path = local.path().join("qr.png"); + std::fs::write(&path, b"controller-private").unwrap(); + let (target, fs) = fixture("/workspace", path.to_str().unwrap(), false, false); + assert!(target.read(100).await.is_err()); + let info = target + .info_with_scope(FileReadScope::Provider) + .await + .unwrap(); + assert_eq!(info.name, "qr.png"); + let file = target + .read_with_scope(100, FileReadScope::Provider) + .await + .unwrap(); + assert_eq!(file.bytes, b"remote-image"); + let chunk = target + .read_chunk_with_scope(7, 100, FileReadScope::Provider) + .await + .unwrap(); + assert_eq!(chunk.bytes, b"image"); + assert!(fs + .reads + .lock() + .unwrap() + .iter() + .all(|read| read == path.to_str().unwrap())); + assert!(target + .read_with_scope(2, FileReadScope::Provider) + .await + .is_err()); + assert!( + target.read(100).await.is_err(), + "explicit reads must not widen automatic delivery" + ); + } + + #[test] + fn controller_scope_preserves_runtime_uri_confinement() { + for reference in [ + "/tmp/wxqr/qr.png", + "computer:///tmp/wxqr/qr.png", + "../output.png", + ] { + assert!(controller_file_read_scope(reference).unwrap() == FileReadScope::Provider); + } + for reference in [ + "openbitfun://current-session/artifacts/qr.png", + "computer://openbitfun%3A%2F%2Fcurrent-session%2Fartifacts%2Fqr.png", + ] { + assert!(controller_file_read_scope(reference).unwrap() == FileReadScope::Workspace); + } + } + #[test] fn uri_paths_decode_once_and_preserve_runtime_scope() { assert_eq!( From 2d56fc82f5e5f86830073b71123719e7372eb2f6 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 31 Oct 2026 09:41:57 +0800 Subject: [PATCH 2/4] fix(mobile): align message metadata and assistant session controls --- .../mobile/app/ChatMessageBubbleTest.kt | 16 ++++++++ .../mobile/app/ConversationViewTest.kt | 1 + .../mobile/app/ui/chat/ChatMessageBubble.kt | 13 ++++++ .../mobile/app/ui/chat/tool/ToolGlyph.kt | 22 ++-------- .../mobile/app/ui/chat/tool/ToolStatusList.kt | 10 ++--- .../sidebar/SidebarRemoteWorkspaceSection.kt | 5 ++- .../components/mobile-components.json | 4 +- .../preview/generated/mobile-design-data.js | 5 ++- .../entry/src/main/ets/i18n/RemoteI18n.ets | 7 ++++ .../pages/components/ChatMessageBubble.ets | 2 + .../pages/components/ChatMessageChrome.ets | 16 ++++++++ .../pages/components/SidebarDeviceGroup.ets | 7 +++- .../ets/pages/components/ToolStatusList.ets | 22 ++-------- .../ets/pages/policy/ToolCollapsePolicy.ets | 5 ++- .../ets/services/DurableSessionReducer.ets | 4 +- .../src/main/ets/services/TimeFormat.ets | 5 +++ .../main/ets/services/WorkspaceCatalog.ets | 2 + .../ConversationPresentationUnit.test.ets | 11 ++++- .../entry/src/test/LocalTestFixtures.ets | 6 ++- .../tests/host-text-retranslator.test.cjs | 22 ++++++++++ .../tools/tests/workspace-catalog.test.cjs | 12 ++++++ .../Features/Chat/ChatTimelineView.swift | 19 +++++++-- .../DesignSystem/MobileDesignGallery.swift | 18 +++++++- .../Features/Shell/SidebarView.swift | 18 +++++--- .../MobileAppModel+GeneralChat.swift | 3 +- .../MobileAppModel+RemoteSession.swift | 11 +++-- .../Infrastructure/MobileLocalization.swift | 8 ++++ .../Models/MobilePresentationModels.swift | 7 +++- .../RemoteCodeSessionSendUITests.swift | 19 +++++++++ .../ios/Testing/MobileProcessGroupTests.swift | 7 ++-- .../session/ConversationPresentation.kt | 4 +- .../feature/session/RemoteSessionStore.kt | 2 +- .../feature/session/SessionRecordReplica.kt | 2 +- .../shell/RemoteSidebarPresentation.kt | 6 ++- .../workspace/WorkspaceCatalogUiState.kt | 3 +- .../session/ConversationPresentationTest.kt | 11 +++++ .../session/SessionRecordReplicaTest.kt | 4 +- .../session/ToolRowPresentationTest.kt | 9 ++++ .../shell/RemoteSidebarPresentationTest.kt | 11 +++++ .../feature/workspace/WorkspaceCatalogTest.kt | 14 +++++++ src/mobile-web/AGENTS.md | 1 + .../src/components/ChatTranscript.tsx | 27 ++++++++---- src/mobile-web/src/i18n/messageTime.ts | 14 +++++++ src/mobile-web/src/pages/ChatPage.tsx | 3 +- .../src/styles/components/chat.scss | 6 +++ .../mobile-chat-regressions-fixture.tsx | 31 ++++++++++++++ .../mobile-chat-regressions-browser.test.mjs | 41 +++++++++++++++++++ 47 files changed, 404 insertions(+), 92 deletions(-) create mode 100644 src/mobile-web/src/i18n/messageTime.ts create mode 100644 src/mobile-web/tests/helpers/mobile-chat-regressions-fixture.tsx create mode 100644 src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt index 296b46557e..694a2852ee 100644 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt +++ b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt @@ -39,6 +39,21 @@ class ChatMessageBubbleTest { @get:Rule val composeRule = createComposeRule() + @Test + fun userAndAssistantTimesRenderBelowTheirMessages() { + var kind by mutableStateOf(ConversationRowKind.USER) + composeRule.setContent { + Bubble(row(kind, text = "Dated message").copy(timestampMs = 1700000000000L)) + } + for (role in listOf(ConversationRowKind.USER, ConversationRowKind.ASSISTANT)) { + composeRule.runOnIdle { kind = role } + composeRule.onNodeWithTag("chat-message-timestamp").assertIsDisplayed() + val content = composeRule.onNodeWithText("Dated message").getUnclippedBoundsInRoot() + val time = composeRule.onNodeWithTag("chat-message-timestamp").getUnclippedBoundsInRoot() + assertTrue(time.top >= content.bottom) + } + } + @Test fun aTurnThatWorkedInStepsIsDrawnInSteps() { composeRule.setContent { @@ -278,6 +293,7 @@ class ChatMessageBubbleTest { showRetry = showRetry, error = null, live = false, + timestampMs = null, ) private fun runningTool(): ToolCard = ToolCard( diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt index efbd6f386d..ea3fc3221c 100644 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt +++ b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt @@ -607,6 +607,7 @@ class ConversationViewTest { showRetry = false, error = null, live = false, + timestampMs = null, ) private fun string(resource: Int): String = diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt index f75c17c4de..0e33b988e0 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt @@ -9,6 +9,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -89,6 +90,18 @@ internal fun ChatMessageBubble( MessageImageGallery(images = row.images, userStyle = false) } + row.timestampMs?.let { timestamp -> + val locale = LocalConfiguration.current.locales[0] + Text( + java.text.DateFormat.getDateTimeInstance( + java.text.DateFormat.SHORT, java.text.DateFormat.SHORT, locale, + ).format(java.util.Date(timestamp)), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("chat-message-timestamp"), + ) + } + // Two mutually exclusive footnotes about delivery: nothing has arrived // yet, or the send was refused. when { diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt index 429c67a4e1..d6dd1b0197 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt @@ -39,7 +39,7 @@ internal fun ToolStatusIcon(tool: ToolCard, modifier: Modifier) { modifier = Modifier .size(18.dp) .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(5.dp)) - .border(1.dp, badgeBorder(tool), RoundedCornerShape(5.dp)), + .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(5.dp)), contentAlignment = Alignment.Center, ) { Icon( @@ -54,7 +54,7 @@ internal fun ToolStatusIcon(tool: ToolCard, modifier: Modifier) { modifier = Modifier .align(Alignment.BottomEnd) .size(10.dp) - .background(statusTint(tool.phase), CircleShape) + .background(MaterialTheme.colorScheme.onSurfaceVariant, CircleShape) .border(1.dp, MaterialTheme.colorScheme.surface, CircleShape), contentAlignment = Alignment.Center, ) { @@ -132,25 +132,9 @@ private fun kindTint(kind: ToolKind): Color = when (kind) { else -> MaterialTheme.colorScheme.onSurfaceVariant } -@Composable -private fun badgeBorder(tool: ToolCard): Color = if (tool.phase == ToolPhase.FAILED) { - MaterialTheme.colorScheme.error -} else { - MaterialTheme.colorScheme.outlineVariant -} - private fun statusMark(phase: ToolPhase): String? = when (phase) { - ToolPhase.FAILED -> "!" ToolPhase.PENDING_CONFIRMATION -> "?" ToolPhase.RUNNING -> "•" ToolPhase.CANCELLED -> "×" - // Done and queued are the states nobody is waiting on. - ToolPhase.COMPLETED, ToolPhase.WAITING -> null -} - -@Composable -private fun statusTint(phase: ToolPhase): Color = if (phase == ToolPhase.FAILED) { - MaterialTheme.colorScheme.error -} else { - MaterialTheme.colorScheme.onSurfaceVariant + ToolPhase.COMPLETED, ToolPhase.FAILED, ToolPhase.WAITING -> null } diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt index 0d9f69a723..b80f4f5ea3 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt @@ -231,7 +231,7 @@ internal fun ToolStatusRow( (if (ToolAction.ANSWER in tool.actions) setOf(ToolAction.CANCEL) else emptySet()) } else tool.actions val blocking = transcriptActions.isNotEmpty() - val emphasized = expanded || blocking || tool.phase == ToolPhase.FAILED + val emphasized = expanded || blocking val canExpand = tool.expandable val openable = tool.filePath.isNotEmpty() @@ -268,7 +268,6 @@ internal fun ToolStatusRow( toolLineLabel(tool), style = MaterialTheme.typography.bodySmall, color = when { - tool.phase == ToolPhase.FAILED -> MaterialTheme.colorScheme.error openable -> MaterialTheme.colorScheme.primary else -> MaterialTheme.colorScheme.onSurfaceVariant }, @@ -442,8 +441,8 @@ private fun TodoToolCard(tool: ToolCard, enabled: Boolean, modifier: Modifier) { * The row's one line, ported from `toolLineLabel`. * * What it leads with is what the reader wants first, and that changes with the - * state: a running tool leads with the thing it is working on, a failed one with - * the failure, and anything waiting on the user with the fact that it is. + * state: a running tool leads with the thing it is working on, and anything + * waiting on the user with the fact that it is. Failures remain in the details. */ @Composable private fun toolLineLabel(tool: ToolCard): String { @@ -453,9 +452,6 @@ private fun toolLineLabel(tool: ToolCard): String { tool.phase == ToolPhase.RUNNING -> stringResource(R.string.tool_line_running, target.ifEmpty { operation }) - tool.phase == ToolPhase.FAILED -> - join(stringResource(R.string.tool_line_failed, operation), target) - tool.phase == ToolPhase.PENDING_CONFIRMATION || ToolAction.ANSWER in tool.actions -> join(stringResource(R.string.tool_phase_pending), operation) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt index 8aa0478b7a..fc0504dfa9 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt @@ -386,7 +386,10 @@ private fun SidebarActiveDeviceBody( modesOnly = true, path = path, expanded = createMenuOpen, - onToggle = { createMenuOpen = !createMenuOpen }, + onToggle = { + if (entry.kind == "assistant") onCreateInWorkspace(entry, "claw") + else createMenuOpen = !createMenuOpen + }, onDismiss = { createMenuOpen = false }, onCreateAgent = { agent -> createMenuOpen = false; onCreateInWorkspace(entry, agent) }, ) diff --git a/src/apps/mobile/design-system/components/mobile-components.json b/src/apps/mobile/design-system/components/mobile-components.json index e759987a6d..c1244a0b62 100644 --- a/src/apps/mobile/design-system/components/mobile-components.json +++ b/src/apps/mobile/design-system/components/mobile-components.json @@ -66,10 +66,10 @@ }, "message_bubble": { "purpose": "Presents one user or assistant message in the conversation timeline.", - "anatomy": ["message_text", "role_surface", "hairline_border"], + "anatomy": ["message_text", "role_surface", "hairline_border", "message_timestamp"], "states": ["user", "assistant"], "tokens": ["body_large", "message_bubble_max_width", "message_bubble_horizontal_padding", "message_bubble_vertical_padding", "message_bubble_radius", "message_spacing", "timeline_top_padding"], - "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy." + "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy. Show each available host message time below its content in localized short date/time with muted label-small text, right aligned for users and left aligned for assistants. Omit unavailable or invalid legacy timestamps. Ordinary failed tool calls share the neutral collapsed activity presentation; their actual failure details remain expandable. Questions, approvals and failed replies retain their attention states." }, "conversation_overlay": { "purpose": "Lets the transcript own the whole pane while the header and composer stay reachable above it.", diff --git a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js b/src/apps/mobile/design-system/preview/generated/mobile-design-data.js index 84f7378e77..1c76a85aec 100644 --- a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js +++ b/src/apps/mobile/design-system/preview/generated/mobile-design-data.js @@ -667,7 +667,8 @@ export const mobileComponents = { "anatomy": [ "message_text", "role_surface", - "hairline_border" + "hairline_border", + "message_timestamp" ], "states": [ "user", @@ -682,7 +683,7 @@ export const mobileComponents = { "message_spacing", "timeline_top_padding" ], - "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy." + "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy. Show each available host message time below its content in localized short date/time with muted label-small text, right aligned for users and left aligned for assistants. Omit unavailable or invalid legacy timestamps. Ordinary failed tool calls share the neutral collapsed activity presentation; their actual failure details remain expandable. Questions, approvals and failed replies retain their attention states." }, "conversation_overlay": { "purpose": "Lets the transcript own the whole pane while the header and composer stay reachable above it.", diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets index be35260dee..845be95928 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets @@ -94,6 +94,13 @@ export class RemoteI18n { return []; } + static formatMessageTime(timestamp: number): string { + const locale = RemoteI18n.language() === APP_LOCALE_EN_US ? 'en-US' : 'zh-CN'; + return new intl.DateTimeFormat(locale, { + year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' + }).format(new Date(timestamp)); + } + static formatAbsoluteDate(timestamp: number): string { const locale = RemoteI18n.language() === APP_LOCALE_EN_US ? 'en-US' : 'zh-CN'; const formatter = new intl.DateTimeFormat(locale, { diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets index ecf36e3cc4..273033ef9e 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets @@ -13,6 +13,7 @@ import { MessageBodyMarkdown, MessageFileCards, MessageImageGallery, MessageMark import { AssistantMessageCopyAction, ChatMessageRetryAction, + ChatMessageTimestamp, ChatTypingDots, ChatUserMessageBubble } from './ChatMessageChrome'; @@ -156,6 +157,7 @@ export struct ChatMessageBubble { this.showRetryAction ? (this.item.detail || '') : '' ) } + ChatMessageTimestamp({ timestamp: this.item.timestamp || '' }) this.ActionRow() } .layoutWeight(1) diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets index 976f7dec3d..bb50087fc8 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets @@ -1,3 +1,4 @@ +import { TimeFormat } from '../../services/TimeFormat'; import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; import { RemoteI18n } from '../../i18n/RemoteI18n'; import { MessageCopyScope } from '../actions/ConversationIntent'; @@ -155,6 +156,7 @@ export struct ChatUserMessageBubble { .borderRadius(MobileDesignGeometry.messageBubbleRadius) .alignItems(HorizontalAlign.Start) } + ChatMessageTimestamp({ timestamp: this.item.timestamp || '' }) if (this.item.status === 'failed' && this.showRetryAction) { ChatMessageRetryAction({ retryText: this.item.text, onRetry: this.onRetryMessage }) } @@ -349,3 +351,17 @@ export struct AssistantMessageCopyAction { return scope === MessageCopyScope.Plain ? MarkdownParser.formatInlineText(this.source) : this.source; } } + +@ComponentV2 +export struct ChatMessageTimestamp { + @Param timestamp: string = ''; + + build() { + if (TimeFormat.message(this.timestamp).length > 0) { + Text(TimeFormat.message(this.timestamp)) + .fontSize(MobileDesignTypography.labelSmall.size) + .fontColor(MUTED) + .id('chat-message-timestamp') + } + } +} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets index e61d1571ad..89e05ff221 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets @@ -184,7 +184,12 @@ struct SidebarWorkspaceGroup { } }) .onClick(() => { - this.showCreateMenu = !this.showCreateMenu; + if (this.workspaceKind === 'assistant') { + this.showCreateMenu = false; + this.onCreateInWorkspace(this.path, 'claw', this.connectionId, this.sshHost, this.workspaceIdOrUndefined()); + } else { + this.showCreateMenu = !this.showCreateMenu; + } }) } .width('100%') diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets index 8ed9d4932f..e02a3f5436 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets @@ -225,8 +225,7 @@ export struct ToolStatusList { this.ToolStatusIcon(tool) Text(this.toolLineLabel(tool)) .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.hasToolError(tool) ? STATUS_DANGER : - (this.toolFilePath(tool).length > 0 ? FILE_LINK : MUTED)) + .fontColor(this.toolFilePath(tool).length > 0 ? FILE_LINK : MUTED) .layoutWeight(1) .maxLines(1) .textOverflow({ overflow: TextOverflow.Ellipsis }) @@ -502,7 +501,6 @@ export struct ToolStatusList { private isEmphasizedToolRow(tool: ConversationUiToolStatus, index: number): boolean { return this.expandedToolKey === this.toolKey(tool, index) || - this.hasToolError(tool) || this.isPendingConfirmation(tool) || this.isQuestionTool(tool) || this.isRunningTool(tool); @@ -852,14 +850,10 @@ export struct ToolStatusList { if (this.isRunningTool(tool)) { return `${RemoteI18n.t('chat.toolRunning')} “${this.compactText(this.operationTarget(tool), 24)}”`; } - if (this.hasToolError(tool)) { - return `${RemoteI18n.f('chat.toolFailed', this.operationLabel(tool))} · ` + - `${this.compactText(this.operationTarget(tool), 24)}`; - } if (this.isPendingConfirmation(tool) || this.isQuestionTool(tool)) { return `${this.displayStatus(tool.status || 'pending')} · ${this.operationLabel(tool)}`; } - if (this.isCompletedTool(tool) || this.isCancelledTool(tool)) { + if (this.isCompletedTool(tool) || this.isCancelledTool(tool) || this.hasToolError(tool)) { return `${this.operationLabel(tool)} · ${this.compactText(this.operationTarget(tool), 28)}`; } return `${this.displayStatus(tool.status || 'pending')} · ${this.operationLabel(tool)}`; @@ -915,16 +909,10 @@ export struct ToolStatusList { } private toolTypeBorderColor(tool: ConversationUiToolStatus): ResourceColor { - if (this.hasToolError(tool)) { - return STATUS_DANGER; - } return LINE; } private toolStatusIcon(tool: ConversationUiToolStatus): string { - if (this.hasToolError(tool)) { - return '!'; - } const normalized = (tool.status || '').toLowerCase(); if (normalized === 'running' || normalized === 'active') { return '•'; @@ -939,15 +927,11 @@ export struct ToolStatusList { } private toolStatusColor(tool: ConversationUiToolStatus): ResourceColor { - if (this.hasToolError(tool)) { - return STATUS_DANGER; - } return MUTED; } private shouldShowStatusBadge(tool: ConversationUiToolStatus): boolean { - return this.hasToolError(tool) || - this.isPendingConfirmation(tool) || + return this.isPendingConfirmation(tool) || this.isQuestionTool(tool) || this.isRunningTool(tool) || this.isCancelledTool(tool); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets index c89ab5cdf1..36b0b7c7b7 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets @@ -17,13 +17,14 @@ export class ToolCollapsePolicy { static readonly MIN_SUMMARY_COUNT: number = 2; static shouldFoldIntoSummary(tool: ConversationUiToolStatus): boolean { - if (PlanToolPolicy.isPlanTool(tool) || ToolCollapsePolicy.hasError(tool) || + if (PlanToolPolicy.isPlanTool(tool) || ToolCollapsePolicy.isPending(tool) || ToolCollapsePolicy.isQuestion(tool) || ToolCollapsePolicy.isRunning(tool)) { return false; } - return ToolCollapsePolicy.isCompleted(tool) || ToolCollapsePolicy.isCancelled(tool); + return ToolCollapsePolicy.isCompleted(tool) || ToolCollapsePolicy.isCancelled(tool) || + ToolCollapsePolicy.hasError(tool); } static collapsedGroups(tools: ConversationUiToolStatus[]): ToolCollapseGroup[] { diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets index 2cc1a18604..ccb2a444a2 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets @@ -168,7 +168,7 @@ export class DurableSessionReducer { const metadata = turn.userMessage.metadata as UserMetadata | undefined; const userText = metadata?.original_text || turn.userMessage.content; if (userText.length > 0 || (metadata?.images?.length || 0) > 0) result.push({ id: turn.userMessage.id, turnId: turn.turnId, - role: 'user', text: userText, images: metadata?.images, status: 'sent', timestamp: new Date(turn.userMessage.timestamp).toISOString() }); + role: 'user', text: userText, images: metadata?.images, status: 'sent', timestamp: String(turn.userMessage.timestamp) }); const turnFence = this.tombstones.get(`turn/${turn.turnId}`) ?? 0; const visible = entries.filter((item: StoredItem) => { const round = this.rounds.get(item.roundId); @@ -201,7 +201,7 @@ export class DurableSessionReducer { result.push({ id: `assistant-${turn.turnId}`, turnId: turn.turnId, role: 'assistant', status: status, text: items.filter((item: ChatMessageItemResponse) => item.type === 'text' && !item.is_subagent).map((item: ChatMessageItemResponse) => item.content || '').join(''), thinking: items.filter((item: ChatMessageItemResponse) => item.type === 'thinking' && !item.is_subagent).map((item: ChatMessageItemResponse) => item.content || '').join(''), - tools: tools, items: items, timestamp: new Date(turn.timestamp).toISOString(), error: turn.error, renderVersion: stored.revision }); + tools: tools, items: items, timestamp: String(turn.timestamp), error: turn.error, renderVersion: stored.revision }); return result; } } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets index 03734bdbd5..ba13739891 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets @@ -1,6 +1,11 @@ import { RemoteI18n } from '../i18n/RemoteI18n'; export class TimeFormat { + static message(value: string): string { + const timestamp = TimeFormat.timestampMs(value); + return Number.isFinite(new Date(timestamp).getTime()) ? RemoteI18n.formatMessageTime(timestamp) : ''; + } + static relative(value: string, nowMs: number = Date.now()): string { const timestamp = TimeFormat.timestampMs(value); if (Number.isNaN(timestamp)) { diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets index b4f3c0983b..d3c9b4d67d 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets @@ -35,6 +35,8 @@ export function projectWorkspaceCatalog( remoteConnectionId: row.remoteConnectionId, remoteSshHost: row.remoteSshHost }); }); + workspaces.sort((left: RecentWorkspaceEntry, right: RecentWorkspaceEntry): number => + Number(right.workspaceKind === 'assistant') - Number(left.workspaceKind === 'assistant')); return { workspaces, recentWorkspaces: recent, source: opened ? 'opened' : 'recent' }; } diff --git a/src/apps/mobile/harmonyos/entry/src/test/ConversationPresentationUnit.test.ets b/src/apps/mobile/harmonyos/entry/src/test/ConversationPresentationUnit.test.ets index d968c90e66..f29485b19f 100644 --- a/src/apps/mobile/harmonyos/entry/src/test/ConversationPresentationUnit.test.ets +++ b/src/apps/mobile/harmonyos/entry/src/test/ConversationPresentationUnit.test.ets @@ -581,6 +581,15 @@ export default function conversationPresentationUnitTest() { }); describe('ToolCollapsePolicy', () => { + it('folds failed calls with completed work and retains error details', 0, () => { + const failed = toolStatus('failed', 'WebFetch', 'failed'); + failed.error_preview = 'HTTP 404'; + const groups = ToolCollapsePolicy.collapsedGroups([toolStatus('read', 'Read', 'completed'), failed]); + expect(groups.length).assertEqual(1); + expect(groups[0].type).assertEqual('summary'); + expect(groups[0].tools[1].error_preview).assertEqual('HTTP 404'); + }); + it('folds consecutive completed tools of any kind into one summary', 0, () => { const groups = ToolCollapsePolicy.collapsedGroups([ toolStatus('1', 'Grep', 'completed'), @@ -618,7 +627,7 @@ export default function conversationPresentationUnitTest() { expect(PlanToolPolicy.canBuild(planTool)).assertTrue(); }); - it('does not fold running, failed, or blocking tools into the summary', 0, () => { + it('does not fold running or blocking tools into the summary', 0, () => { const groups = ToolCollapsePolicy.collapsedGroups([ toolStatus('1', 'Grep', 'completed'), toolStatus('2', 'Read', 'completed'), diff --git a/src/apps/mobile/harmonyos/entry/src/test/LocalTestFixtures.ets b/src/apps/mobile/harmonyos/entry/src/test/LocalTestFixtures.ets index bf8b9bc8bc..e6f22a7f6d 100644 --- a/src/apps/mobile/harmonyos/entry/src/test/LocalTestFixtures.ets +++ b/src/apps/mobile/harmonyos/entry/src/test/LocalTestFixtures.ets @@ -1,7 +1,7 @@ import { WorkspaceCatalog, mergeLegacyWorkspaces } from '../main/ets/services/WorkspaceCatalog'; import { HostSessionStream, HostSessionCallbacks, HostSessionEvent, HostSessionSource, HostStreamPage } from '../main/ets/services/HostSessionStream'; import { SessionRecord } from '../main/ets/services/DurableSessionReducer'; -import { SavedRuntimeConnection } from '../main/ets/model/RemoteModels'; +import { SavedRuntimeConnection, SessionRolledBackResult } from '../main/ets/model/RemoteModels'; import { describe, it, expect } from '@ohos/hypium'; import { RemoteI18n } from '../main/ets/i18n/RemoteI18n'; import { ChatSessionController, ChatSessionSnapshot } from '../main/ets/services/ChatSessionController'; @@ -912,6 +912,10 @@ export class RemoteSessionProjectionRecord { } export class FakeRemoteChatCommandClient implements RemoteChatCommandClient { + async rollbackSessionToTurn(): Promise { + throw new Error('Unexpected rollback in chat command fixture'); + } + messageResults: SessionMessagesResult[] = []; messageRequests: string[] = []; messageResolvers: Array<(result: SessionMessagesResult) => void> = []; diff --git a/src/apps/mobile/harmonyos/tools/tests/host-text-retranslator.test.cjs b/src/apps/mobile/harmonyos/tools/tests/host-text-retranslator.test.cjs index c7322ecfe2..a1d72766ff 100644 --- a/src/apps/mobile/harmonyos/tools/tests/host-text-retranslator.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/host-text-retranslator.test.cjs @@ -169,3 +169,25 @@ test('shared runtime refresh preserves workspace identity and refreshes download assert.equal(state.workspaceName, 'Not connected'); } }); + + +test('message times preserve legacy scales, omit invalid values, and follow the active locale', () => { + const { remote } = load(); + const source = fs.readFileSync(path.join(root, 'ets/services/TimeFormat.ets'), 'utf8'); + const compiled = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } + }).outputText; + const exports = {}; + new Function('require', 'exports', compiled)(() => ({ RemoteI18n: remote }), exports); + const { TimeFormat } = exports; + for (const locale of ['zh-CN', 'en-US']) { + remote.setLanguage(locale); + const expected = new Intl.DateTimeFormat(locale, { + year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' + }).format(new Date(1700000000000)); + for (const timestamp of ['1700000000', '1700000000000', '1700000000000000', '1700000000000000000', '2023-11-14T22:13:20.000Z']) { + assert.equal(TimeFormat.message(timestamp), expected); + } + for (const timestamp of ['', 'invalid', '9'.repeat(30)]) assert.equal(TimeFormat.message(timestamp), ''); + } +}); diff --git a/src/apps/mobile/harmonyos/tools/tests/workspace-catalog.test.cjs b/src/apps/mobile/harmonyos/tools/tests/workspace-catalog.test.cjs index f7df7eccc2..76f70e6736 100644 --- a/src/apps/mobile/harmonyos/tools/tests/workspace-catalog.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/workspace-catalog.test.cjs @@ -110,3 +110,15 @@ test('1.0.0 localhost markers follow workspace kind without losing real SSH iden assert.equal(catalog.workspaces[1].remoteSshHost, 'localhost'); assert.equal(catalog.workspaces[1].remoteConnectionId, 'saved'); }); + +test('opened assistants are pinned with stable ordering and unchanged picker history', () => { + const catalog = projectWorkspaceCatalog({ workspaces: [{path: '/recent'}], opened_workspaces: [ + { workspace_id: 'remote', path: '/repo', workspace_kind: 'remote', remote_connection_id: 'ssh' }, + { workspace_id: 'a', path: '/assistant-a', workspace_kind: 'assistant' }, + { workspace_id: 'local', path: '/local', workspace_kind: 'normal' }, + { workspace_id: 'b', path: '/assistant-b', workspace_kind: 'assistant' }, + ] }, []); + assert.deepEqual(catalog.workspaces.map(row => row.workspaceId), ['a', 'b', 'remote', 'local']); + assert.equal(catalog.workspaces[2].remoteConnectionId, 'ssh'); + assert.deepEqual(catalog.recentWorkspaces.map(row => row.path), ['/recent']); +}); diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift index 4e2a797a15..cfc1aa57ec 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift @@ -327,6 +327,7 @@ private struct ConversationRowView: View, Equatable { .background(OpenBitFunTheme.soft) .clipShape(RoundedRectangle(cornerRadius: MobileDesignGeometry.messageBubbleRadius)) } + messageTimestamp if row.showRetry { Button { model.retryMessage(row.text, images: row.images) } label: { Label(model.localized("重新发送"), systemImage: "arrow.clockwise") @@ -364,10 +365,21 @@ private struct ConversationRowView: View, Equatable { } .buttonStyle(.plain) } + messageTimestamp } .frame(maxWidth: .infinity, alignment: .leading) } + @ViewBuilder + private var messageTimestamp: some View { + if let timestamp = row.timestamp { + Text(MobileLocalization.messageTime(timestamp, language: model.appLanguage)) + .font(MobileDesignTypography.labelSmall.font) + .foregroundStyle(OpenBitFunTheme.muted) + .accessibilityIdentifier("chat.messageTimestamp") + } + } + private func assistantFailure(_ error: String) -> some View { VStack(alignment: .leading, spacing: 6) { Text(model.localized("本次回复失败")) @@ -1356,7 +1368,7 @@ private struct ToolStatusRow: View { .subtracting(tool.actions.contains("ANSWER") ? ["CANCEL"] : []) } - private var emphasized: Bool { !transcriptActions.isEmpty || expanded || tool.phase == "FAILED" } + private var emphasized: Bool { !transcriptActions.isEmpty || expanded } var mailboxQuestion = false @@ -1638,7 +1650,6 @@ private struct ToolStatusRow: View { let target = tool.target.isEmpty ? "" : " · \(tool.target)" return switch tool.phase { case "RUNNING": model.localizedFormat("正在%@%@", operationLabel, target) - case "FAILED": model.localizedFormat("%@失败%@", operationLabel, target) case "PENDING_CONFIRMATION": model.localizedFormat("等待确认 · %@", operationLabel) case "WAITING": model.localizedFormat("等待执行 · %@", operationLabel) default: "\(operationLabel)\(target)" @@ -1665,11 +1676,11 @@ private struct ToolStatusRow: View { } private var statusColor: Color { - switch tool.phase { case "FAILED": OpenBitFunTheme.statusDanger; case "COMPLETED": OpenBitFunTheme.statusSuccess; default: OpenBitFunTheme.muted } + switch tool.phase { case "COMPLETED": OpenBitFunTheme.statusSuccess; default: OpenBitFunTheme.muted } } private var statusMark: String { - switch tool.phase { case "FAILED": "!"; case "PENDING_CONFIRMATION": "?"; case "CANCELLED": "×"; case "COMPLETED": "✓"; default: "•" } + switch tool.phase { case "PENDING_CONFIRMATION": "?"; case "CANCELLED": "×"; case "COMPLETED": "✓"; default: "•" } } } diff --git a/src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/MobileDesignGallery.swift b/src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/MobileDesignGallery.swift index 805cfc1dbe..8ba87a380f 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/MobileDesignGallery.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/MobileDesignGallery.swift @@ -178,6 +178,22 @@ struct StreamingRegressionView: View { } model.selectedSessionID = "fixture" model.timelineRows = ProcessInfo.processInfo.arguments.contains("--card-regression") ? [cardRow] : history + if ProcessInfo.processInfo.arguments.contains("--message-metadata-regression") { + let failed = MobileTimelineTool(id: "fetch", name: "WebFetch", phase: "FAILED", kind: "WEB", + operation: "FETCH_URL", target: "example.com", filePath: "", fileLabel: "", + input: "https://example.com", output: "HTTP 404", question: nil, questions: [], actions: [], foldIntoSummary: true) + let completed = MobileTimelineTool(id: "read", name: "Read", phase: "COMPLETED", kind: "FILE", + operation: "READ_FILE", target: "README.md", filePath: "", fileLabel: "", + input: "README.md", output: "Document content", question: nil, questions: [], actions: [], foldIntoSummary: true) + model.timelineRows = [ + MobileConversationRow(id: "dated-user", kind: "USER", text: "Check the sources.", thinking: nil, + images: [], tools: [], blocks: [], streaming: false, typing: false, showRetry: false, error: nil, + timestamp: Date(timeIntervalSince1970: 1700000000)), + MobileConversationRow(id: "dated-assistant", kind: "ASSISTANT", text: "The remaining source confirms the result.", thinking: nil, + images: [], tools: [completed, failed], blocks: [], streaming: false, typing: false, showRetry: false, error: nil, + timestamp: Date(timeIntervalSince1970: 1700000010)) + ] + } } .task(id: generation) { guard generation > 0 else { return } @@ -238,7 +254,7 @@ struct StreamingRegressionView: View { func tool(_ id: String, phase: String = "COMPLETED") -> MobileTimelineTool { MobileTimelineTool(id: id, name: "Read", phase: phase, kind: "FILE", operation: "READ", target: id, filePath: "", fileLabel: "", input: "INPUT-\(id)", output: "OUTPUT-\(id)", - question: nil, questions: [], actions: [], foldIntoSummary: phase == "COMPLETED") + question: nil, questions: [], actions: [], foldIntoSummary: phase == "COMPLETED" || phase == "FAILED") } if ProcessInfo.processInfo.arguments.contains("--subagent-detail-regression") { return MobileConversationRow(id: "subtask-details", kind: "ASSISTANT", text: "", thinking: nil, diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarView.swift b/src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarView.swift index edd2296086..bde877ea62 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarView.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarView.swift @@ -440,7 +440,8 @@ struct SidebarView: View { directoryExpanded: workspace.directoryExpanded, directoryStatus: workspace.directoryStatus, remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost + remoteSshHost: workspace.remoteSshHost, + kind: workspace.kind ) SidebarWorkspaceRow( workspace: scopedWorkspace, @@ -455,8 +456,12 @@ struct SidebarView: View { ) }, onToggleCreate: { - workspaceCreateTarget = scopedWorkspace - workspaceCreatePath = scopedWorkspace.scopeKey + if scopedWorkspace.kind == "assistant" { + model.openDirectoryRemoteDraft(device: device, workspace: scopedWorkspace, agentType: "claw") + } else { + workspaceCreateTarget = scopedWorkspace + workspaceCreatePath = scopedWorkspace.scopeKey + } }, onOpenWorkspace: { model.selectDirectoryWorkspace(scopedWorkspace) }, onOpenSession: { model.selectDirectorySession($0) }, onActions: { session in @@ -560,7 +565,7 @@ struct SidebarView: View { return sources.map { source in MobileWorkspaceGroup(workspaceId: source.workspaceId, path: source.path, name: source.name, selected: source.selected, sessions: section.sessions, deviceKey: normalizedDeviceKey(model.remoteExpectedDeviceKey), - remoteConnectionId: source.remoteConnectionId, remoteSshHost: source.remoteSshHost) + remoteConnectionId: source.remoteConnectionId, remoteSshHost: source.remoteSshHost, kind: source.kind) } } return ForEach(workspaces) { workspace in @@ -577,7 +582,9 @@ struct SidebarView: View { } }, onToggleCreate: { - if HarnessProfilePolicy.shared.supported(capabilities: model.remoteHostCapabilities) { + if workspace.kind == "assistant" { + model.createRemoteSession(in: workspace, agentType: "claw") + } else if HarnessProfilePolicy.shared.supported(capabilities: model.remoteHostCapabilities) { workspaceCreatePath = workspaceCreatePath == workspace.scopeKey ? nil : workspace.scopeKey } else { model.createRemoteSession(in: workspace, agentType: "code") @@ -806,6 +813,7 @@ struct SidebarView: View { } private func directoryCreateMenu(device: MobileDeviceDirectoryEntry, workspace: MobileWorkspaceGroup) -> AnyView? { + if workspace.kind == "assistant" { return nil } // Capabilities belong to the connected target, never another directory device. guard model.remoteExpectedDeviceKey == "account:\(device.id)", HarnessProfilePolicy.shared.supported(capabilities: model.remoteHostCapabilities) else { return nil } diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+GeneralChat.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+GeneralChat.swift index c0bd384a0a..386c6807f9 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+GeneralChat.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+GeneralChat.swift @@ -114,7 +114,8 @@ extension MobileAppModel { typing: row.typing, showRetry: row.showRetry, error: row.error, - live: row.live + live: row.live, + timestamp: row.timestampMs.map { Date(timeIntervalSince1970: $0.doubleValue / 1000) } ) } diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift index d9b55b8d98..92b323eae9 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift @@ -171,7 +171,8 @@ extension MobileAppModel { directoryExpanded: directory?.expanded ?? false, directoryStatus: directory?.status.name ?? "IDLE", remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost + remoteSshHost: workspace.remoteSshHost, + kind: workspace.kind ) } return MobileDeviceDirectoryEntry( @@ -186,7 +187,7 @@ extension MobileAppModel { recentWorkspaces: entry.recentWorkspaces.map { workspace in MobileWorkspaceGroup(workspaceId: workspace.workspaceId, path: workspace.path, name: workspace.displayName, selected: false, sessions: [], deviceKey: deviceKey, - remoteConnectionId: workspace.remoteConnectionId, remoteSshHost: workspace.remoteSshHost) + remoteConnectionId: workspace.remoteConnectionId, remoteSshHost: workspace.remoteSshHost, kind: workspace.kind) } ) } @@ -811,7 +812,8 @@ extension MobileAppModel { directoryExpanded: workspace.directoryExpanded, directoryStatus: workspace.directoryStatus, remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost + remoteSshHost: workspace.remoteSshHost, + kind: workspace.kind ) }, sessions: device.sessions.filter { !succeeded.contains($0.id) }, @@ -1371,7 +1373,8 @@ extension MobileAppModel { selected: workspace.selected, sessions: remoteSessions.filter { ownedIDs.contains($0.id) }, remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost + remoteSshHost: workspace.remoteSshHost, + kind: workspace.kind ) } setPublishedIfChanged(\.remoteWorkspaces, to: projectedWorkspaces) diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileLocalization.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileLocalization.swift index 557da6d5aa..4ebe98ca1d 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileLocalization.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileLocalization.swift @@ -17,6 +17,14 @@ enum MobileLanguage: String, CaseIterable, Identifiable { enum MobileLocalization { static let preferenceKey = "openbitfun.mobile.language" + static func messageTime(_ date: Date, language: MobileLanguage) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: language.rawValue) + formatter.dateStyle = .short + formatter.timeStyle = .short + return formatter.string(from: date) + } + static func restoredLanguage() -> MobileLanguage { if let saved = UserDefaults.standard.string(forKey: preferenceKey), let language = MobileLanguage(rawValue: saved) { diff --git a/src/apps/mobile/ios/OpenBitFun/Presentation/Models/MobilePresentationModels.swift b/src/apps/mobile/ios/OpenBitFun/Presentation/Models/MobilePresentationModels.swift index 6a8fb008d7..9b72bfc35a 100644 --- a/src/apps/mobile/ios/OpenBitFun/Presentation/Models/MobilePresentationModels.swift +++ b/src/apps/mobile/ios/OpenBitFun/Presentation/Models/MobilePresentationModels.swift @@ -187,10 +187,11 @@ final class MobileConversationRow: Identifiable, Equatable { let showRetry: Bool let error: String? let live: Bool + let timestamp: Date? init(id: String, kind: String, text: String, thinking: String?, images: [MobileTimelineImage], tools: [MobileTimelineTool], blocks: [MobileTimelineBlock], streaming: Bool, typing: Bool, - showRetry: Bool, error: String?, live: Bool = false) { + showRetry: Bool, error: String?, live: Bool = false, timestamp: Date? = nil) { self.id = nativeTimelineString(id) self.kind = nativeTimelineString(kind) self.text = nativeTimelineString(text) @@ -203,6 +204,7 @@ final class MobileConversationRow: Identifiable, Equatable { self.showRetry = showRetry self.error = error.map(nativeTimelineString) self.live = live + self.timestamp = timestamp } static func == (lhs: MobileConversationRow, rhs: MobileConversationRow) -> Bool { lhs === rhs } @@ -212,7 +214,7 @@ final class MobileConversationRow: Identifiable, Equatable { return id == other.id && kind == other.kind && text == other.text && thinking == other.thinking && images == other.images && tools == other.tools && blocks == other.blocks && streaming == other.streaming && typing == other.typing && - showRetry == other.showRetry && error == other.error && live == other.live + showRetry == other.showRetry && error == other.error && live == other.live && timestamp == other.timestamp } static func reconcile(_ incoming: [MobileConversationRow], with current: [MobileConversationRow]) -> [MobileConversationRow] { @@ -455,6 +457,7 @@ struct MobileWorkspaceGroup: Identifiable, Equatable { var directoryStatus = "IDLE" var remoteConnectionId: String? = nil var remoteSshHost: String? = nil + var kind: String = "normal" var scope: MobileWorkspaceScope { MobileWorkspaceScope(path: path, remoteConnectionId: remoteConnectionId, remoteSshHost: remoteSshHost, workspaceId: workspaceId) diff --git a/src/apps/mobile/ios/OpenBitFunUITests/RemoteCodeSessionSendUITests.swift b/src/apps/mobile/ios/OpenBitFunUITests/RemoteCodeSessionSendUITests.swift index 2a16384d00..21ccd628f4 100644 --- a/src/apps/mobile/ios/OpenBitFunUITests/RemoteCodeSessionSendUITests.swift +++ b/src/apps/mobile/ios/OpenBitFunUITests/RemoteCodeSessionSendUITests.swift @@ -948,6 +948,25 @@ private extension XCUIApplication { } final class StreamingPresentationUITests: XCTestCase { + func testMessageTimesAndQuietFailures() { + let app = XCUIApplication() + app.launchArguments = ["--streaming-regression", "--message-metadata-regression"] + app.launch() + let timestamps = app.staticTexts.matching(identifier: "chat.messageTimestamp") + XCTAssertTrue(timestamps.firstMatch.waitForExistence(timeout: 15)) + XCTAssertEqual(timestamps.count, 2) + let summary = app.buttons["tool.summary.read"] + XCTAssertTrue(summary.exists) + XCTAssertFalse(app.buttons["tool.toggle.fetch"].exists) + summary.tap() + app.buttons["tool.toggle.fetch"].tap() + XCTAssertTrue(app.staticTexts["HTTP 404"].waitForExistence(timeout: 3)) + let capture = XCTAttachment(screenshot: app.screenshot()) + capture.name = "Message times and expandable tool failure" + capture.lifetime = .keepAlways + add(capture) + } + func testCollapsedDraftKeepsTextAndShowsVoiceOnlyWhenExpanded() { let app = XCUIApplication() app.launchArguments = ["--composer-draft-preview"] diff --git a/src/apps/mobile/ios/Testing/MobileProcessGroupTests.swift b/src/apps/mobile/ios/Testing/MobileProcessGroupTests.swift index d36e8f65f9..1c25b4157c 100644 --- a/src/apps/mobile/ios/Testing/MobileProcessGroupTests.swift +++ b/src/apps/mobile/ios/Testing/MobileProcessGroupTests.swift @@ -11,16 +11,17 @@ struct MobileProcessGroupTests { static func snapshotTests() { func row(_ id: String = "row", text: String = "body", blocks: [MobileTimelineBlock] = [], tools: [MobileTimelineTool] = [], live: Bool = false, - error: String? = nil) -> MobileConversationRow { + error: String? = nil, timestamp: Date? = nil) -> MobileConversationRow { MobileConversationRow(id: id, kind: "ASSISTANT", text: text, thinking: nil, images: [], tools: tools, blocks: blocks, streaming: live, typing: false, - showRetry: error != nil, error: error, live: live) + showRetry: error != nil, error: error, live: live, timestamp: timestamp) } let original = row() let same = row() precondition(original != same, "View equality must compare identity without scanning content") precondition(MobileConversationRow.reconcile([same], with: [original])[0] === original) for changed in [row(text: "edited"), row(live: true), row(error: "failed"), + row(timestamp: Date(timeIntervalSince1970: 1700000000)), row(blocks: [.thinking(id: "thought", text: "Updated", streaming: true)]), row(tools: [tool("new")])] { precondition(MobileConversationRow.reconcile([changed], with: [original])[0] === changed, @@ -61,7 +62,7 @@ struct MobileProcessGroupTests { let live = MobileTimelineBlock.tools(id: "live", tools: [tool("running", fold: false)]) let blocked = MobileProcessGroup.project([thought, first, live, between, last]) precondition(blocked.count == 3 && blocked.allSatisfy { !$0.hasSummary }, - "Running/failed/approval/question/plan tools must break completed activity groups") + "Running/approval/question/plan tools must break completed activity groups") let child = MobileTimelineBlock.subagent(id: "task", title: "Task", running: true, text: "", children: []) precondition(MobileProcessGroup.project([first, child, last]).count == 3) let growing = MobileProcessGroup.project([thought, first, between, last, diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentation.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentation.kt index 93f0a1fefb..c95630bf08 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentation.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentation.kt @@ -94,7 +94,7 @@ public data class ToolCard public constructor( public val foldIntoSummary: Boolean get() { if (actions.isNotEmpty() || kind == ToolKind.QUESTION) return false - if (phase != ToolPhase.COMPLETED && phase != ToolPhase.CANCELLED) return false + if (phase !in setOf(ToolPhase.COMPLETED, ToolPhase.CANCELLED, ToolPhase.FAILED)) return false val normalizedName = name.filterNot { it == '_' || it == '-' || it.isWhitespace() }.lowercase() val planWrite = normalizedName in setOf("write", "writefile", "createfile") && filePath.lowercase().endsWith(".plan.md") @@ -166,6 +166,7 @@ public data class ConversationRow public constructor( public val error: String?, /** This is the current turn, including its finalizing snapshot before persistence. */ public val live: Boolean, + public val timestampMs: Long?, ) /** @@ -211,6 +212,7 @@ public fun ChatTimelineState.conversationRows(): List = typing = message?.let { isTyping(it, item.isStreaming) } == true, showRetry = item.showRetryAction, error = message?.error?.trim()?.takeIf(String::isNotEmpty), + timestampMs = message?.timestamp?.let(SessionTimePresentation::timestampMs), ) } diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt index ac2be2bd0f..f0ed846413 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt @@ -1718,7 +1718,7 @@ public class RemoteSessionStore internal constructor( renderVersion = null, turnId = clientTurnId, detail = null, - timestamp = null, + timestamp = Clock.System.now().toString(), thinking = null, tools = null, items = null, diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplica.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplica.kt index 37a8fa3829..ecee7252a2 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplica.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplica.kt @@ -243,7 +243,7 @@ internal class SessionRecordReplica(val sessionId: String) { val shownItems = rendered.map { item -> item.tool?.id?.let { id -> controlTools.firstOrNull { it.id == id } }?.let { item.copy(tool = it) } ?: item } + controlTools.filter { tool -> rendered.none { it.tool?.id == tool.id } }.map { ChatMessageItemResponse(type = "tool", tool = it) } return listOf(RemoteResponseMapper.chatMessage(ChatMessageResponse(id = user.string("id"), role = "user", content = user.string("content"), turnId = turnId, metadata = user["metadata"], images = userImages(user), timestamp = user.string("timestamp"))), - RemoteResponseMapper.chatMessage(ChatMessageResponse(id = "${turnId}_assistant", role = "assistant", turnId = turnId, + RemoteResponseMapper.chatMessage(ChatMessageResponse(id = "${turnId}_assistant", role = "assistant", turnId = turnId, timestamp = turn.string("timestamp"), content = rendered.filter { it.type == "text" && it.isSubagent != true }.joinToString("") { it.content.orEmpty() }, thinking = rendered.filter { it.type == "thinking" && it.isSubagent != true }.joinToString("") { it.content.orEmpty() }, items = shownItems, status = when (turn.string("status")) { "inprogress" -> "streaming"; "error" -> "failed"; else -> turn.string("status") }, error = turn.string("error"), metadata = turn))) diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentation.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentation.kt index eaaea8a85d..54ae116eed 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentation.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentation.kt @@ -41,10 +41,11 @@ public data class RemoteSidebarWorkspaceRow public constructor( public val remoteConnectionId: String?, public val remoteSshHost: String?, public val workspaceId: String?, - public val load: RemoteSidebarWorkspaceLoad = RemoteSidebarWorkspaceLoad.READY, + public val load: RemoteSidebarWorkspaceLoad, + public val kind: String, ) { public val key: String get() = RemoteWorkspaceIdentity(path, remoteConnectionId, remoteSshHost, workspaceId).key - public constructor(path: String, name: String, selected: Boolean, sessions: List, remoteConnectionId: String?, remoteSshHost: String?) : this(path, name, selected, sessions, remoteConnectionId, remoteSshHost, null) + public constructor(path: String, name: String, selected: Boolean, sessions: List, remoteConnectionId: String?, remoteSshHost: String?) : this(path, name, selected, sessions, remoteConnectionId, remoteSshHost, null, RemoteSidebarWorkspaceLoad.READY, "normal") public constructor(path: String, name: String, selected: Boolean, sessions: List, remoteConnectionId: String?) : this(path, name, selected, sessions, remoteConnectionId, null) public constructor(path: String, name: String, selected: Boolean, sessions: List) : this(path, name, selected, sessions, null) } @@ -130,6 +131,7 @@ public object RemoteSidebarPresentation { remoteSshHost = workspace.remoteSshHost, workspaceId = workspace.workspaceId, load = load, + kind = workspace.kind, sessions = owned.map { session -> RemoteSidebarSessionRow( id = session.id, diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogUiState.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogUiState.kt index d44d803afc..0b29bd110d 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogUiState.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogUiState.kt @@ -46,7 +46,8 @@ internal fun projectWorkspaceCatalog( row.name.isBlank() -> row.copy(name = row.path.trimEnd('/').substringAfterLast('/')) else -> row } - }.distinctBy { it.workspaceId ?: Triple(it.remoteConnectionId, it.remoteSshHost, it.path) }, + }.distinctBy { it.workspaceId ?: Triple(it.remoteConnectionId, it.remoteSshHost, it.path) } + .sortedBy { it.kind != "assistant" }, if (opened) WorkspaceCatalogSource.OPENED else WorkspaceCatalogSource.RECENT, ) } diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentationTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentationTest.kt index 288466d6a5..3cb6ef856b 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentationTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentationTest.kt @@ -15,6 +15,17 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class ConversationPresentationTest { + @Test + fun messageTimesSurviveProjectionWithLegacyScalesAndMissingValues() { + val rows = timeline(persisted = listOf( + message("user", "user", "Question").copy(timestamp = "1700000000"), + message("assistant", "assistant", "Answer").copy(timestamp = "1700000001000"), + message("legacy", "assistant", "Old answer").copy(timestamp = null), + message("invalid", "user", "Old question").copy(timestamp = "invalid"), + )).conversationRows() + assertEquals(listOf(1700000000000L, 1700000001000L, null, null), rows.map { it.timestampMs }) + } + @Test fun anEmptySessionGetsTheOneRowNobodyOwns() { val rows = timeline().conversationRows() diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplicaTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplicaTest.kt index 75ce529b84..255f2a10e9 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplicaTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplicaTest.kt @@ -7,7 +7,7 @@ class SessionRecordReplicaTest { private fun record(revision: Long, status: String, text: String): JsonObject = buildJsonObject { put("sessionId", "s"); put("id", "item/i"); put("revision", revision) put("turn", buildJsonObject { - put("sessionId", "s"); put("turnId", "t"); put("turnIndex", 0); put("status", status) + put("sessionId", "s"); put("turnId", "t"); put("turnIndex", 0); put("status", status); put("timestamp", 1700000001000L) put("userMessage", buildJsonObject { put("id", "u"); put("content", "question"); put("timestamp", 1) }) }) put("round", buildJsonObject { put("id", "r"); put("turnId", "t"); put("roundIndex", 0) }) @@ -23,6 +23,8 @@ class SessionRecordReplicaTest { assertEquals("u", messages[0].id) assertEquals("hello world", messages[1].text) assertEquals("completed", messages[1].status) + assertEquals("1", messages[0].timestamp) + assertEquals("1700000001000", messages[1].timestamp) } @Test fun turnRecordUserMessageOutlivesTheHeadersItsChildrenRepeat() { val replica = SessionRecordReplica("s") diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentationTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentationTest.kt index 7a98a135b8..74029ba354 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentationTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentationTest.kt @@ -18,6 +18,15 @@ class ToolRowPresentationTest { assertEquals(3, assertIs(rows.single()).tools.size) } + @Test + fun failedCallsFoldWithCompletedWorkWithoutLosingTheirDetails() { + val failed = tool("fetch", ToolKind.WEB, ToolPhase.FAILED).copy(output = "HTTP 404") + val rows = collapseToolRows(listOf(tool("read", ToolKind.DOCUMENT), failed)) + val group = assertIs(rows.single()) + assertEquals(ToolPhase.FAILED, group.tools.last().phase) + assertEquals("HTTP 404", group.tools.last().output) + } + @Test fun leavesAttentionAndPlanToolsVisible() { val rows = collapseToolRows( diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentationTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentationTest.kt index b0d80f010f..a679bed7bb 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentationTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentationTest.kt @@ -15,6 +15,17 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class RemoteSidebarPresentationTest { + @Test + fun assistantKindReachesNativeCreationControls() { + val ready = workspaceReady(selected("/repo", "Project"), listOf( + recent("/repo", "Project"), recent("/assistant", "Assistant").copy(kind = "assistant"), + )) + val rows = RemoteSidebarPresentation.workspacesForSessions(ready, emptyList()) + assertEquals("/assistant", rows.first().path) + assertEquals("assistant", rows.first().kind) + assertEquals("git", rows.last().kind) + } + @Test fun selectionDoesNotReorderOrRenameHostCatalog() { val rows = RemoteSidebarPresentation.workspaces( diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogTest.kt index 46ea6f22d3..87bd8fdc17 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogTest.kt @@ -73,5 +73,19 @@ class WorkspaceCatalogTest { assertEquals("localhost", catalog.workspaces[1].remoteSshHost) } + @Test + fun openedAssistantsComeFirstWithoutReorderingPeersOrPickerHistory() { + val response = decode("""{"workspaces":[{"path":"/recent"}],"opened_workspaces":[ + {"workspace_id":"remote","path":"/repo","workspace_kind":"remote","remote_connection_id":"ssh"}, + {"workspace_id":"a","path":"/assistant-a","workspace_kind":"assistant"}, + {"workspace_id":"local","path":"/local","workspace_kind":"normal"}, + {"workspace_id":"b","path":"/assistant-b","workspace_kind":"assistant"} + ]}""") + val catalog = response.sidebarCatalog(emptyList()) + assertEquals(listOf("a", "b", "remote", "local"), catalog.workspaces.map { it.workspaceId }) + assertEquals("ssh", catalog.workspaces[2].remoteConnectionId) + assertEquals("/recent", catalog.recentWorkspaces.single().path) + } + private fun decode(wire: String): RecentWorkspaceListResponse = RelayJson.decodeFromString(wire) } diff --git a/src/mobile-web/AGENTS.md b/src/mobile-web/AGENTS.md index eebab366f5..ab4aa0200d 100644 --- a/src/mobile-web/AGENTS.md +++ b/src/mobile-web/AGENTS.md @@ -54,6 +54,7 @@ pnpm --dir src/mobile-web run test:interaction-mailbox # independent question/pe pnpm --dir src/mobile-web run test:terminal-browser # real xterm keyboard, ANSI and native bridge pnpm --dir src/mobile-web run test:ui-components pnpm --dir src/mobile-web run test:session-stream-browser # host-driven latest/backward pages, hints, restart gaps, no relay history routes +node --test src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs # localized message times and expandable failures at compact/wide widths node --test src/mobile-web/tests/background-delivery-browser.test.mjs # quiet execution details, failures, questions, generation fences at three viewport widths pnpm --dir src/mobile-web run test:host-queue # idempotent outbox and real browser close/reopen pnpm --dir src/mobile-web run test:host-stream # HostStream reader: hints, reconnects, host restart, unsupported hosts; catalog subscription; next-input suggestions diff --git a/src/mobile-web/src/components/ChatTranscript.tsx b/src/mobile-web/src/components/ChatTranscript.tsx index fdeab84a40..823c21ec0d 100644 --- a/src/mobile-web/src/components/ChatTranscript.tsx +++ b/src/mobile-web/src/components/ChatTranscript.tsx @@ -17,6 +17,7 @@ import { backgroundDeliveryFromMetadata, readBackgroundDelivery, suppressesBackg import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { MobileButton, MobileCard, MobileDisclosure, MobileMessage } from '@openbitfun/ui/mobile'; import { useI18n } from '../i18n'; +import { messageTimestamp } from '../i18n/messageTime'; import type { ActiveTurnSnapshot, ChatMessage, ChatMessageItem, RemoteToolStatus } from '../services/RemoteSessionManager'; import ChatAskQuestionCard from './ChatAskQuestionCard'; import { MarkdownContent } from './ChatMarkdown'; @@ -460,10 +461,10 @@ const ToolCard: React.FC<{ ? formatDuration(now - tool.start_ms) : ''; - const statusClass = isRunning ? 'running' : isCompleted ? 'done' : isError ? 'error' : 'pending'; + const statusClass = isRunning ? 'running' : isCompleted ? 'done' : isError ? 'settled' : 'pending'; return ( - +
{isRunning ? ( @@ -473,8 +474,8 @@ const ToolCard: React.FC<{ ) : isError ? ( - -