From 2529c9bca257233a01efad2a7332a83b91fe18fd Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:10:48 +0800 Subject: [PATCH 1/5] fix(mobile-web): derive chat header from the session workspace The chat header read the store's selected workspace, so opening a Claw session showed the previously selected project and branch. Pass the session's workspace context when a session is opened and keep it in the tab navigation record. Assistant sessions show the assistant name and no branch; normal sessions show their own workspace and a branch only when it is the currently selected workspace. Fixes #2360 --- src/mobile-web/src/App.tsx | 13 ++- src/mobile-web/src/pages/ChatPage.tsx | 20 +++- src/mobile-web/src/pages/SessionListPage.tsx | 64 ++++++++--- .../src/services/MobileNavigationStore.ts | 28 ++++- .../src/services/workspaceIdentity.ts | 96 ++++++++++++++++- src/mobile-web/tests/account-login.test.mjs | 21 ++++ src/mobile-web/tests/browser-account.test.mjs | 58 ++++++++++ .../tests/fixtures/assistant-session.tsx | 35 ++++-- .../tests/workspace-identity.test.mjs | 102 ++++++++++++++++++ 9 files changed, 410 insertions(+), 27 deletions(-) diff --git a/src/mobile-web/src/App.tsx b/src/mobile-web/src/App.tsx index e236c5a01b..e2badd859c 100644 --- a/src/mobile-web/src/App.tsx +++ b/src/mobile-web/src/App.tsx @@ -25,6 +25,7 @@ import { useConnectionHealth } from './hooks/useConnectionHealth'; import { useMobileViewport } from './hooks/useMobileViewport'; import { useWideLayout } from './hooks/useWideLayout'; import { useMobileStore } from './services/store'; +import type { SessionWorkspaceContext } from './services/workspaceIdentity'; import RemoteHomePanel from './components/RemoteHomePanel'; import './styles/index.scss'; @@ -55,6 +56,7 @@ const AppContent: React.FC = () => { const [activeSessionId, setActiveSessionId] = useState(null); const [activeSessionName, setActiveSessionName] = useState('Session'); const [activeSessionAgentType, setActiveSessionAgentType] = useState('Standard'); + const [activeSessionWorkspace, setActiveSessionWorkspace] = useState(); const [chatAutoFocus, setChatAutoFocus] = useState(false); const [compactSidebarOpen, setCompactSidebarOpen] = useState(false); const isWideLayout = useWideLayout(); @@ -195,6 +197,7 @@ const AppContent: React.FC = () => { setActiveSessionId(null); setActiveSessionName('Session'); setActiveSessionAgentType('Standard'); + setActiveSessionWorkspace(undefined); setChatAutoFocus(false); setPrevPage(null); setNavDir(null); @@ -279,11 +282,13 @@ const AppContent: React.FC = () => { sessionName?: string, isNew?: boolean, agentType = 'Standard', + workspace?: SessionWorkspaceContext, ) => { useMobileStore.getState().setError(null); setActiveSessionId(sessionId); setActiveSessionName(sessionName || 'Session'); setActiveSessionAgentType(agentType); + setActiveSessionWorkspace(workspace); setChatAutoFocus(!!isNew); setCompactSidebarOpen(false); if (isWideLayout) { @@ -315,6 +320,7 @@ const AppContent: React.FC = () => { setActiveSessionId(restored.session.id); setActiveSessionName(restored.session.name); setActiveSessionAgentType(restored.session.agentType); + setActiveSessionWorkspace(restored.session.workspace); setChatAutoFocus(false); setPrevPage(null); setNavDir(null); @@ -327,6 +333,7 @@ const AppContent: React.FC = () => { setActiveSessionId(null); setActiveSessionName('Session'); setActiveSessionAgentType('Standard'); + setActiveSessionWorkspace(undefined); setChatAutoFocus(false); setPrevPage(null); setNavDir(null); @@ -352,6 +359,7 @@ const AppContent: React.FC = () => { setActiveSessionId(null); setActiveSessionName('Session'); setActiveSessionAgentType('Standard'); + setActiveSessionWorkspace(undefined); setChatAutoFocus(false); setCompactSidebarOpen(false); setPrevPage(null); @@ -429,6 +437,7 @@ const AppContent: React.FC = () => { setActiveSessionId(null); setActiveSessionName('Session'); setActiveSessionAgentType('Standard'); + setActiveSessionWorkspace(undefined); setChatAutoFocus(false); setCompactSidebarOpen(false); setPrevPage(null); @@ -454,9 +463,10 @@ const AppContent: React.FC = () => { id: activeSessionId, name: activeSessionName, agentType: activeSessionAgentType, + workspace: activeSessionWorkspace, } : undefined, }); - }, [accountDirectoryOpen, activeSessionAgentType, activeSessionId, activeSessionName, controlTarget, page]); + }, [accountDirectoryOpen, activeSessionAgentType, activeSessionId, activeSessionName, activeSessionWorkspace, controlTarget, page]); const isAnimating = navDir !== null; const currentPage: Page = page; @@ -500,6 +510,7 @@ const AppContent: React.FC = () => { sessionId={activeSessionId} sessionName={activeSessionName} agentType={activeSessionAgentType} + workspace={activeSessionWorkspace} onBack={isWideLayout ? handleBackToSessions : () => setCompactSidebarOpen(true)} autoFocus={chatAutoFocus} wideLayout={isWideLayout} diff --git a/src/mobile-web/src/pages/ChatPage.tsx b/src/mobile-web/src/pages/ChatPage.tsx index 95677c6b22..7c28d1a3ea 100644 --- a/src/mobile-web/src/pages/ChatPage.tsx +++ b/src/mobile-web/src/pages/ChatPage.tsx @@ -22,6 +22,11 @@ import { type PendingChatImage, } from '../services/chatImageAttachments'; import { useMobileStore } from '../services/store'; +import { + resolveChatHeaderContext, + sessionWorkspaceContext, + type SessionWorkspaceContext, +} from '../services/workspaceIdentity'; import { createRemoteCacheScope, remoteCache } from '../services/RemoteCache'; import ChatHeader from '../components/ChatHeader'; import ChatComposerBar from '../components/ChatComposerBar'; @@ -51,6 +56,7 @@ interface ChatPageProps { sessionId: string; sessionName?: string; agentType?: string; + workspace?: SessionWorkspaceContext; onBack: () => void; autoFocus?: boolean; wideLayout?: boolean; @@ -74,6 +80,7 @@ const ChatPage: React.FC = ({ sessionId, sessionName, agentType: sessionAgentType = 'Standard', + workspace: sessionWorkspace, onBack, autoFocus, wideLayout = false, @@ -88,6 +95,8 @@ const ChatPage: React.FC = ({ error, setError, currentWorkspace, + currentAssistant, + sessions, authenticatedUserId, controlTarget, connectionHealth, @@ -1152,8 +1161,15 @@ const ChatPage: React.FC = ({ } }; - const workspaceName = currentWorkspace?.project_name || currentWorkspace?.path?.split('/').pop() || ''; - const gitBranch = currentWorkspace?.git_branch; + // Restored navigation from an older build has no workspace; the loaded session row may. + const listedSession = sessionWorkspace ? undefined : sessions.find((session) => session.session_id === sessionId); + const { workspaceName, gitBranch } = resolveChatHeaderContext({ + agentType: sessionAgentType, + session: sessionWorkspace ?? (listedSession && sessionWorkspaceContext(listedSession)), + currentWorkspace, + currentAssistant, + assistantLabel: t('shared.agents.Claw'), + }); const displayName = liveTitle || sessionName || t('chat.session'); const isRemoteWorkspace = currentWorkspace?.workspace_kind === 'remote' || Boolean(currentWorkspace?.remote_connection_id) diff --git a/src/mobile-web/src/pages/SessionListPage.tsx b/src/mobile-web/src/pages/SessionListPage.tsx index 9376b8d066..3d595e2684 100644 --- a/src/mobile-web/src/pages/SessionListPage.tsx +++ b/src/mobile-web/src/pages/SessionListPage.tsx @@ -63,9 +63,13 @@ import { describeRemoteError } from '../services/remoteErrorPresentation'; // Device-directory read failures share the device pages' relay-failure copy. import { deviceFailurePresentation } from '../services/deviceFailureCopy'; import { + isClawAgent, sameWorkspace, sessionMatchesWorkspace, + sessionWorkspaceContext, + workspaceContext, workspaceIdentityKey, + type SessionWorkspaceContext, type WorkspaceReference, } from '../services/workspaceIdentity'; import { useTheme } from '../theme'; @@ -93,6 +97,7 @@ interface SessionListPageProps { sessionName?: string, isNew?: boolean, agentType?: string, + workspace?: SessionWorkspaceContext, ) => void; onOpenWorkspace: () => void; onOpenDeviceTools: () => void; @@ -139,6 +144,21 @@ function commandIdentity( }; } +function createdSessionWorkspace( + path: string, + identity: RemoteWorkspaceIdentity, + owner?: SessionWorkspaceContext, +): SessionWorkspaceContext | undefined { + return sessionWorkspaceContext({ + workspace_id: identity.workspaceId, + workspace_path: path, + workspace_identity: { + remote_connection_id: identity.remoteConnectionId, + remote_ssh_host: identity.remoteSshHost, + }, + }, owner); +} + function assistantIdentity(assistant: AssistantEntry | null | undefined): RemoteWorkspaceIdentity { return { workspaceId: assistant?.workspace_id }; } @@ -213,10 +233,6 @@ function isCoworkAgent(agentType: string): boolean { return agentType === 'cowork' || agentType === 'Cowork'; } -function isClawAgent(agentType: string): boolean { - return agentType === 'claw' || agentType === 'Claw'; -} - /** Pick first workspace suitable for Expert mode (exclude Claw assistant roots when kind is known). */ function pickFirstProWorkspace(list: RecentWorkspaceEntry[]): RecentWorkspaceEntry | undefined { if (list.length === 0) return undefined; @@ -434,15 +450,37 @@ const SessionListPage: React.FC = ({ clearLongPressTimer(); }, []); - const handleSessionClick = useCallback((s: SessionInfo, e: React.MouseEvent) => { + // The flat list is scoped by the selected mode; compact rows name their own owner. + const listWorkspaceOwner = useMemo(() => { + if (displayMode === 'assistant') { + return currentAssistant ? workspaceContext({ ...currentAssistant, workspace_kind: 'assistant' }) : undefined; + } + return currentWorkspace ? workspaceContext(currentWorkspace) : undefined; + }, [currentAssistant, currentWorkspace, displayMode]); + + const listedSessionWorkspace = useCallback((session: SessionInfo) => { + const owner = listWorkspaceOwner; + return sessionWorkspaceContext( + session, + owner?.path && sessionMatchesWorkspace(session, { ...owner, path: owner.path }) ? owner : undefined, + ); + }, [listWorkspaceOwner]); + + const handleSessionClick = useCallback((s: SessionInfo, e: React.MouseEvent, owner?: RecentWorkspaceEntry) => { if (longPressTriggeredRef.current) { e.preventDefault(); e.stopPropagation(); longPressTriggeredRef.current = false; return; } - onSelectSession(s.session_id, s.name, false, s.agent_type); - }, [onSelectSession]); + onSelectSession( + s.session_id, + s.name, + false, + s.agent_type, + owner ? sessionWorkspaceContext(s, workspaceContext(owner)) : listedSessionWorkspace(s), + ); + }, [listedSessionWorkspace, onSelectSession]); // ── Session actions ───────────────────────────────────────────── const showToast = useCallback((msg: string) => { @@ -1031,7 +1069,7 @@ const SessionListPage: React.FC = ({ workspaceIdentity: createdIdentity, replaceWorkspace: true, }); - onSelectSession(created.session_id, t(isClawAgent(agentType) ? 'sessions.remoteClawSession' : isCoworkAgent(agentType) ? 'sessions.remoteCoworkSession' : 'sessions.remoteCodeSession'), true, agentType); + onSelectSession(created.session_id, t(isClawAgent(agentType) ? 'sessions.remoteClawSession' : isCoworkAgent(agentType) ? 'sessions.remoteCoworkSession' : 'sessions.remoteCodeSession'), true, agentType, createdSessionWorkspace(createdPath, createdIdentity, workspaceContext(workspace))); } catch (error: unknown) { if (isSessionListCurrent(targetEpoch) && !isRemoteControlTargetChangedError(error)) { setError(describeRemoteError(error, t)); @@ -1430,14 +1468,15 @@ const SessionListPage: React.FC = ({ remoteConnectionId: created.remote_connection_id ?? identity.remoteConnectionId, remoteSshHost: created.remote_ssh_host ?? identity.remoteSshHost, }; - await loadFirstPage(created.workspace_path ?? workspacePath, searchQuery, createdIdentity); + const createdPath = created.workspace_path ?? workspacePath; + await loadFirstPage(createdPath, searchQuery, createdIdentity); if (!isSessionListCurrent(targetEpoch)) return; const label = isClawAgent(agentType) ? t('sessions.remoteClawSession') : isCoworkAgent(agentType) ? t('sessions.remoteCoworkSession') : t('sessions.remoteCodeSession'); - onSelectSession(created.session_id, label, true, agentType); + onSelectSession(created.session_id, label, true, agentType, createdSessionWorkspace(createdPath, createdIdentity, listWorkspaceOwner)); } catch (e: any) { if (isSessionListCurrent(targetEpoch) && !isRemoteControlTargetChangedError(e)) { setError(describeRemoteError(e, t)); @@ -1452,6 +1491,7 @@ const SessionListPage: React.FC = ({ currentAssistant, displayMode, isSessionListCurrent, + listWorkspaceOwner, loadFirstPage, onSelectSession, searchQuery, @@ -1686,7 +1726,7 @@ const SessionListPage: React.FC = ({ key={session.session_id} onContextMenu={(event) => { event.preventDefault(); setMenuSession(session); }} > - handleSessionClick(session, event)}> + handleSessionClick(session, event, workspace)}> {session.name || t('sessions.untitledSession')} @@ -1859,7 +1899,7 @@ const SessionListPage: React.FC = ({ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); - onSelectSession(sessions[0].session_id, sessions[0].name, false, sessions[0].agent_type); + onSelectSession(sessions[0].session_id, sessions[0].name, false, sessions[0].agent_type, listedSessionWorkspace(sessions[0])); } }} > diff --git a/src/mobile-web/src/services/MobileNavigationStore.ts b/src/mobile-web/src/services/MobileNavigationStore.ts index bb7c941115..bec39eff2f 100644 --- a/src/mobile-web/src/services/MobileNavigationStore.ts +++ b/src/mobile-web/src/services/MobileNavigationStore.ts @@ -1,4 +1,5 @@ import { canonicalAgentId } from '../../../shared/agent-harness/contract.generated'; +import type { SessionWorkspaceContext } from './workspaceIdentity'; const STORAGE_KEY = 'openbitfun.mobile.navigation.v1'; export interface MobileNavigationScope { @@ -11,7 +12,7 @@ export interface MobileNavigationScope { export interface MobileNavigation { deviceId: string; disconnected?: boolean; - session?: { id: string; name: string; agentType: string }; + session?: { id: string; name: string; agentType: string; workspace?: SessionWorkspaceContext }; } export interface PairedNavigation { @@ -21,6 +22,23 @@ export interface PairedNavigation { type StorageLike = Pick; +/** Additive session field: records from older builds omit it, and bad values are dropped. */ +function readSessionWorkspace(value: unknown): SessionWorkspaceContext | undefined { + if (!value || typeof value !== 'object') return undefined; + const record = value as Record; + const text = (field: string) => (typeof record[field] === 'string' ? record[field] as string : undefined); + const kind = text('workspace_kind'); + const workspace: SessionWorkspaceContext = { + workspace_id: text('workspace_id'), + path: text('path'), + remote_connection_id: text('remote_connection_id'), + remote_ssh_host: text('remote_ssh_host'), + name: text('name'), + workspace_kind: kind === 'normal' || kind === 'assistant' || kind === 'remote' ? kind : undefined, + }; + return workspace.workspace_id || workspace.path || workspace.name ? workspace : undefined; +} + function browserStorage(): StorageLike | null { try { return typeof window === 'undefined' ? null : window.sessionStorage; } catch { return null; } @@ -42,12 +60,18 @@ export function loadMobileNavigation( || typeof record.deviceId !== 'string' || !record.deviceId.trim()) return null; const session = record.session; + const workspace = readSessionWorkspace(session?.workspace); return { deviceId: record.deviceId, ...(record.disconnected === true ? { disconnected: true } : {}), session: session && typeof session.id === 'string' && session.id.trim() && typeof session.name === 'string' && typeof session.agentType === 'string' - ? { id: session.id, name: session.name, agentType: canonicalAgentId(session.agentType) } + ? { + id: session.id, + name: session.name, + agentType: canonicalAgentId(session.agentType), + ...(workspace ? { workspace } : {}), + } : undefined, }; } catch { diff --git a/src/mobile-web/src/services/workspaceIdentity.ts b/src/mobile-web/src/services/workspaceIdentity.ts index b4f6b649eb..f61b8f6c79 100644 --- a/src/mobile-web/src/services/workspaceIdentity.ts +++ b/src/mobile-web/src/services/workspaceIdentity.ts @@ -1,4 +1,4 @@ -import type { AssistantEntry, RecentWorkspaceEntry, SessionInfo } from './RemoteSessionManager'; +import type { AssistantEntry, RecentWorkspaceEntry, SessionInfo, WorkspaceInfo } from './RemoteSessionManager'; export interface WorkspaceCatalog { workspaces: RecentWorkspaceEntry[]; @@ -234,3 +234,97 @@ export function workspaceDisplayName( if (basename) return basename; return remoteSshHost?.trim() || remoteConnectionId?.trim() || 'Workspace'; } + +/** Claw sessions run in an assistant workspace, which is never a project checkout. */ +export function isClawAgent(agentType: string): boolean { + return agentType === 'claw' || agentType === 'Claw'; +} + +/** + * The workspace a session belongs to, captured when the session is opened. Every + * field is optional because pre-ID hosts and old navigation records omit them. + */ +export interface SessionWorkspaceContext extends WorkspaceReference { + name?: string; + workspace_kind?: RecentWorkspaceEntry['workspace_kind']; +} + +export function workspaceContext(workspace: WorkspaceReference & { + name?: string; + project_name?: string; + workspace_kind?: RecentWorkspaceEntry['workspace_kind']; +}): SessionWorkspaceContext { + return { + workspace_id: workspace.workspace_id, + path: workspace.path, + remote_connection_id: workspace.remote_connection_id, + remote_ssh_host: workspace.remote_ssh_host, + name: workspace.name ?? workspace.project_name, + workspace_kind: workspace.workspace_kind, + }; +} + +/** + * Merge a session's own facts with the workspace row that owns it. The session + * decides identity because the host pinned it; the owner supplies the display + * name and kind, since `workspace_name` is only the workspace's root label. + */ +export function sessionWorkspaceContext( + session: Partial>, + owner?: SessionWorkspaceContext, +): SessionWorkspaceContext | undefined { + const provenance = session.workspace_identity; + const context: SessionWorkspaceContext = { + workspace_id: session.workspace_id ?? provenance?.workspace_id ?? owner?.workspace_id, + path: provenance?.path || session.workspace_path || owner?.path, + remote_connection_id: provenance?.remote_connection_id ?? owner?.remote_connection_id, + remote_ssh_host: provenance?.remote_ssh_host ?? owner?.remote_ssh_host, + name: owner?.name ?? session.workspace_name, + workspace_kind: owner?.workspace_kind, + }; + return context.workspace_id || context.path || context.name ? context : undefined; +} + +export interface ChatHeaderContext { + workspaceName: string; + gitBranch?: string; +} + +/** + * Header facts for one session. The store's current workspace and assistant are + * selections, not the session's owner: they only contribute when they are the + * same workspace. A branch is known only for the current workspace, and an + * unattributed non-assistant session shows nothing rather than a guess. + */ +export function resolveChatHeaderContext({ + agentType, + session, + currentWorkspace, + currentAssistant, + assistantLabel, +}: { + agentType: string; + session?: SessionWorkspaceContext; + currentWorkspace?: WorkspaceInfo | null; + currentAssistant?: AssistantEntry | null; + assistantLabel: string; +}): ChatHeaderContext { + const sessionIsCurrentAssistant = sameWorkspace(session, currentAssistant); + if (isClawAgent(agentType) || session?.workspace_kind === 'assistant' || sessionIsCurrentAssistant) { + const selectedAssistant = !session || sessionIsCurrentAssistant ? currentAssistant : undefined; + return { workspaceName: selectedAssistant?.name.trim() || session?.name?.trim() || assistantLabel }; + } + if (!session) return { workspaceName: '' }; + const current = currentWorkspace && sameWorkspace(session, normalizeWorkspaceRouting(currentWorkspace)) + ? currentWorkspace + : undefined; + return { + workspaceName: workspaceDisplayName( + current?.project_name || session.name, + session.path, + session.remote_ssh_host, + session.remote_connection_id, + ), + gitBranch: current?.git_branch, + }; +} diff --git a/src/mobile-web/tests/account-login.test.mjs b/src/mobile-web/tests/account-login.test.mjs index 52181235be..1f217fbc1b 100644 --- a/src/mobile-web/tests/account-login.test.mjs +++ b/src/mobile-web/tests/account-login.test.mjs @@ -443,3 +443,24 @@ test('a dropped connection mid-sign-in is retried instead of ending the attempt' assert.equal(offline.error.message, 'Could not reach the account service.'); assert.equal(offline.polls.length, 60); }); + +test('restored session workspace is additive: old records stay readable and bad values are dropped', () => { + const scope = { accountId: 'a', controllerDeviceId: 'c', relayUrl: 'r', routeKey: 'k' }; + const stored = (session) => ({ + getItem: () => JSON.stringify({ version: 1, ...scope, deviceId: 'device', session }), + setItem() {}, removeItem() {}, + }); + const old = { id: 's', name: 'Session', agentType: 'Claw' }; + assert.deepEqual(loadMobileNavigation(scope, stored(old)).session, old); + assert.deepEqual(loadMobileNavigation(scope, stored({ ...old, workspace: 'bad' })).session, old); + assert.deepEqual(loadMobileNavigation(scope, stored({ ...old, workspace: { path: 42, name: null } })).session, old); + assert.deepEqual( + loadMobileNavigation(scope, stored({ + ...old, workspace: { workspace_id: 'ws', name: 'Nova', workspace_kind: 'future-kind' }, + })).session.workspace, + { + workspace_id: 'ws', path: undefined, remote_connection_id: undefined, + remote_ssh_host: undefined, name: 'Nova', workspace_kind: undefined, + }, + ); +}); diff --git a/src/mobile-web/tests/browser-account.test.mjs b/src/mobile-web/tests/browser-account.test.mjs index 413469f400..782d2ca466 100644 --- a/src/mobile-web/tests/browser-account.test.mjs +++ b/src/mobile-web/tests/browser-account.test.mjs @@ -59,6 +59,64 @@ test('assistant workspace plus creates a session whose first message reaches the } finally {await browser.close();await server.close();} }); +test('chat header follows the session workspace, not the selected project and branch', { timeout: 60000 }, async () => { + const server=await startSourceServer();const browser=await launchBrowser(); + try { + for(const width of [390,1280]) { + const context=await browser.createIncognitoBrowserContext(); + try { + const page=await context.newPage();await page.setViewport({width,height:844});await page.goto(server.origin); + await page.evaluate(async()=>{ + const {mountAssistantSessionFixture}=await import('/tests/fixtures/assistant-session.tsx'); + window.assistantFixture=await mountAssistantSessionFixture({selectedProject:true}); + }); + const headerText=async()=>{ + await page.waitForSelector('.chat-page__input'); + await page.waitForFunction(()=>Boolean(document.querySelector('.chat-page__workspace-name')?.textContent)); + return page.evaluate(()=>({ + workspace:document.querySelector('.chat-page__workspace-name').textContent, + branch:document.querySelector('.chat-page__workspace-branch')?.textContent??null, + })); + }; + const backToList=async()=>{ + await page.evaluate(()=>document.querySelector('.chat-page__back').click()); + await page.waitForSelector('.harmony-sidebar__workspace-group'); + }; + const openSession=async(workspace,sessionName)=>{ + await page.waitForFunction(workspace=>[...document.querySelectorAll('.harmony-sidebar__workspace-main')] + .some(node=>node.textContent.includes(workspace)),{},workspace); + await page.evaluate((workspace,sessionName)=>{ + const group=[...document.querySelectorAll('.harmony-sidebar__workspace-group')] + .find(node=>node.querySelector('.harmony-sidebar__workspace-main').textContent.includes(workspace)); + const open=[...group.querySelectorAll('.harmony-sidebar__session-main')].some(node=>node.textContent.includes(sessionName)); + if(!open)group.querySelector('.harmony-sidebar__workspace-main').click(); + },workspace,sessionName); + await page.waitForFunction(sessionName=>[...document.querySelectorAll('.harmony-sidebar__session-main')] + .some(node=>node.textContent.includes(sessionName)),{},sessionName); + await page.evaluate(sessionName=>[...document.querySelectorAll('.harmony-sidebar__session-main')] + .find(node=>node.textContent.includes(sessionName)).click(),sessionName); + }; + // New assistant session while the host has `home / master` selected. + await page.waitForSelector('button[aria-label="Assistant · New Session"]'); + await page.click('button[aria-label="Assistant · New Session"]'); + assert.deepEqual(await headerText(),{workspace:'Assistant',branch:null}); + await backToList(); + // Existing assistant session opened from its catalog row. + await openSession('Assistant','New Session'); + assert.deepEqual(await headerText(),{workspace:'Assistant',branch:null}); + await backToList(); + // The selected project keeps its branch. + await openSession('home','home session'); + assert.deepEqual(await headerText(),{workspace:'home',branch:'master'}); + await backToList(); + // Another project shows its own name and no unknown branch. + await openSession('api','api session'); + assert.deepEqual(await headerText(),{workspace:'api',branch:null}); + } finally {await context.close();} + } + } finally {await browser.close();await server.close();} +}); + test('pre-fix assistant outbox retries with its original ID, content and attachments after reopening', { timeout: 60000 }, async () => { const server=await startSourceServer();const browser=await launchBrowser(); try { diff --git a/src/mobile-web/tests/fixtures/assistant-session.tsx b/src/mobile-web/tests/fixtures/assistant-session.tsx index 74f603bcbf..54b68775cb 100644 --- a/src/mobile-web/tests/fixtures/assistant-session.tsx +++ b/src/mobile-web/tests/fixtures/assistant-session.tsx @@ -10,18 +10,28 @@ import { I18nProvider } from '../../src/i18n'; import { ThemeProvider } from '../../src/theme'; import { useMobileStore } from '../../src/services/store'; import { RemoteSessionManager, type SessionInfo } from '../../src/services/RemoteSessionManager'; +import type { SessionWorkspaceContext } from '../../src/services/workspaceIdentity'; import type { RelayHttpClient } from '../../src/services/RelayHttpClient'; import { queueStorage, type QueueItem, type QueueOutboxRecord } from '../../../shared/dialog-queue/HostDialogQueue'; /** Real sidebar, chat, manager and durable outbox; only host IO is simulated. */ -export async function mountAssistantSessionFixture({ legacyWorkspace = false, queueSupported = true, legacyPending = false } = {}) { +export async function mountAssistantSessionFixture({ legacyWorkspace = false, queueSupported = true, legacyPending = false, selectedProject = false } = {}) { const account = 'assistant-mode-account', device = 'assistant-mode-host', sessionId = 'assistant-session'; const capabilities = ['host_stream_v1', ...(queueSupported ? ['dialog_queue_v1'] : []), ...(legacyWorkspace ? [] : ['workspace_id_references_v1', 'harness_profiles_v1'])]; const assistant = { ...(legacyWorkspace ? {} : { workspace_id: 'assistant-workspace' }), path: '/fixtures/assistant', name: 'Assistant', workspace_kind: 'assistant' as const, last_opened: '' }; const session: SessionInfo = { session_id: sessionId, name: 'New Session', agent_type: 'Claw', - workspace_id: assistant.workspace_id, workspace_path: assistant.path, created_at: '1', updated_at: '1', message_count: 0 }; + workspace_id: assistant.workspace_id, workspace_path: assistant.path, created_at: '1', updated_at: '1', message_count: 0, + // The host sends the root label; the assistant identity name lives on the catalog row. + ...(selectedProject ? { workspace_name: 'workspace' } : {}) }; + // Issue 2360 shape: the host's selected workspace is a Git project, not the assistant. + const project = (name: string) => ({ workspace_id: `${name}-workspace`, path: `/fixtures/${name}`, name, + workspace_kind: 'normal' as const, last_opened: '' }); + const projects = selectedProject ? [project('home'), project('api')] : []; + const projectSessions: SessionInfo[] = projects.map((workspace) => ({ session_id: `${workspace.name}-session`, + name: `${workspace.name} session`, agent_type: 'agentic', workspace_id: workspace.workspace_id, + workspace_path: workspace.path, workspace_name: workspace.name, created_at: '1', updated_at: '1', message_count: 0 })); const calls: Array> = [], sessions: SessionInfo[] = legacyPending ? [session] : []; const receipts = new Map(); const scope = JSON.stringify([account, device, sessionId]); @@ -45,11 +55,16 @@ export async function mountAssistantSessionFixture({ legacyWorkspace = false, qu async sendDeviceRpc(target: string, command: Record) { calls.push(structuredClone({ device: target, ...command })); switch (command.cmd) { - case 'get_workspace_info': return { resp: 'workspace_info', ...assistant, has_workspace: true, capabilities }; - case 'list_recent_workspaces': return { resp: 'recent_workspaces', workspaces: [assistant], - ...(legacyWorkspace ? {} : { opened_workspaces: [assistant] }) }; + case 'get_workspace_info': return selectedProject + ? { resp: 'workspace_info', workspace_id: projects[0].workspace_id, path: projects[0].path, project_name: projects[0].name, + git_branch: 'master', workspace_kind: 'normal', has_workspace: true, capabilities } + : { resp: 'workspace_info', ...assistant, has_workspace: true, capabilities }; + case 'list_recent_workspaces': return { resp: 'recent_workspaces', workspaces: [assistant, ...projects], + ...(legacyWorkspace ? {} : { opened_workspaces: [assistant, ...projects] }) }; case 'list_assistants': return { resp: 'assistant_list', assistants: [assistant] }; - case 'list_sessions': return { resp: 'sessions', sessions, has_more: false }; + case 'list_sessions': return { resp: 'sessions', has_more: false, sessions: selectedProject + ? [...sessions, ...projectSessions].filter((row) => row.workspace_id === command.workspace_id) + : sessions }; // The RemoteCommand create path accepts the mobile alias. The queue // invokes the runtime directly and requires its registered mode ID. case 'create_session': sessions.push(session); return { resp: 'session_created', ...session }; @@ -82,19 +97,21 @@ export async function mountAssistantSessionFixture({ legacyWorkspace = false, qu const manager = new RemoteSessionManager(client, capabilities); useMobileStore.getState().resetForDeviceSwitch(); useMobileStore.setState({ authenticatedUserId: account, connectionHealth: 'connected', - controlTarget: { deviceId: device, deviceName: 'Host' }, error: null }); + // A paired relay has no device name, so the header shows the workspace line. + controlTarget: { deviceId: device, deviceName: selectedProject ? null : 'Host' }, error: null }); localStorage.setItem('openbitfun-mobile-language', 'en-US'); const element = document.createElement('main'); element.className = 'mobile-app'; document.body.replaceChildren(element); const root = createRoot(element); function Fixture() { - const [selected, setSelected] = useState<{ id: string; agentType?: string } | null>(legacyPending ? { id: sessionId, agentType: 'Claw' } : null); + const [selected, setSelected] = useState<{ id: string; agentType?: string; workspace?: SessionWorkspaceContext } | null>(legacyPending ? { id: sessionId, agentType: 'Claw' } : null); return {selected ? setSelected(null)} wideLayout={window.innerWidth >= 900} /> : setSelected({ id, agentType })} + onSelectSession={(id, _name, _isNew, agentType, workspace) => setSelected({ id, agentType, workspace })} onOpenWorkspace={() => {}} onDisconnect={() => {}} /> }; } diff --git a/src/mobile-web/tests/workspace-identity.test.mjs b/src/mobile-web/tests/workspace-identity.test.mjs index 77d1fd9634..bb539c0993 100644 --- a/src/mobile-web/tests/workspace-identity.test.mjs +++ b/src/mobile-web/tests/workspace-identity.test.mjs @@ -10,6 +10,7 @@ const code = ts.transpileModule(source, { const { mergeWorkspaceSessions, sessionMatchesWorkspace, workspaceIdentityKey, resolveLegacyWorkspaceReference, sameWorkspace, + isClawAgent, resolveChatHeaderContext, sessionWorkspaceContext, workspaceContext, } = await import( `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` ); @@ -432,3 +433,104 @@ test('workspace icons reject future formats and external image URLs without loca assert.equal(calls, 1); } }); + +const home = { + workspace_id: 'ws-home', has_workspace: true, path: '/Users/me/home', + project_name: 'home', git_branch: 'master', workspace_kind: 'normal', +}; +const claw = { workspace_id: 'ws-claw', path: '/Users/me/.bitfun/personal_assistant/workspace', name: 'Nova' }; +const header = (overrides) => resolveChatHeaderContext({ + agentType: 'Standard', + currentWorkspace: home, + currentAssistant: null, + assistantLabel: 'Claw', + ...overrides, +}); + +test('assistant sessions never inherit the selected normal workspace or its branch', () => { + // Issue 2360: Pro mode selected `home / master`, then a Claw session is opened. + const owner = workspaceContext({ ...claw, workspace_kind: 'assistant' }); + const session = sessionWorkspaceContext({ + workspace_id: 'ws-claw', workspace_path: claw.path, workspace_name: 'workspace', + }, owner); + assert.deepEqual(header({ agentType: 'Claw', session }), { workspaceName: 'Nova' }); + // A catalog row may carry the kind without the agent type saying Claw. + assert.deepEqual(header({ agentType: 'Cowork', session }), { workspaceName: 'Nova' }); + // The selected assistant is matched by identity and supplies the current name. + assert.deepEqual( + header({ agentType: 'claw', session: { path: claw.path }, currentAssistant: claw }), + { workspaceName: 'Nova' }, + ); +}); + +test('a different selected assistant does not rename an attributed assistant session', () => { + const session = { workspace_id: 'ws-claw', path: claw.path, name: 'Nova', workspace_kind: 'assistant' }; + const other = { workspace_id: 'ws-other', path: '/Users/me/other', name: 'Other' }; + assert.deepEqual(header({ agentType: 'Claw', session, currentAssistant: other }), { workspaceName: 'Nova' }); +}); + +test('assistant sessions without workspace facts use the selection, then the localized label', () => { + // Navigation restored from an older build only knows the agent type. + assert.deepEqual(header({ agentType: 'Claw', currentAssistant: claw }), { workspaceName: 'Nova' }); + assert.deepEqual(header({ agentType: 'Claw' }), { workspaceName: 'Claw' }); +}); + +test('normal sessions show their own workspace and a branch only for the current workspace', () => { + assert.deepEqual( + header({ session: { workspace_id: 'ws-home', path: home.path, name: 'stale label' } }), + { workspaceName: 'home', gitBranch: 'master' }, + ); + assert.deepEqual( + header({ session: { workspace_id: 'ws-api', path: '/Users/me/api', name: 'api' } }), + { workspaceName: 'api', gitBranch: undefined }, + ); + assert.deepEqual( + header({ session: { path: '/Users/me/api/' } }), + { workspaceName: 'api', gitBranch: undefined }, + ); + // No session facts: show nothing rather than guess from the selection. + assert.deepEqual(header({}), { workspaceName: '' }); +}); + +test('same-path SSH sessions keep their branch scoped to the selected host', () => { + const sshA = { + has_workspace: true, path: a.path, project_name: 'herdr', git_branch: 'main', + workspace_kind: 'remote', remote_connection_id: 'ssh-a', remote_ssh_host: 'host-a', + }; + assert.deepEqual( + header({ currentWorkspace: sshA, session: { ...b, name: 'herdr' } }), + { workspaceName: 'herdr', gitBranch: undefined }, + ); + assert.deepEqual( + header({ currentWorkspace: sshA, session: { ...a, name: 'herdr' } }), + { workspaceName: 'herdr', gitBranch: 'main' }, + ); +}); + +test('legacy localhost markers on the current workspace still match the local session', () => { + const legacy = { ...home, workspace_id: undefined, remote_ssh_host: 'localhost' }; + assert.deepEqual( + header({ currentWorkspace: legacy, session: { path: home.path } }), + { workspaceName: 'home', gitBranch: 'master' }, + ); +}); + +test('session workspace context keeps host identity and takes only display facts from the owner', () => { + const owner = workspaceContext({ ...a, workspace_id: 'ws-owner', name: 'Row name', workspace_kind: 'remote' }); + assert.deepEqual(sessionWorkspaceContext({ + workspace_id: 'ws-session', workspace_path: '/pinned', workspace_name: 'host label', + }, owner), { + workspace_id: 'ws-session', path: '/pinned', + remote_connection_id: 'ssh-a', remote_ssh_host: 'host-a', + name: 'Row name', workspace_kind: 'remote', + }); + // Pre-ID rows carry only the path and root label. + assert.deepEqual(sessionWorkspaceContext({ workspace_path: '/p', workspace_name: 'p' }), { + workspace_id: undefined, path: '/p', remote_connection_id: undefined, remote_ssh_host: undefined, + name: 'p', workspace_kind: undefined, + }); + assert.equal(sessionWorkspaceContext({}), undefined); + assert.equal(isClawAgent('claw'), true); + assert.equal(isClawAgent('Claw'), true); + assert.equal(isClawAgent('Cowork'), false); +}); From 3100d4c2b292ef7baf7839f0a5dbe71fac14229a Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:19:59 +0800 Subject: [PATCH 2/5] fix(mobile-web): gate rollback on the session workspace The rollback gate read the selected workspace, so a session opened from another workspace could get the wrong answer. Decide it from the same session context as the header. Also compare localhost markers from older hosts on both sides when matching the selected workspace, apply a selected owner to a created session only when it matches, and clear the session workspace when leaving the chat. --- src/mobile-web/src/App.tsx | 10 ++- src/mobile-web/src/pages/ChatPage.tsx | 8 +-- src/mobile-web/src/pages/SessionListPage.tsx | 26 +++----- .../src/services/workspaceIdentity.ts | 46 ++++++++++++-- .../tests/workspace-identity.test.mjs | 63 ++++++++++++++++++- 5 files changed, 126 insertions(+), 27 deletions(-) diff --git a/src/mobile-web/src/App.tsx b/src/mobile-web/src/App.tsx index e2badd859c..e356d3d772 100644 --- a/src/mobile-web/src/App.tsx +++ b/src/mobile-web/src/App.tsx @@ -219,7 +219,10 @@ const AppContent: React.FC = () => { // Pop navigation handlers that can be called from both UI buttons and popstate const doPopFromChat = useCallback(() => { navigateTo('sessions', 'pop'); - setTimeout(() => setActiveSessionId(null), NAV_DURATION); + setTimeout(() => { + setActiveSessionId(null); + setActiveSessionWorkspace(undefined); + }, NAV_DURATION); }, [navigateTo]); const doPopFromWorkspace = useCallback(() => { @@ -307,7 +310,10 @@ const AppContent: React.FC = () => { const handleBackToSessions = useCallback(() => { navigateTo('sessions', 'pop'); - setTimeout(() => setActiveSessionId(null), NAV_DURATION); + setTimeout(() => { + setActiveSessionId(null); + setActiveSessionWorkspace(undefined); + }, NAV_DURATION); }, [navigateTo]); const handleControlTargetChanged = useCallback(() => { diff --git a/src/mobile-web/src/pages/ChatPage.tsx b/src/mobile-web/src/pages/ChatPage.tsx index 7c28d1a3ea..31d2a70293 100644 --- a/src/mobile-web/src/pages/ChatPage.tsx +++ b/src/mobile-web/src/pages/ChatPage.tsx @@ -23,6 +23,7 @@ import { } from '../services/chatImageAttachments'; import { useMobileStore } from '../services/store'; import { + isRemoteSessionWorkspace, resolveChatHeaderContext, sessionWorkspaceContext, type SessionWorkspaceContext, @@ -1163,17 +1164,16 @@ const ChatPage: React.FC = ({ // Restored navigation from an older build has no workspace; the loaded session row may. const listedSession = sessionWorkspace ? undefined : sessions.find((session) => session.session_id === sessionId); + const sessionContext = sessionWorkspace ?? (listedSession && sessionWorkspaceContext(listedSession)); const { workspaceName, gitBranch } = resolveChatHeaderContext({ agentType: sessionAgentType, - session: sessionWorkspace ?? (listedSession && sessionWorkspaceContext(listedSession)), + session: sessionContext, currentWorkspace, currentAssistant, assistantLabel: t('shared.agents.Claw'), }); const displayName = liveTitle || sessionName || t('chat.session'); - const isRemoteWorkspace = currentWorkspace?.workspace_kind === 'remote' - || Boolean(currentWorkspace?.remote_connection_id) - || Boolean(currentWorkspace?.remote_ssh_host); + const isRemoteWorkspace = isRemoteSessionWorkspace(sessionAgentType, sessionContext, currentWorkspace); return (
diff --git a/src/mobile-web/src/pages/SessionListPage.tsx b/src/mobile-web/src/pages/SessionListPage.tsx index 3d595e2684..c0b0cde827 100644 --- a/src/mobile-web/src/pages/SessionListPage.tsx +++ b/src/mobile-web/src/pages/SessionListPage.tsx @@ -65,11 +65,13 @@ import { deviceFailurePresentation } from '../services/deviceFailureCopy'; import { isClawAgent, sameWorkspace, + selectedSessionWorkspaceContext, sessionMatchesWorkspace, sessionWorkspaceContext, workspaceContext, workspaceIdentityKey, type SessionWorkspaceContext, + type SessionWorkspaceFacts, type WorkspaceReference, } from '../services/workspaceIdentity'; import { useTheme } from '../theme'; @@ -144,19 +146,15 @@ function commandIdentity( }; } -function createdSessionWorkspace( - path: string, - identity: RemoteWorkspaceIdentity, - owner?: SessionWorkspaceContext, -): SessionWorkspaceContext | undefined { - return sessionWorkspaceContext({ +function createdSessionFacts(path: string, identity: RemoteWorkspaceIdentity): SessionWorkspaceFacts { + return { workspace_id: identity.workspaceId, workspace_path: path, workspace_identity: { remote_connection_id: identity.remoteConnectionId, remote_ssh_host: identity.remoteSshHost, }, - }, owner); + }; } function assistantIdentity(assistant: AssistantEntry | null | undefined): RemoteWorkspaceIdentity { @@ -458,13 +456,9 @@ const SessionListPage: React.FC = ({ return currentWorkspace ? workspaceContext(currentWorkspace) : undefined; }, [currentAssistant, currentWorkspace, displayMode]); - const listedSessionWorkspace = useCallback((session: SessionInfo) => { - const owner = listWorkspaceOwner; - return sessionWorkspaceContext( - session, - owner?.path && sessionMatchesWorkspace(session, { ...owner, path: owner.path }) ? owner : undefined, - ); - }, [listWorkspaceOwner]); + const listedSessionWorkspace = useCallback((session: SessionInfo) => ( + selectedSessionWorkspaceContext(session, listWorkspaceOwner) + ), [listWorkspaceOwner]); const handleSessionClick = useCallback((s: SessionInfo, e: React.MouseEvent, owner?: RecentWorkspaceEntry) => { if (longPressTriggeredRef.current) { @@ -1069,7 +1063,7 @@ const SessionListPage: React.FC = ({ workspaceIdentity: createdIdentity, replaceWorkspace: true, }); - onSelectSession(created.session_id, t(isClawAgent(agentType) ? 'sessions.remoteClawSession' : isCoworkAgent(agentType) ? 'sessions.remoteCoworkSession' : 'sessions.remoteCodeSession'), true, agentType, createdSessionWorkspace(createdPath, createdIdentity, workspaceContext(workspace))); + onSelectSession(created.session_id, t(isClawAgent(agentType) ? 'sessions.remoteClawSession' : isCoworkAgent(agentType) ? 'sessions.remoteCoworkSession' : 'sessions.remoteCodeSession'), true, agentType, sessionWorkspaceContext(createdSessionFacts(createdPath, createdIdentity), workspaceContext(workspace))); } catch (error: unknown) { if (isSessionListCurrent(targetEpoch) && !isRemoteControlTargetChangedError(error)) { setError(describeRemoteError(error, t)); @@ -1476,7 +1470,7 @@ const SessionListPage: React.FC = ({ : isCoworkAgent(agentType) ? t('sessions.remoteCoworkSession') : t('sessions.remoteCodeSession'); - onSelectSession(created.session_id, label, true, agentType, createdSessionWorkspace(createdPath, createdIdentity, listWorkspaceOwner)); + onSelectSession(created.session_id, label, true, agentType, selectedSessionWorkspaceContext(createdSessionFacts(createdPath, createdIdentity), listWorkspaceOwner)); } catch (e: any) { if (isSessionListCurrent(targetEpoch) && !isRemoteControlTargetChangedError(e)) { setError(describeRemoteError(e, t)); diff --git a/src/mobile-web/src/services/workspaceIdentity.ts b/src/mobile-web/src/services/workspaceIdentity.ts index f61b8f6c79..56fc8de4f2 100644 --- a/src/mobile-web/src/services/workspaceIdentity.ts +++ b/src/mobile-web/src/services/workspaceIdentity.ts @@ -130,8 +130,13 @@ export function resolveLegacyWorkspaceReference( return matches.length === 1 ? matches[0] : undefined; } +/** The workspace facts a session row or a `session_created` reply can carry. */ +export type SessionWorkspaceFacts = Partial< + Pick +>; + /** The workspace a session claims, merged from host facts and cache provenance. */ -function sessionWorkspaceReference(session: SessionInfo): WorkspaceReference | undefined { +function sessionWorkspaceReference(session: SessionWorkspaceFacts): WorkspaceReference | undefined { const provenance = session.workspace_identity; const workspaceId = session.workspace_id ?? provenance?.workspace_id; if (!provenance && !workspaceId) return undefined; @@ -153,7 +158,7 @@ function sessionWorkspaceReference(session: SessionInfo): WorkspaceReference | u * local workspace being asked about. */ export function sessionMatchesWorkspace( - session: SessionInfo, + session: SessionWorkspaceFacts, workspace: WorkspaceIdentity, catalog: readonly WorkspaceIdentity[] = [], ): boolean { @@ -270,7 +275,7 @@ export function workspaceContext(workspace: WorkspaceReference & { * name and kind, since `workspace_name` is only the workspace's root label. */ export function sessionWorkspaceContext( - session: Partial>, + session: SessionWorkspaceFacts, owner?: SessionWorkspaceContext, ): SessionWorkspaceContext | undefined { const provenance = session.workspace_identity; @@ -285,6 +290,19 @@ export function sessionWorkspaceContext( return context.workspace_id || context.path || context.name ? context : undefined; } +/** For a selection that may have moved on: its display facts apply only if it owns the session. */ +export function selectedSessionWorkspaceContext( + session: SessionWorkspaceFacts, + selection?: SessionWorkspaceContext, +): SessionWorkspaceContext | undefined { + return sessionWorkspaceContext( + session, + selection?.path && sessionMatchesWorkspace(session, { ...selection, path: selection.path }) + ? selection + : undefined, + ); +} + export interface ChatHeaderContext { workspaceName: string; gitBranch?: string; @@ -298,7 +316,7 @@ export interface ChatHeaderContext { */ export function resolveChatHeaderContext({ agentType, - session, + session: sessionContext, currentWorkspace, currentAssistant, assistantLabel, @@ -309,6 +327,8 @@ export function resolveChatHeaderContext({ currentAssistant?: AssistantEntry | null; assistantLabel: string; }): ChatHeaderContext { + // Older hosts mark local records with sshHost=localhost, so compare both sides routed. + const session = sessionContext && normalizeWorkspaceRouting(sessionContext); const sessionIsCurrentAssistant = sameWorkspace(session, currentAssistant); if (isClawAgent(agentType) || session?.workspace_kind === 'assistant' || sessionIsCurrentAssistant) { const selectedAssistant = !session || sessionIsCurrentAssistant ? currentAssistant : undefined; @@ -328,3 +348,21 @@ export function resolveChatHeaderContext({ gitBranch: current?.git_branch, }; } + +/** + * Whether the open session runs on an SSH workspace, which keeps rollback off. + * The selected workspace only decides when the session has no workspace facts. + */ +export function isRemoteSessionWorkspace( + agentType: string, + session: SessionWorkspaceContext | undefined, + currentWorkspace: WorkspaceInfo | null | undefined, +): boolean { + if (isClawAgent(agentType) || session?.workspace_kind === 'assistant') return false; + const owner = session ?? currentWorkspace; + if (!owner) return false; + const routed = normalizeWorkspaceRouting(owner); + return routed.workspace_kind === 'remote' + || Boolean(routed.remote_connection_id) + || Boolean(routed.remote_ssh_host); +} diff --git a/src/mobile-web/tests/workspace-identity.test.mjs b/src/mobile-web/tests/workspace-identity.test.mjs index bb539c0993..a182ff5977 100644 --- a/src/mobile-web/tests/workspace-identity.test.mjs +++ b/src/mobile-web/tests/workspace-identity.test.mjs @@ -10,7 +10,8 @@ const code = ts.transpileModule(source, { const { mergeWorkspaceSessions, sessionMatchesWorkspace, workspaceIdentityKey, resolveLegacyWorkspaceReference, sameWorkspace, - isClawAgent, resolveChatHeaderContext, sessionWorkspaceContext, workspaceContext, + isClawAgent, isRemoteSessionWorkspace, resolveChatHeaderContext, selectedSessionWorkspaceContext, + sessionWorkspaceContext, workspaceContext, } = await import( `data:text/javascript;base64,${Buffer.from(code).toString('base64')}` ); @@ -534,3 +535,63 @@ test('session workspace context keeps host identity and takes only display facts assert.equal(isClawAgent('Claw'), true); assert.equal(isClawAgent('Cowork'), false); }); + +test('localhost markers from older hosts on either side keep the branch for the selected workspace', () => { + const legacyCurrent = { ...home, workspace_id: undefined }; + const legacyMarker = { workspace_kind: 'normal', remote_ssh_host: 'localhost' }; + // A new session in the selected workspace: the created reply carries the marker. + assert.deepEqual( + header({ currentWorkspace: legacyCurrent, session: { path: home.path, ...legacyMarker } }), + { workspaceName: 'home', gitBranch: 'master' }, + ); + assert.deepEqual( + header({ + currentWorkspace: { ...legacyCurrent, remote_ssh_host: 'localhost' }, + session: { path: home.path, ...legacyMarker }, + }), + { workspaceName: 'home', gitBranch: 'master' }, + ); +}); + +test('the rollback gate follows the open session, not the selected workspace', () => { + const ssh = { ...a, name: 'herdr', workspace_kind: 'remote' }; + const selectedSsh = { + has_workspace: true, path: a.path, workspace_kind: 'remote', + remote_connection_id: 'ssh-a', remote_ssh_host: 'host-a', + }; + // Local project selected while the open session is SSH. + assert.equal(isRemoteSessionWorkspace('Standard', ssh, home), true); + assert.equal(isRemoteSessionWorkspace('Standard', { path: a.path, remote_ssh_host: 'host-a' }, home), true); + // SSH project selected while a Claw or local session is open. + assert.equal(isRemoteSessionWorkspace('Claw', undefined, selectedSsh), false); + assert.equal(isRemoteSessionWorkspace('Claw', { path: claw.path }, selectedSsh), false); + assert.equal(isRemoteSessionWorkspace('Cowork', { path: claw.path, workspace_kind: 'assistant' }, selectedSsh), false); + assert.equal(isRemoteSessionWorkspace('Standard', { path: home.path, workspace_kind: 'normal' }, selectedSsh), false); + // Without session facts the selection still gates, as it did before. + assert.equal(isRemoteSessionWorkspace('Standard', undefined, selectedSsh), true); + assert.equal(isRemoteSessionWorkspace('Standard', undefined, home), false); + assert.equal(isRemoteSessionWorkspace('Standard', undefined, null), false); + // A normal record's localhost marker is not SSH; an unknown kind keeps its selector. + assert.equal(isRemoteSessionWorkspace('Standard', { path: home.path, workspace_kind: 'normal', remote_ssh_host: 'localhost' }, null), false); + assert.equal(isRemoteSessionWorkspace('Standard', { path: home.path, remote_ssh_host: 'localhost' }, null), true); +}); + +test('a selection that no longer owns the created session lends it no name or kind', () => { + const selection = workspaceContext({ ...claw, workspace_kind: 'assistant' }); + const facts = (workspace_id, workspace_path, remote = {}) => ({ + workspace_id, workspace_path, workspace_identity: remote, + }); + assert.equal(selectedSessionWorkspaceContext(facts('ws-claw', claw.path), selection).name, 'Nova'); + const moved = selectedSessionWorkspaceContext(facts('ws-api', '/Users/me/api'), selection); + assert.equal(moved.name, undefined); + assert.equal(moved.workspace_kind, undefined); + assert.equal(moved.workspace_id, 'ws-api'); + // ID-less SSH facts on the same path are a different workspace from a local selection. + const local = workspaceContext({ path: a.path, name: 'local', workspace_kind: 'normal' }); + const onHost = selectedSessionWorkspaceContext( + facts(undefined, a.path, { remote_connection_id: 'ssh-a', remote_ssh_host: 'host-a' }), + local, + ); + assert.equal(onHost.name, undefined); + assert.equal(onHost.remote_ssh_host, 'host-a'); +}); From 512c76d7f2d217f4b1e2012fe14db4fb07cca616 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:23:33 +0800 Subject: [PATCH 3/5] fix(mobile-web): keep rollback gated for unknown session routing A path-only session context, such as an old cached row, read as local and could offer rollback on an SSH workspace. Treat it as unknown: it stays gated if the selected workspace or a known workspace with the same ID or root is remote. Only Claw/assistant or explicit routing facts can override a remote selection. --- src/mobile-web/src/pages/ChatPage.tsx | 3 +- src/mobile-web/src/pages/SessionListPage.tsx | 3 ++ src/mobile-web/src/services/store.ts | 10 ++++++ .../src/services/workspaceIdentity.ts | 33 ++++++++++++++----- .../tests/workspace-identity.test.mjs | 28 ++++++++++++++++ 5 files changed, 68 insertions(+), 9 deletions(-) diff --git a/src/mobile-web/src/pages/ChatPage.tsx b/src/mobile-web/src/pages/ChatPage.tsx index 31d2a70293..1ac64e5c78 100644 --- a/src/mobile-web/src/pages/ChatPage.tsx +++ b/src/mobile-web/src/pages/ChatPage.tsx @@ -97,6 +97,7 @@ const ChatPage: React.FC = ({ setError, currentWorkspace, currentAssistant, + knownWorkspaces, sessions, authenticatedUserId, controlTarget, @@ -1173,7 +1174,7 @@ const ChatPage: React.FC = ({ assistantLabel: t('shared.agents.Claw'), }); const displayName = liveTitle || sessionName || t('chat.session'); - const isRemoteWorkspace = isRemoteSessionWorkspace(sessionAgentType, sessionContext, currentWorkspace); + const isRemoteWorkspace = isRemoteSessionWorkspace(sessionAgentType, sessionContext, currentWorkspace, knownWorkspaces); return (
diff --git a/src/mobile-web/src/pages/SessionListPage.tsx b/src/mobile-web/src/pages/SessionListPage.tsx index c0b0cde827..9ffddd770b 100644 --- a/src/mobile-web/src/pages/SessionListPage.tsx +++ b/src/mobile-web/src/pages/SessionListPage.tsx @@ -333,6 +333,9 @@ const SessionListPage: React.FC = ({ const [assistantList, setAssistantList] = useState([]); const [showAssistantPicker, setShowAssistantPicker] = useState(false); const [workspaceList, setWorkspaceList] = useState([]); + useEffect(() => { + useMobileStore.getState().setKnownWorkspaces(workspaceList); + }, [workspaceList]); const [showWorkspacePicker, setShowWorkspacePicker] = useState(false); const [workspaceCatalogSource, setWorkspaceCatalogSource] = useState<'opened' | 'recent' | null>(null); diff --git a/src/mobile-web/src/services/store.ts b/src/mobile-web/src/services/store.ts index c3b55d459b..6023fdf46a 100644 --- a/src/mobile-web/src/services/store.ts +++ b/src/mobile-web/src/services/store.ts @@ -5,6 +5,7 @@ import type { WorkspaceInfo, ActiveTurnSnapshot, AssistantEntry, + RecentWorkspaceEntry, } from './RemoteSessionManager'; export type ConnectionStatus = 'idle' | 'pairing' | 'paired' | 'error'; @@ -22,6 +23,10 @@ interface MobileStore { currentAssistant: AssistantEntry | null; setCurrentAssistant: (a: AssistantEntry | null) => void; + /** The host's workspace catalog, loaded by the session list. Used for conservative routing checks. */ + knownWorkspaces: RecentWorkspaceEntry[]; + setKnownWorkspaces: (workspaces: RecentWorkspaceEntry[]) => void; + /** One-shot hint after pairing so SessionList matches desktop assistant vs project workspace. */ pairedDisplayMode: 'pro' | 'assistant' | null; setPairedDisplayMode: (m: 'pro' | 'assistant' | null) => void; @@ -81,6 +86,9 @@ export const useMobileStore = create((set, get) => ({ currentAssistant: null, setCurrentAssistant: (currentAssistant) => set({ currentAssistant }), + knownWorkspaces: [], + setKnownWorkspaces: (knownWorkspaces) => set({ knownWorkspaces }), + pairedDisplayMode: null, setPairedDisplayMode: (pairedDisplayMode) => set({ pairedDisplayMode }), @@ -166,6 +174,7 @@ export const useMobileStore = create((set, get) => ({ connectionStatus: 'idle', currentWorkspace: null, currentAssistant: null, + knownWorkspaces: [], pairedDisplayMode: null, authenticatedUserId: null, authenticatedUserLabel: null, @@ -182,6 +191,7 @@ export const useMobileStore = create((set, get) => ({ set({ currentWorkspace: null, currentAssistant: null, + knownWorkspaces: [], pairedDisplayMode: null, sessions: [], activeSessionId: null, diff --git a/src/mobile-web/src/services/workspaceIdentity.ts b/src/mobile-web/src/services/workspaceIdentity.ts index 56fc8de4f2..4f8cd01583 100644 --- a/src/mobile-web/src/services/workspaceIdentity.ts +++ b/src/mobile-web/src/services/workspaceIdentity.ts @@ -349,20 +349,37 @@ export function resolveChatHeaderContext({ }; } +function hasRemoteRouting(workspace: { + workspace_kind?: string; remote_connection_id?: string; remote_ssh_host?: string; +}): boolean { + const routed = normalizeWorkspaceRouting(workspace); + return routed.workspace_kind === 'remote' + || Boolean(routed.remote_connection_id) + || Boolean(routed.remote_ssh_host); +} + /** - * Whether the open session runs on an SSH workspace, which keeps rollback off. - * The selected workspace only decides when the session has no workspace facts. + * Whether the open session may run on an SSH workspace, which keeps rollback off. + * Only Claw/assistant or explicit routing facts on the session can decide alone. + * A path-only context (for example an old cached row) is unknown, so it stays + * remote if the selected workspace is remote or a known workspace with the same + * ID or root is remote. */ export function isRemoteSessionWorkspace( agentType: string, session: SessionWorkspaceContext | undefined, currentWorkspace: WorkspaceInfo | null | undefined, + knownWorkspaces: readonly RecentWorkspaceEntry[] = [], ): boolean { if (isClawAgent(agentType) || session?.workspace_kind === 'assistant') return false; - const owner = session ?? currentWorkspace; - if (!owner) return false; - const routed = normalizeWorkspaceRouting(owner); - return routed.workspace_kind === 'remote' - || Boolean(routed.remote_connection_id) - || Boolean(routed.remote_ssh_host); + if (session && (session.workspace_kind || session.remote_connection_id || session.remote_ssh_host)) { + return hasRemoteRouting(session); + } + if (currentWorkspace && hasRemoteRouting(currentWorkspace)) return true; + if (!session) return false; + const root = normalizedLegacyRoot(session.path); + return knownWorkspaces.some((workspace) => hasRemoteRouting(workspace) && ( + (Boolean(session.workspace_id) && workspace.workspace_id === session.workspace_id) + || (Boolean(root) && normalizedLegacyRoot(workspace.path) === root) + )); } diff --git a/src/mobile-web/tests/workspace-identity.test.mjs b/src/mobile-web/tests/workspace-identity.test.mjs index a182ff5977..48ee280759 100644 --- a/src/mobile-web/tests/workspace-identity.test.mjs +++ b/src/mobile-web/tests/workspace-identity.test.mjs @@ -595,3 +595,31 @@ test('a selection that no longer owns the created session lends it no name or ki assert.equal(onHost.name, undefined); assert.equal(onHost.remote_ssh_host, 'host-a'); }); + +test('a path-only session context cannot open the rollback gate over a possibly remote workspace', () => { + const pathOnly = { path: a.path }; + const selectedSsh = { + has_workspace: true, path: '/elsewhere', workspace_kind: 'remote', + remote_connection_id: 'ssh-a', remote_ssh_host: 'host-a', + }; + const sshRow = { path: `${a.path}/`, name: 'herdr', last_opened: '', workspace_kind: 'remote', remote_ssh_host: 'host-a' }; + const localRow = { path: a.path, name: 'herdr', last_opened: '', workspace_kind: 'normal' }; + // Unknown routing stays remote under a remote selection. + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, selectedSsh), true); + assert.equal(isRemoteSessionWorkspace('Standard', { ...pathOnly, workspace_id: 'ws', name: 'herdr' }, selectedSsh), true); + // Unknown routing stays remote if a known workspace with that root is remote, even beside a local one. + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, home, [sshRow]), true); + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, home, [localRow, sshRow]), true); + assert.equal( + isRemoteSessionWorkspace('Standard', { workspace_id: 'ws-ssh' }, home, [{ ...sshRow, workspace_id: 'ws-ssh', path: '/other' }]), + true, + ); + // Nothing known says remote. + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, home, [localRow]), false); + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, home, [{ ...sshRow, path: '/other' }]), false); + assert.equal(isRemoteSessionWorkspace('Standard', pathOnly, null), false); + // Explicit local facts and Claw/assistant may still override a remote selection. + assert.equal(isRemoteSessionWorkspace('Standard', { ...pathOnly, workspace_kind: 'normal' }, selectedSsh, [sshRow]), false); + assert.equal(isRemoteSessionWorkspace('Claw', pathOnly, selectedSsh, [sshRow]), false); + assert.equal(isRemoteSessionWorkspace('Standard', { ...pathOnly, workspace_kind: 'assistant' }, selectedSsh, [sshRow]), false); +}); From 353dd1a2ba0d2e9757dcfdd2a41da54db8b26700 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:41:20 +0800 Subject: [PATCH 4/5] test(mobile-web): use a neutral assistant path in header fixture --- src/mobile-web/tests/workspace-identity.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mobile-web/tests/workspace-identity.test.mjs b/src/mobile-web/tests/workspace-identity.test.mjs index 48ee280759..0a4ee0ac4b 100644 --- a/src/mobile-web/tests/workspace-identity.test.mjs +++ b/src/mobile-web/tests/workspace-identity.test.mjs @@ -439,7 +439,7 @@ const home = { workspace_id: 'ws-home', has_workspace: true, path: '/Users/me/home', project_name: 'home', git_branch: 'master', workspace_kind: 'normal', }; -const claw = { workspace_id: 'ws-claw', path: '/Users/me/.bitfun/personal_assistant/workspace', name: 'Nova' }; +const claw = { workspace_id: 'ws-claw', path: '/Users/me/assistant/workspace', name: 'Nova' }; const header = (overrides) => resolveChatHeaderContext({ agentType: 'Standard', currentWorkspace: home, From a9035f2e76662fa1d57a23d889f8f4f145bbcc83 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 11:22:56 +0800 Subject: [PATCH 5/5] test(web-ui): expect the session workspace in mobile session selection --- .../SessionListTargetInitialization.test.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/SessionListTargetInitialization.test.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/SessionListTargetInitialization.test.tsx index 23298ce4e8..35b927ed7d 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/SessionListTargetInitialization.test.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/SessionListTargetInitialization.test.tsx @@ -172,6 +172,11 @@ describe('SessionList target initialization ownership', () => { 'sessions.remoteClawSession', true, 'claw', + expect.objectContaining({ + workspace_kind: 'assistant', + workspace_id: 'assistant-b', + path: '/assistant-b', + }), ); }); it('workspace creation offers all modes while footer tools preserve workspace identity', async () => {