From b6f250abb926af5426629a49b630fb0fde0e5940 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 12 Nov 2026 02:14:22 +0800 Subject: [PATCH] fix(mobile): restore mobile architecture check and HarmonyOS test harness - pnpm run mobile:architecture failed on main: the shared JVM client build contract test reached into the HarmonyOS tree, and RemoteSession exposed public default arguments. Move the cross-platform build contract to scripts/mobile-client-build.contract.test.mjs and replace the defaults with explicit constructors. - Update HarmonyOS harness tests for MessageQueueStore and the sidebar footer, drop the removed derivePasswordHash call from the ohosTest target, and stop the local unit test from swallowing unexpected errors or touching HUKS. --- package.json | 2 +- scripts/mobile-client-build.contract.test.mjs | 41 +++++++++++++++++ .../src/main/ets/services/ClientBuild.ets | 2 +- .../ets/test/NativeCryptoLoad.test.ets | 20 +++++++-- .../test/TransportAndGeneralChatUnit.test.ets | 20 ++++++++- .../tools/tests/interaction-mailbox.test.cjs | 3 ++ .../tests/session-model-hydration.test.cjs | 13 +++++- .../tools/tests/session-record.test.cjs | 25 ++++++++--- .../tools/tests/workspace-editor.test.cjs | 4 +- .../mobile/core/domain/ConversationModels.kt | 18 +++++++- .../core/domain/SessionListPolicyTest.kt | 33 ++++++++++++++ .../session/RemoteResponseMapperTest.kt | 44 +++++++++++++++++++ .../core/transport/ClientBuildContractTest.kt | 29 ++---------- 13 files changed, 210 insertions(+), 44 deletions(-) create mode 100644 scripts/mobile-client-build.contract.test.mjs diff --git a/package.json b/package.json index ad020b46be..4d09078e85 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,7 @@ "models-dev:update": "node scripts/update-models-dev-snapshot.mjs", "check:build-prereqs": "node scripts/check-build-prereqs.mjs", "harmony:architecture": "node scripts/check-harmonyos-architecture.mjs", - "mobile:architecture": "node scripts/check-mobile-architecture.mjs", + "mobile:architecture": "node scripts/check-mobile-architecture.mjs && node --test scripts/mobile-client-build.contract.test.mjs", "mobile:ui:generate": "node scripts/mobile-ui-design-system.mjs", "mobile:ui:check": "node scripts/mobile-ui-design-system.mjs --check && node scripts/mobile-ui-preview.mjs --check", "mobile:ui:preview": "node scripts/mobile-ui-design-system.mjs && node scripts/mobile-ui-preview.mjs", diff --git a/scripts/mobile-client-build.contract.test.mjs b/scripts/mobile-client-build.contract.test.mjs new file mode 100644 index 0000000000..d5947da58c --- /dev/null +++ b/scripts/mobile-client-build.contract.test.mjs @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; + +// Cross-platform source contracts belong to the repository, not a shared +// runtime module that would then need to reach into a platform's implementation. +const root = path.resolve(import.meta.dirname, '..'); +const source = relative => fs.readFileSync(path.join(root, relative), 'utf8'); +const services = 'src/apps/mobile/harmonyos/entry/src/main/ets/services'; + +function protocolVersion(file, declaration) { + const match = source(file).match(declaration); + assert.ok(match, `Missing protocol version declaration in ${file}`); + return Number(match[1]); +} + +test('mobile and web protocol versions match the Rust account contract', () => { + const expected = protocolVersion( + 'src/crates/contracts/product-domains/src/account.rs', + /^pub const CLIENT_PROTOCOL_VERSION: u32 = (\d+);$/m, + ); + for (const [file, declaration] of [ + ['src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/ClientBuild.kt', + /^public const val CLIENT_PROTOCOL_VERSION: Int = (\d+)$/m], + [`${services}/ClientBuild.ets`, /^export const CLIENT_PROTOCOL_VERSION: number = (\d+);$/m], + ['src/shared/relay-transport/ClientBuild.ts', /^export const CLIENT_PROTOCOL_VERSION = (\d+);$/m], + ]) { + assert.equal(protocolVersion(file, declaration), expected, `${file} must match the Rust contract`); + } +}); + +test('HarmonyOS reports its bundle build and protocol on login and every handshake', () => { + // Preserve the transport assertions formerly owned by the shared JVM suite. + // The version string is resolved from this platform's bundle at runtime. + const realtime = source(`${services}/AccountRealtime.ets`); + assert.ok(realtime.includes('clientVersion: clientVersion()')); + assert.ok(realtime.includes('clientProtocol: CLIENT_PROTOCOL_VERSION')); + const client = source(`${services}/CloudAccountClient.ets`); + assert.ok(client.includes('clientVersion: clientVersion(), clientProtocol: CLIENT_PROTOCOL_VERSION')); +}); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets index 013a54e12c..3107e7162f 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets @@ -21,7 +21,7 @@ import { bundleManager } from '@kit.AbilityKit'; * `openbitfun_product_domains::account::CLIENT_PROTOCOL_VERSION` in * `src/crates/contracts/product-domains/src/account.rs` and to the Kotlin * `CLIENT_PROTOCOL_VERSION` the other mobile clients share; - * `ClientBuildContractTest` in `shared/core-transport` pins them together so + * `scripts/mobile-client-build.contract.test.mjs` pins them together so * one side can never drift. */ export const CLIENT_PROTOCOL_VERSION: number = 2; diff --git a/src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/NativeCryptoLoad.test.ets b/src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/NativeCryptoLoad.test.ets index 175e0d1923..f8dee91563 100644 --- a/src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/NativeCryptoLoad.test.ets +++ b/src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/NativeCryptoLoad.test.ets @@ -1,11 +1,23 @@ import { describe, it, expect } from '@ohos/hypium'; -import { CloudAccountCrypto } from '../../../main/ets/services/CloudAccountCrypto'; +import openbitfunCrypto from 'libopenbitfun_crypto.so'; +import { Encoding } from '../../../main/ets/services/Encoding'; + +// The account password login that wrapped this binding is retired, so the load +// goes straight to the native Argon2id work the library still ships. +const LOAD_MEMORY_KIB: number = 16 * 1024; +const LOAD_PASSES: number = 2; +const LOAD_LANES: number = 1; + +function nativeArgon2id(input: Uint8Array, salt: Uint8Array): Promise { + return openbitfunCrypto.argon2idRaw(input, salt, LOAD_MEMORY_KIB, LOAD_PASSES, LOAD_LANES); +} export default function nativeCryptoLoadTest() { describe('NativeCryptoLoad', () => { it('keeps the ArkTS event loop responsive during concurrent Argon2id work', 0, async () => { const salt = new Uint8Array([0x42, 0x69, 0x74, 0x46, 0x75, 0x6e, 0x2d, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]); + const input = Encoding.utf8ToBytes('openbitfun-device-load'); let heartbeatTicks = 0; const heartbeatId = setInterval(() => { heartbeatTicks += 1; @@ -13,9 +25,9 @@ export default function nativeCryptoLoadTest() { const startedAt = Date.now(); const results = await Promise.all([ - CloudAccountCrypto.derivePasswordHash('openbitfun-device-load', salt, { m: 16 * 1024, t: 2, p: 1 }), - CloudAccountCrypto.derivePasswordHash('openbitfun-device-load', salt, { m: 16 * 1024, t: 2, p: 1 }), - CloudAccountCrypto.derivePasswordHash('openbitfun-device-load', salt, { m: 16 * 1024, t: 2, p: 1 }) + nativeArgon2id(input, salt), + nativeArgon2id(input, salt), + nativeArgon2id(input, salt) ]); clearInterval(heartbeatId); diff --git a/src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets b/src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets index a8aa718d2d..4e7f1f0139 100644 --- a/src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets +++ b/src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets @@ -110,7 +110,8 @@ import { } from '../main/ets/services/CloudAccountClient'; import { CloudAccountSessionStore, - PersistedCloudAccountSession + PersistedCloudAccountSession, + PersistedWatchProvisionIdentity } from '../main/ets/services/CloudAccountSessionStore'; import { RemotePageState } from '../main/ets/pages/state/RemotePageState'; import { ConversationViewState } from '../main/ets/pages/state/ConversationViewState'; @@ -427,6 +428,20 @@ class GatedAccountSessionManager extends ScriptedAccountSessionManager { /** HUKS and preferences are not reachable from a local unit run. */ class InMemoryCloudAccountSessionStore extends CloudAccountSessionStore { + private watchIdentity?: PersistedWatchProvisionIdentity; + async loadWatchProvisionIdentity(relayUrl: string, userId: string, + deviceId: string): Promise { + // A persisted key keeps this refusal test independent of HUKS/randomness + // (neither platform service exists in the host LocalTest runner). + return this.watchIdentity || { + relayUrl, userId, deviceId, requestId: '12345678-1234-4234-8234-123456789abc', + privateKeyBase64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' + }; + } + async saveWatchProvisionIdentity(identity: PersistedWatchProvisionIdentity): Promise { + this.watchIdentity = identity; + } + readonly saved: PersistedCloudAccountSession[] = []; profile?: GitHubAccountProfile; async loadProfile(_userId: string): Promise { return this.profile; } @@ -1319,7 +1334,8 @@ export default function transportAndGeneralChatUnitTest() { '12345678-1234-4234-8234-123456789abc' ); } catch (err) { - if (err instanceof CloudAccountRequestError) statusCode = err.statusCode; + if (!(err instanceof CloudAccountRequestError)) throw new Error(String(err)); + statusCode = err.statusCode; } expect(statusCode).assertEqual(expectedStatus); expect(harness.sessionStore.clears).assertEqual(0); diff --git a/src/apps/mobile/harmonyos/tools/tests/interaction-mailbox.test.cjs b/src/apps/mobile/harmonyos/tools/tests/interaction-mailbox.test.cjs index 42771e355c..d99e87921f 100644 --- a/src/apps/mobile/harmonyos/tools/tests/interaction-mailbox.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/interaction-mailbox.test.cjs @@ -15,6 +15,7 @@ const models = load('../model/InteractionMailbox'); const { InteractionMailboxStore } = load('InteractionMailboxStore', { '../model/InteractionMailbox': models }); const reducer = load('DurableSessionReducer'); const { ChatSessionController } = load('ChatSessionController', { + './MessageQueueStore': load('MessageQueueStore', { '../model/MessageQueue': load('../model/MessageQueue') }), './InteractionMailboxStore': { InteractionMailboxStore }, './DurableSessionReducer': reducer, './SubagentStreamCoordinator': load('SubagentStreamCoordinator', { './DurableSessionReducer': reducer }), }); @@ -25,6 +26,7 @@ const snapshot = (requests = [request()], questions = [], sessionId = 's') => ({ function fixture() { const f = { state: null, wire: snapshot(), calls: [], fail: false }; f.client = { + supportsMessageQueue: () => false, async getModelCatalog() { return { version: 1, models: [], default_models: {} }; }, async hostInvoke(command, args) { f.calls.push({ command, args }); @@ -67,6 +69,7 @@ test('tool completion cannot consume runtime approval or manufacture an active t assert.deepEqual(mailbox.requests.map(r => r.requestId), ['approval']); assert.equal(transcript.activeTurn, undefined); assert.deepEqual(transcript.messageSnapshot, []); + controller.stop(); f.wire = snapshot([]); await callbacks.onEvent({ session_id: 's', event: 'session-interaction-changed', payload: {} }); assert.deepEqual(mailbox.requests, []); diff --git a/src/apps/mobile/harmonyos/tools/tests/session-model-hydration.test.cjs b/src/apps/mobile/harmonyos/tools/tests/session-model-hydration.test.cjs index eb8f005389..11e77b86f2 100644 --- a/src/apps/mobile/harmonyos/tools/tests/session-model-hydration.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/session-model-hydration.test.cjs @@ -3,11 +3,21 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const ts = require('typescript'); +function load(name, dependencies = {}) { + const source = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets', `${name}.ets`), 'utf8'); + const exports = {}; + new Function('require', 'exports', ts.transpileModule(source, { compilerOptions: { + target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, + } }).outputText)(key => dependencies[key] || {}, exports); + return exports; +} +const queueModule = load('services/MessageQueueStore', { '../model/MessageQueue': load('model/MessageQueue') }); const source = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/services/ChatSessionController.ets'), 'utf8'); const exported = {}; new Function('require', 'exports', ts.transpileModule(source, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS}}).outputText)(name => ({ + './MessageQueueStore': queueModule, './InteractionMailboxStore': { InteractionMailboxStore: class { select() {} } }, - './DurableSessionReducer': { DurableSessionReducer: class { messages() { return []; } } }, + './DurableSessionReducer': load('services/DurableSessionReducer'), './SubagentStreamCoordinator': { SubagentStreamCoordinator: class { beginSession() {} endSession() {} @@ -20,6 +30,7 @@ const flush = () => new Promise(resolve => setImmediate(resolve)); function fixture() { const requests = [], streams = [], snapshots = [], errors = []; const manager = { + supportsMessageQueue: () => false, getModelCatalog(sessionId) { return new Promise((resolve, reject) => requests.push({sessionId, resolve, reject})); }, subscribeSession(sessionId, callbacks) { streams.push(callbacks); return {close() {}, isClosed() {return false;}}; }, }; diff --git a/src/apps/mobile/harmonyos/tools/tests/session-record.test.cjs b/src/apps/mobile/harmonyos/tools/tests/session-record.test.cjs index cafba8e4e1..f2a23d82e0 100644 --- a/src/apps/mobile/harmonyos/tools/tests/session-record.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/session-record.test.cjs @@ -3,6 +3,18 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const ts = require('typescript'); +const activeControllers = new Set(); +test.afterEach(() => { + for (const controller of activeControllers) controller.stop(); + activeControllers.clear(); +}); +function createController(Controller, manager, hooks) { + // These transcript fixtures model hosts without a message queue. Leaving + // the capability method absent starts error/retry timers in the real store. + const controller = new Controller(Object.assign(manager, { supportsMessageQueue: () => false }), hooks); + activeControllers.add(controller); + return controller; +} function load(name, dependencies = {}) { const source = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/services', `${name}.ets`), 'utf8'); const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText; @@ -18,6 +30,7 @@ const { DurableSessionReducer } = reducerModule; const subagentModule = load('SubagentStreamCoordinator', { './DurableSessionReducer': reducerModule }); function loadController() { return load('ChatSessionController', { + './MessageQueueStore': load('MessageQueueStore', { '../model/MessageQueue': load('../model/MessageQueue') }), './DurableSessionReducer': reducerModule, './InteractionMailboxStore': mailboxModule, './SubagentStreamCoordinator': subagentModule }); @@ -33,7 +46,7 @@ function suggestionFixture() { const snapshots = []; const manager = { getModelCatalog: async () => ({version: 1, models: [], default_models: {}}), subscribeSession: (_id, next) => { callbacks = next; return {wake() {}, close() {}}; } }; - const controller = new ChatSessionController(manager, {onSnapshot: value => snapshots.push(value), canPoll: () => true, onError: error => {throw error;}}); + const controller = createController(ChatSessionController, Object.assign(manager, { supportsMessageQueue: () => false }), {onSnapshot: value => snapshots.push(value), canPoll: () => true, onError: error => {throw error;}}); controller.start('session', {pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0}); return { controller, snapshots, stream: () => callbacks, latest: () => snapshots.at(-1) }; } @@ -126,7 +139,7 @@ test('controller hydrates from the same record log without transcript RPC', asyn const { ChatSessionController } = loadController(); let callbacks, snapshots = []; const manager = { getModelCatalog: async () => ({ version: 1, models: [], default_models: {} }), subscribeSession: (_id, next) => { callbacks = next; return { wake() {}, close() {} }; }, getSessionMessages: () => { throw new Error('Snapshot RPC is forbidden'); } }; - const controller = new ChatSessionController(manager, { onSnapshot: value => snapshots.push(value), canPoll: () => true, onError: error => { throw error; } }); + const controller = createController(ChatSessionController, Object.assign(manager, { supportsMessageQueue: () => false }), { onSnapshot: value => snapshots.push(value), canPoll: () => true, onError: error => { throw error; } }); controller.start('session', { pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0 }); await callbacks.onEvent(record(1, 'partial')); assert.equal(snapshots.length, 0); @@ -180,7 +193,7 @@ test('initial and resumed mailbox restores questions independently of transcript return {sessionId:'session',permissions:{revision:0,requests:[]},userQuestions:{revision:1,questions:[{toolId:'question-tool',sessionId:'session',questions:question,registeredAtMs:1}]}}; } }; - const controller = new ChatSessionController(manager,{onSnapshot:value=>snapshot=value,onMailbox:value=>mailbox=value,onError:error=>{throw error;},canPoll:()=>true}); + const controller = createController(ChatSessionController, Object.assign(manager, { supportsMessageQueue: () => false }),{onSnapshot:value=>snapshot=value,onMailbox:value=>mailbox=value,onError:error=>{throw error;},canPoll:()=>true}); controller.start('session',{pollVersion:0,knownMessageCount:0,knownModelCatalogVersion:0}); await callbacks.onResumed(); await callbacks.onCaughtUp(); assert.equal(snapshot.activeTurn,undefined); @@ -321,7 +334,7 @@ test('history publishes user and assistant together after reduction, including a getModelCatalog: () => new Promise(resolve => { resolveCatalog = resolve; }), subscribeSession: (_id, next) => { callbacks = next; return { close() {} }; } }; - const controller = new ChatSessionController(manager, { canPoll: () => true, + const controller = createController(ChatSessionController, Object.assign(manager, { supportsMessageQueue: () => false }), { canPoll: () => true, onSnapshot: value => snapshots.push(value), onError: error => { throw error; } }); controller.start('session', { pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0 }); await callbacks.onCaughtUp(); @@ -355,7 +368,7 @@ async function durableTimelineHarness() { timeline.reset('session'); let stream; const { ChatSessionController } = loadController(); - const controller = new ChatSessionController({ + const controller = createController(ChatSessionController, { getModelCatalog: async () => ({ version: 1, models: [], default_models: {} }), subscribeSession: (_id, callbacks) => { stream = callbacks; return { wake() {}, close() {} }; } }, { onSnapshot: snapshot => timeline.applySnapshot(snapshot), canPoll: () => true, @@ -455,7 +468,7 @@ test('host restart terminal record settles active turn without reporting success const { ChatSessionController } = loadController(); let stream, snapshot; const timeline = new ChatTimelineStore(); timeline.reset('session'); - const controller = new ChatSessionController({ getModelCatalog: async () => ({version:1,models:[],default_models:{}}), + const controller = createController(ChatSessionController, { getModelCatalog: async () => ({version:1,models:[],default_models:{}}), subscribeSession: (_id, callbacks) => { stream=callbacks; return {wake(){},close(){}}; } }, { onSnapshot: value => { snapshot=value; timeline.applySnapshot(value); }, canPoll:()=>true, onError:error=>{throw error;} }); controller.start('session',{pollVersion:0,knownMessageCount:0,knownModelCatalogVersion:0}); diff --git a/src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs b/src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs index ef2cf30ba1..cd52ed3637 100644 --- a/src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs @@ -20,7 +20,9 @@ test('sidebar final entry hierarchy keeps modes in workspace plus and tools in t assert.doesNotMatch(menu,/supportsHarnessProfiles|workspaceTools\.files|workspaceTools\.terminal|openWorkspaceTools/); const sidebar=fs.readFileSync(path.join(components,'AppSidebar.ets'),'utf8'); assert.doesNotMatch(sidebar,/requestChat|sidebar\.newChat|sidebar\.conversations/); - assert.match(sidebar,/workspaceTools\.title/); + const footer=fs.readFileSync(path.join(components,'SidebarToolsFooter.ets'),'utf8'); + assert.match(sidebar,/SidebarToolsFooter\(\{/); + assert.match(footer,/workspaceTools\.title/); assert.match(sidebar,/if \(this.connectionState !== 'connected'\) return/); assert.doesNotMatch(sidebar,/DeviceToolsPicker|showToolsPicker/); assert.match(sidebar,/type: 'open-device', deviceId: this.controlTargetDeviceId/); diff --git a/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationModels.kt b/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationModels.kt index 8dc0c4715c..0a114fc8c8 100644 --- a/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationModels.kt +++ b/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationModels.kt @@ -49,12 +49,26 @@ public data class RemoteSession public constructor( public val workspaceName: String?, public val workspaceIdentity: RemoteWorkspaceIdentity?, /** Set when the session hangs off another one (btw/review/miniapp/subagent). */ - public val parentSessionId: String? = null, - public val relationshipKind: String? = null, + public val parentSessionId: String?, + public val relationshipKind: String?, ) { + // Explicit overloads keep legacy callers working on both Kotlin and Swift. + // Kotlin default arguments are not exported as Swift initializers. public constructor(id: String, title: String, agentType: String, status: String, updatedAt: String, createdAt: String, messageCount: Int, workspacePath: String?, workspaceName: String?) : this(id, title, agentType, status, updatedAt, createdAt, messageCount, workspacePath, workspaceName, null) + + public constructor(id: String, title: String, agentType: String, status: String, updatedAt: String, + createdAt: String, messageCount: Int, workspacePath: String?, workspaceName: String?, + workspaceIdentity: RemoteWorkspaceIdentity?) : + this(id, title, agentType, status, updatedAt, createdAt, messageCount, workspacePath, workspaceName, + workspaceIdentity, null, null) + + public constructor(id: String, title: String, agentType: String, status: String, updatedAt: String, + createdAt: String, messageCount: Int, workspacePath: String?, workspaceName: String?, + workspaceIdentity: RemoteWorkspaceIdentity?, parentSessionId: String?) : + this(id, title, agentType, status, updatedAt, createdAt, messageCount, workspacePath, workspaceName, + workspaceIdentity, parentSessionId, null) } public data class ChatSessionCursor public constructor( diff --git a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicyTest.kt b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicyTest.kt index 48abd18505..1fb91a0934 100644 --- a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicyTest.kt +++ b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicyTest.kt @@ -3,6 +3,7 @@ package com.openbitfun.mobile.core.domain import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SessionListPolicyTest { @@ -47,6 +48,38 @@ class SessionListPolicyTest { assertFalse(SessionListVisibility.isMobileVisible(session(id = "acp", agentType = "acp:codex"))) } + @Test + fun legacyConstructorsKeepTopLevelSessionsAndWorkspaceOwnership() { + val local = RemoteWorkspaceIdentity("/repo", null, null) + val ssh = RemoteWorkspaceIdentity("/repo", "connection", "host", "ssh-workspace") + val legacy = RemoteSession("legacy", "Legacy", "code", "idle", "", "", 0, "/repo", null) + val scoped = RemoteSession("scoped", "Scoped", "code", "idle", "", "", 0, "/repo", null, + workspaceIdentity = ssh) + + for (row in listOf(legacy, scoped)) { + assertNull(row.parentSessionId) + assertNull(row.relationshipKind) + assertTrue(SessionListVisibility.isMobileVisible(row)) + } + assertNull(legacy.workspaceIdentity) + assertTrue(legacy.belongsTo(local, listOf(local))) + assertFalse(legacy.belongsTo(ssh, listOf(local, ssh))) + assertEquals(ssh, scoped.workspaceIdentity) + assertTrue(scoped.belongsTo(ssh, listOf(local, ssh))) + assertFalse(scoped.belongsTo(local, listOf(local, ssh))) + } + + @Test + fun parentOnlyConstructorKeepsChildrenHiddenWithoutInventingARelationshipKind() { + val child = RemoteSession("child", "Child", "code", "idle", "", "", 0, "/repo", null, + workspaceIdentity = null, parentSessionId = "parent") + + assertEquals("parent", child.parentSessionId) + assertNull(child.relationshipKind) + assertFalse(SessionListVisibility.isMobileVisible(child)) + assertFalse(SessionListVisibility.isMobileVisible(child.copy(title = "Renamed"))) + } + private fun session( id: String, agentType: String = "code", diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteResponseMapperTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteResponseMapperTest.kt index 56887d95b6..2b8a1e0f91 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteResponseMapperTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteResponseMapperTest.kt @@ -5,12 +5,56 @@ import com.openbitfun.mobile.core.protocol.ChatMessageItemResponse import com.openbitfun.mobile.core.protocol.ChatMessageResponse import com.openbitfun.mobile.core.protocol.RemoteToolStatusResponse import com.openbitfun.mobile.core.protocol.SessionItemResponse +import com.openbitfun.mobile.core.protocol.RelayJson import com.openbitfun.mobile.core.domain.ChatTimelineStore +import com.openbitfun.mobile.core.domain.SessionListVisibility +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.jsonObject import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class RemoteResponseMapperTest { + @Test + fun legacySessionPayloadRoundTripRemainsVisibleWithoutNewMetadata() { + val payload = """{"session_id":"legacy","name":"Existing session","workspace_path":"/repo"}""" + val decoded = RelayJson.decodeFromString(payload) + val encoded = RelayJson.encodeToString(decoded) + val roundTrip = RelayJson.decodeFromString(encoded) + assertEquals(decoded, roundTrip) + val fields = RelayJson.parseToJsonElement(encoded).jsonObject + assertFalse("parent_session_id" in fields) + assertFalse("relationship_kind" in fields) + assertFalse("workspace_id" in fields) + + val session = RemoteResponseMapper.session(roundTrip) + assertEquals("legacy", session.id) + assertEquals("Existing session", session.title) + assertEquals("/repo", session.workspacePath) + assertNull(session.workspaceIdentity) + assertNull(session.parentSessionId) + assertNull(session.relationshipKind) + assertTrue(SessionListVisibility.isMobileVisible(session)) + } + + @Test + fun childSessionPayloadRoundTripPreservesRelationshipAndWorkspaceIdentity() { + for (kind in listOf("", ",\"relationship_kind\":\"btw\"")) { + val payload = """{"id":"child","workspace_path":"/repo","workspace_id":"ssh-workspace","parent_session_id":"parent"$kind}""" + val decoded = RelayJson.decodeFromString(payload) + val roundTrip = RelayJson.decodeFromString(RelayJson.encodeToString(decoded)) + assertEquals(decoded, roundTrip) + + val session = RemoteResponseMapper.session(roundTrip) + assertEquals("ssh-workspace", session.workspaceIdentity?.workspaceId) + assertEquals("parent", session.parentSessionId) + assertEquals(if (kind.isEmpty()) null else "btw", session.relationshipKind) + assertFalse(SessionListVisibility.isMobileVisible(session)) + } + } + @Test fun activeTurnCarriesPollVersionAsRenderVersion() { val turn = ActiveTurnSnapshotResponse(turnId = "turn-version", status = "active") diff --git a/src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/ClientBuildContractTest.kt b/src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/ClientBuildContractTest.kt index bf82681594..121a110f27 100644 --- a/src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/ClientBuildContractTest.kt +++ b/src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/ClientBuildContractTest.kt @@ -7,13 +7,9 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue /** - * Pins the mobile client build identity to the Rust source of truth and to - * every place that must send it, mirroring - * `src/web-ui/src/infrastructure/account/clientBuild.contract.test.ts`. - * - * The three mobile clients are covered from here because HarmonyOS keeps its - * own ArkTS transport rather than this Kotlin one, and its unit runner cannot - * read repository files; the JVM suite can, so it holds the whole contract. + * Pins the compiled Kotlin build identity to the shared wire contracts and to + * every Kotlin transport entry point that must send it. Cross-platform source + * contracts live in `scripts/mobile-client-build.contract.test.mjs`. */ class ClientBuildContractTest { private val repoRoot: Path = generateSequence(Path.of("").toAbsolutePath()) { it.parent } @@ -54,23 +50,4 @@ class ClientBuildContractTest { assertTrue(client.contains("@SerialName(\"clientProtocol\") val clientProtocol: Int")) assertTrue(client.contains("CLIENT_VERSION, CLIENT_PROTOCOL_VERSION")) } - - @Test - fun harmonyOsTransportReportsTheSameBuild() { - val services = "src/apps/mobile/harmonyos/entry/src/main/ets/services" - val clientBuild = source("$services/ClientBuild.ets") - assertTrue( - clientBuild.contains("export const CLIENT_PROTOCOL_VERSION: number = $CLIENT_PROTOCOL_VERSION;"), - "HarmonyOS CLIENT_PROTOCOL_VERSION must equal the Kotlin one", - ) - // HarmonyOS reads its build string from the bundle manifest at runtime, - // so the value is a call rather than a constant. - val realtime = source("$services/AccountRealtime.ets") - assertTrue(realtime.contains("clientVersion: clientVersion()")) - assertTrue(realtime.contains("clientProtocol: CLIENT_PROTOCOL_VERSION")) - // The phone login body carries it; a watch is provisioned by the phone - // and reports its own build on its own handshake instead. - val client = source("$services/CloudAccountClient.ets") - assertTrue(client.contains("clientVersion: clientVersion(), clientProtocol: CLIENT_PROTOCOL_VERSION")) - } }