From 0bff9398b9766b9d8718b9f17d6476f06c00935e Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 14:15:05 +0800 Subject: [PATCH 1/2] fix(web-ui): preserve internal MiniApp permission scope --- src/web-ui/AGENTS.md | 10 ++ .../src/flow_chat/components/ChatInput.tsx | 22 ++--- .../utils/sessionPermissionMode.test.ts | 91 ++++++++++++++++++- .../flow_chat/utils/sessionPermissionMode.ts | 20 ++++ 4 files changed, 130 insertions(+), 13 deletions(-) diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index 154de38124..8d7febc429 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -285,6 +285,16 @@ pnpm --dir src/web-ui run test:run src/flow_chat/hooks/useChatInputModeSync.test These state/hook fixtures cover delayed session loading and selected peer-surface replacement; they do not establish native rendering or live remote behavior. +For composer permission reads and updates, including internal MiniApp sessions: + +```bash +pnpm --dir src/web-ui run test:run src/flow_chat/utils/sessionPermissionMode.test.ts src/flow_chat/utils/modelSelectionTarget.test.ts src/app/scenes/miniapps/hooks/useMiniAppBridge.test.tsx +``` + +These request/bridge fixtures cover restored topics, legacy path-only scopes and +simulated remote workspace identity. They do not establish native rendering or +live SSH, Remote Control, Peer Device or Detached Dispatch behavior. + For cross-device undo/redo/rollback history invalidation and settled-Turn fences, run `pnpm --dir src/web-ui run test:run src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts`. Missing fence identities (including legacy payloads) must reload authoritative diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index a6c81abc39..9c11ad08aa 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -259,6 +259,7 @@ import { hasSessionStarted, isSessionBindingLocked } from '../utils/sessionLifec import { canTreatMissingPermissionModeAsDefault, isSessionNotFoundError, + sessionPermissionModeScope, } from '../utils/sessionPermissionMode'; import { prepareSessionDraftForCommand } from '../services/sessionDraftService'; import { useSessionWorkspaceSelection } from '../hooks/useSessionWorkspaceSelection'; @@ -2650,10 +2651,7 @@ export const ChatInput: React.FC = ({ }, () => agentAPI.getSessionPermissionMode({ sessionId: permissionSessionId, turnId: activePermissionTurnId ?? undefined, - workspaceId: sessionOwningId, - workspacePath: sessionOwningPath, - remoteConnectionId: effectiveTargetSession?.remoteConnectionId, - remoteSshHost: effectiveTargetSession?.remoteSshHost, + ...sessionPermissionModeScope(effectiveTargetSession), })); if (permissionModeRequestGenerationRef.current !== generation) return; setSessionPermissionMode(response.mode ?? null); @@ -2716,6 +2714,8 @@ export const ChatInput: React.FC = ({ effectiveTargetSession?.persistedTurnCount, effectiveTargetSession?.remoteConnectionId, effectiveTargetSession?.remoteSshHost, + effectiveTargetSession?.sessionKind, + effectiveTargetSession?.agentBackedTransient, effectiveTargetSession?.parentSessionId, effectiveTargetSession?.draft, effectiveTargetSession?.externalHistory, @@ -2774,10 +2774,7 @@ export const ChatInput: React.FC = ({ sessionId: targetSessionId, mode: nextMode, turnId: targetTurnId ?? undefined, - workspaceId: sessionOwningId, - workspacePath: sessionOwningPath, - remoteConnectionId: effectiveTargetSession?.remoteConnectionId, - remoteSshHost: effectiveTargetSession?.remoteSshHost, + ...sessionPermissionModeScope(effectiveTargetSession), }); if ( permissionModeRequestGenerationRef.current === generation @@ -2813,6 +2810,8 @@ export const ChatInput: React.FC = ({ sessionOwningPath, effectiveTargetSession?.remoteConnectionId, effectiveTargetSession?.remoteSshHost, + effectiveTargetSession?.sessionKind, + effectiveTargetSession?.agentBackedTransient, activeTurnPermissionMode, sessionPermissionMode, t, @@ -2897,10 +2896,7 @@ export const ChatInput: React.FC = ({ sessionId: targetSessionId, turnId: targetTurnId, mode: nextTemporaryMode, - workspaceId: sessionOwningId, - workspacePath: sessionOwningPath, - remoteConnectionId: effectiveTargetSession?.remoteConnectionId, - remoteSshHost: effectiveTargetSession?.remoteSshHost, + ...sessionPermissionModeScope(effectiveTargetSession), }); if ( permissionModeRequestGenerationRef.current === generation @@ -2935,6 +2931,8 @@ export const ChatInput: React.FC = ({ confirmFullAccessIfNeeded, effectiveTargetSession?.remoteConnectionId, effectiveTargetSession?.remoteSshHost, + effectiveTargetSession?.sessionKind, + effectiveTargetSession?.agentBackedTransient, effectiveTargetSessionId, isAcpTargetSession, sessionOwningId, diff --git a/src/web-ui/src/flow_chat/utils/sessionPermissionMode.test.ts b/src/web-ui/src/flow_chat/utils/sessionPermissionMode.test.ts index 379a918489..41f9af6ae0 100644 --- a/src/web-ui/src/flow_chat/utils/sessionPermissionMode.test.ts +++ b/src/web-ui/src/flow_chat/utils/sessionPermissionMode.test.ts @@ -1,10 +1,16 @@ -import { describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { agentAPI, type SessionPermissionModeRequest } from '@/infrastructure/api/service-api/AgentAPI'; import type { Session } from '../types/flow-chat'; import { canTreatMissingPermissionModeAsDefault, isSessionNotFoundError, + sessionPermissionModeScope, } from './sessionPermissionMode'; +const invoke = vi.hoisted(() => vi.fn()); +vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { invoke } })); +vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ workspaceManager: {} })); + const emptyNewSession = { dialogTurns: [], historyState: 'new' as const, @@ -39,3 +45,86 @@ describe('session permission mode lifecycle', () => { expect(isSessionNotFoundError(new Error('Permission denied'))).toBe(false); }); }); + +describe('composer permission request scope', () => { + // Shape registered by agent.ensureSession, including a restored topic whose + // history is already present when the floating conversation opens. + const miniAppSession = { + sessionId: 'miniapp-topic', + sessionKind: 'miniapp', + isTransient: true, + agentBackedTransient: true, + workspaceId: 'appdata-workspace', + workspacePath: '/host/miniapps/market-lens/research/topic', + config: {}, + historyState: 'ready', + dialogTurns: [{ id: 'previous-turn' }], + persistedTurnCount: 1, + } as Session; + + beforeEach(() => { invoke.mockReset(); }); + + it.each([ + ['getSessionPermissionMode', 'get_session_permission_mode'], + ['updateSessionPermissionMode', 'update_session_permission_mode'], + ['updateActiveTurnPermissionMode', 'update_active_turn_permission_mode'], + ] as const)('accesses a restored MiniApp internal session through %s', async (method, command) => { + const result = { mode: 'ask', turnMode: 'auto_approve', activeTurnId: 'active-turn' }; + invoke.mockImplementation(async (_command: string, { request }: { request: SessionPermissionModeRequest }) => { + // The host's selector rejects hidden sessions unless explicitly included, + // even when their history and live runtime have already been loaded. + if (!request.includeInternal) throw new Error(`Session not found: ${request.sessionId}`); + return result; + }); + const request = { + sessionId: miniAppSession.sessionId, + turnId: 'active-turn', + ...sessionPermissionModeScope(miniAppSession), + ...(method === 'getSessionPermissionMode' ? {} : { mode: 'ask' as const }), + }; + await expect(agentAPI[method]({ ...request, includeInternal: undefined })).rejects.toThrow('Session not found'); + await expect(agentAPI[method](request)).resolves.toEqual(result); + expect(invoke).toHaveBeenLastCalledWith(command, { request: { + sessionId: 'miniapp-topic', turnId: 'active-turn', + workspaceId: 'appdata-workspace', workspacePath: miniAppSession.workspacePath, + includeInternal: true, remoteConnectionId: undefined, remoteSshHost: undefined, + ...(method === 'getSessionPermissionMode' ? {} : { mode: 'ask' }), + } }); + expect(canTreatMissingPermissionModeAsDefault(miniAppSession)).toBe(false); + }); + + it('keeps legacy path-only MiniApp topics addressable without inventing a workspace ID', () => { + const legacy = { ...miniAppSession, workspaceId: undefined }; + const wireScope = JSON.parse(JSON.stringify(sessionPermissionModeScope(legacy))); + expect(wireScope).toEqual({ workspacePath: miniAppSession.workspacePath, includeInternal: true }); + }); + + it('preserves the owning project and POSIX scope for a remote subagent in a worktree', () => { + const remote = { ...miniAppSession, sessionKind: 'subagent', agentBackedTransient: false, + workspaceId: 'remote-worktree', workspacePath: '/srv/project/.worktrees/task', + projectWorkspaceId: 'remote-project', projectWorkspacePath: '/srv/project', + remoteConnectionId: 'ssh-connection', remoteSshHost: 'target-host', + config: { executionTarget: { kind: 'worktree', worktreeId: 'task' } }, + } as Session; + expect(sessionPermissionModeScope(remote)).toEqual({ + workspaceId: 'remote-project', workspacePath: '/srv/project', + remoteConnectionId: 'ssh-connection', remoteSshHost: 'target-host', includeInternal: true, + }); + }); + + it('does not opt ordinary or UI-only transient sessions into internal visibility', () => { + const ordinary = { ...miniAppSession, sessionKind: 'normal', agentBackedTransient: false } as Session; + expect(sessionPermissionModeScope(ordinary).includeInternal).toBe(false); + expect(sessionPermissionModeScope(undefined)).toEqual({ + workspaceId: undefined, workspacePath: undefined, remoteConnectionId: undefined, + remoteSshHost: undefined, includeInternal: false, + }); + }); + + it('propagates a real host failure for a MiniApp instead of reporting a default-mode success', async () => { + invoke.mockRejectedValue(new Error('Host offline')); + await expect(agentAPI.getSessionPermissionMode({ sessionId: miniAppSession.sessionId, + ...sessionPermissionModeScope(miniAppSession), + })).rejects.toThrow('Host offline'); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/sessionPermissionMode.ts b/src/web-ui/src/flow_chat/utils/sessionPermissionMode.ts index ac10329da4..21470a2646 100644 --- a/src/web-ui/src/flow_chat/utils/sessionPermissionMode.ts +++ b/src/web-ui/src/flow_chat/utils/sessionPermissionMode.ts @@ -1,4 +1,24 @@ +import type { SessionPermissionModeRequest } from '@/infrastructure/api/service-api/AgentAPI'; import type { Session } from '../types/flow-chat'; +import { shouldIncludeInternalModelSession } from './modelSelectionTarget'; +import { sessionOwningWorkspaceId } from './sessionOrdering'; +import { sessionProjectWorkspacePath } from './sessionWorkspace'; + +/** Reads and both permission mutations must address the same runtime session. */ +export function sessionPermissionModeScope(session: Session | undefined): Pick< + SessionPermissionModeRequest, + 'workspaceId' | 'workspacePath' | 'remoteConnectionId' | 'remoteSshHost' | 'includeInternal' +> { + return { + workspaceId: session && sessionOwningWorkspaceId(session), + workspacePath: session && sessionProjectWorkspacePath(session), + remoteConnectionId: session?.remoteConnectionId, + remoteSshHost: session?.remoteSshHost, + // MiniApp and other agent-backed transient views use hidden host sessions, + // just like the model selector. Their existence is not a missing-record gap. + includeInternal: shouldIncludeInternalModelSession(session), + }; +} type PermissionModeSessionState = Pick< Session, From 52361cd21dd042b1bcbd35ef9aa3bf83ae5ca591 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 14:23:08 +0800 Subject: [PATCH 2/2] fix(web-ui): preserve internal scope across MiniApp session recovery --- src/web-ui/AGENTS.md | 8 +++-- .../src/flow_chat/components/ChatInput.tsx | 36 ++++--------------- .../flow_chat/components/ModelSelector.tsx | 3 +- .../ModelSelectorProviderLevels.test.tsx | 18 ++++++++++ .../hooks/useSessionModeSelection.test.tsx | 13 +++++++ .../hooks/useSessionModeSelection.ts | 8 ++++- .../EventHandlerModule.test.ts | 7 ++-- .../flow-chat-manager/EventHandlerModule.ts | 5 +-- .../flow-chat-manager/SessionModule.test.ts | 5 +-- .../flow-chat-manager/SessionModule.ts | 5 +-- .../inheritReviewPermissionMode.test.ts | 20 +++++++++++ .../services/inheritReviewPermissionMode.ts | 8 ++--- .../src/flow_chat/store/FlowChatStore.test.ts | 24 +++++++++---- .../src/flow_chat/store/FlowChatStore.ts | 17 +++++---- .../src/flow_chat/utils/internalSession.ts | 10 ++++++ .../flow_chat/utils/modelSelectionTarget.ts | 7 +--- .../flow_chat/utils/sessionPermissionMode.ts | 4 +-- .../api/service-api/AgentAPI.ts | 2 +- 18 files changed, 130 insertions(+), 70 deletions(-) create mode 100644 src/web-ui/src/flow_chat/utils/internalSession.ts diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index 8d7febc429..71b6dc0634 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -285,14 +285,16 @@ pnpm --dir src/web-ui run test:run src/flow_chat/hooks/useChatInputModeSync.test These state/hook fixtures cover delayed session loading and selected peer-surface replacement; they do not establish native rendering or live remote behavior. -For composer permission reads and updates, including internal MiniApp sessions: +For internal MiniApp session visibility across composer permissions, selectors, +history paging/settlement, and runtime restoration: ```bash pnpm --dir src/web-ui run test:run src/flow_chat/utils/sessionPermissionMode.test.ts src/flow_chat/utils/modelSelectionTarget.test.ts src/app/scenes/miniapps/hooks/useMiniAppBridge.test.tsx +pnpm --dir src/web-ui run test:run src/flow_chat/store/FlowChatStore.test.ts src/flow_chat/services/flow-chat-manager/SessionModule.test.ts src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts src/flow_chat/services/inheritReviewPermissionMode.test.ts src/flow_chat/components/ModelSelectorProviderLevels.test.tsx src/flow_chat/hooks/useSessionModeSelection.test.tsx ``` -These request/bridge fixtures cover restored topics, legacy path-only scopes and -simulated remote workspace identity. They do not establish native rendering or +These request/bridge/store fixtures cover restored topics, legacy path-only scopes, +history repair, and simulated remote workspace/Peer identity. They do not establish native rendering or live SSH, Remote Control, Peer Device or Detached Dispatch behavior. For cross-device undo/redo/rollback history invalidation and settled-Turn fences, diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index 9c11ad08aa..20b36758ae 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -255,6 +255,7 @@ import { import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag'; import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; import { isBtwParentBackedSession, isBtwSessionDraft } from '../utils/modelSelectionTarget'; +import { shouldIncludeInternalSession } from '../utils/internalSession'; import { hasSessionStarted, isSessionBindingLocked } from '../utils/sessionLifecycle'; import { canTreatMissingPermissionModeAsDefault, @@ -1240,9 +1241,6 @@ export const ChatInput: React.FC = ({ const sessionOwningId = effectiveTargetSession ? sessionOwningWorkspaceId(effectiveTargetSession) : undefined; - const sessionOwningPath = effectiveTargetSession - ? sessionProjectWorkspacePath(effectiveTargetSession) - : undefined; // Workspace record the input addresses, or the context workspace while no // session exists yet. An empty string means the targeted session has no // record; it must not fall back to the context. @@ -2705,21 +2703,7 @@ export const ChatInput: React.FC = ({ }, [ activePermissionTurnId, effectiveTargetSessionId, - sessionOwningId, - sessionOwningPath, - effectiveTargetSession?.workspacePath, - effectiveTargetSession?.dialogTurns, - effectiveTargetSession?.historyState, - effectiveTargetSession?.isHistorical, - effectiveTargetSession?.persistedTurnCount, - effectiveTargetSession?.remoteConnectionId, - effectiveTargetSession?.remoteSshHost, - effectiveTargetSession?.sessionKind, - effectiveTargetSession?.agentBackedTransient, - effectiveTargetSession?.parentSessionId, - effectiveTargetSession?.draft, - effectiveTargetSession?.externalHistory, - effectiveTargetSession?.externalContinuationPermissionMode, + effectiveTargetSession, isBtwDraftTarget, isBtwParentBackedTarget, isAcpTargetSession, @@ -2806,12 +2790,7 @@ export const ChatInput: React.FC = ({ } }, [ effectiveTargetSessionId, - sessionOwningId, - sessionOwningPath, - effectiveTargetSession?.remoteConnectionId, - effectiveTargetSession?.remoteSshHost, - effectiveTargetSession?.sessionKind, - effectiveTargetSession?.agentBackedTransient, + effectiveTargetSession, activeTurnPermissionMode, sessionPermissionMode, t, @@ -2929,14 +2908,9 @@ export const ChatInput: React.FC = ({ activeTurnPermissionMode, armedTurnPermissionMode, confirmFullAccessIfNeeded, - effectiveTargetSession?.remoteConnectionId, - effectiveTargetSession?.remoteSshHost, - effectiveTargetSession?.sessionKind, - effectiveTargetSession?.agentBackedTransient, + effectiveTargetSession, effectiveTargetSessionId, isAcpTargetSession, - sessionOwningId, - sessionOwningPath, permissionModeSaving, t, ]); @@ -4817,7 +4791,9 @@ export const ChatInput: React.FC = ({ ? { sessionId: effectiveTargetSessionId, draft: !!effectiveTargetSession.draft, + workspaceId: sessionOwningWorkspaceId(effectiveTargetSession), workspacePath: sessionProjectWorkspacePath(effectiveTargetSession), + includeInternal: shouldIncludeInternalSession(effectiveTargetSession), remoteConnectionId: effectiveTargetSession.remoteConnectionId || effectiveTargetSession.config.remoteConnectionId, diff --git a/src/web-ui/src/flow_chat/components/ModelSelector.tsx b/src/web-ui/src/flow_chat/components/ModelSelector.tsx index 4014381bb9..25376af504 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelector.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelector.tsx @@ -1329,7 +1329,8 @@ export const ModelSelector: React.FC = ({ identity: routingIdentity, epoch: deviceSurfaceScope.epoch, request: { sessionId, workspaceId: activeSession?.workspaceId || activeSession?.config.workspaceId, workspacePath: activeSession ? sessionProjectWorkspacePath(activeSession) : undefined, - remoteConnectionId: activeSession?.remoteConnectionId, remoteSshHost: activeSession?.remoteSshHost }, + remoteConnectionId: activeSession?.remoteConnectionId, remoteSshHost: activeSession?.remoteSshHost, + includeInternal: shouldIncludeInternalModelSession(activeSession) }, allowed: canConfigureNativeDefaults, open: dropdownOpen, draft: sessionDraft ? { mode: sessionDraft.modelRouting, onChange: mode => { if (!sessionId) return; diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx index 0caf38172a..58075e3e95 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx @@ -1406,6 +1406,24 @@ describe('ModelSelector provider levels', () => { expect(document.body.querySelector('[data-testid="model-selection-scope"]')).toBeNull(); }); + it('reads the host routing restriction for a MiniApp instead of losing its status to a visibility error', async () => { + flowChatStoreMocks.sessions.set('miniapp-session', { + sessionKind: 'miniapp', agentBackedTransient: true, isTransient: true, + config: { modelName: 'umbra-main' }, + }); + vi.mocked(agentAPI.getModelRoutingStatus).mockImplementation(async request => { + if (!request?.includeInternal) throw new Error('Session not found'); + return { ...routingHost, ready: false, issue: 'Smart mode is unavailable for subagents' }; + }); + await renderSelector(CATALOG_MODELS, 'umbra-main', 'miniapp-session'); + await openModeMenu(); + expect(agentAPI.getModelRoutingStatus).toHaveBeenCalledWith(expect.objectContaining({ + sessionId: 'miniapp-session', includeInternal: true, + })); + expect(modeAction('smart')?.dataset.tooltip).toBe('modelSelector.modes.smart · modelSelector.routing.configurationIssue'); + expect(agentAPI.updateSessionModel).not.toHaveBeenCalled(); + }); + it('keeps routing and billing configuration out of the all-models defaults', async () => { await act(async () => root.render()); diff --git a/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx b/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx index 84ed93f33b..a8ff615e7b 100644 --- a/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx +++ b/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx @@ -22,10 +22,12 @@ vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ function Probe({ sessionId = 'session-1', draft = false, + internal = false, publish = mocks.publish, }: { sessionId?: string; draft?: boolean; + internal?: boolean; publish?: (modeId: string) => void; }) { const selection = useSessionModeSelection( @@ -33,6 +35,7 @@ function Probe({ sessionId, draft, workspacePath: 'D:/workspace/project', + ...(internal ? { workspaceId: 'miniapp-workspace', includeInternal: true } : {}), }, publish, mocks.reportFailure, @@ -69,6 +72,16 @@ describe('useSessionModeSelection', () => { vi.clearAllMocks(); }); + it('preserves the internal MiniApp workspace scope when changing its mode', async () => { + await act(async () => root.render()); + await act(async () => container.querySelector('button')!.click()); + expect(mocks.updateSessionMode).toHaveBeenCalledWith(expect.objectContaining({ + sessionId: 'session-1', workspaceId: 'miniapp-workspace', includeInternal: true, modeId: 'Standard', + })); + expect(mocks.publish).toHaveBeenCalledWith('Standard'); + expect(mocks.reportFailure).not.toHaveBeenCalled(); + }); + it('keeps an explicit draft selection local until a host session exists', async () => { await act(async () => root.render()); const select = Array.from(container.querySelectorAll('button'))[1]; diff --git a/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts b/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts index 71fb73debd..a02f0ee898 100644 --- a/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts +++ b/src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts @@ -5,9 +5,11 @@ import { agentAPI } from '@/infrastructure/api/service-api/AgentAPI'; export interface SessionModeSelectionTarget { draft?: boolean; sessionId: string; + workspaceId?: string; workspacePath?: string; remoteConnectionId?: string; remoteSshHost?: string; + includeInternal?: boolean; } interface ModeSelectionIntent { @@ -59,9 +61,11 @@ export function useSessionModeSelection( const sessionId = target?.sessionId; const draft = target?.draft; + const workspaceId = target?.workspaceId; const workspacePath = target?.workspacePath; const remoteConnectionId = target?.remoteConnectionId; const remoteSshHost = target?.remoteSshHost; + const includeInternal = target?.includeInternal; const requestModeChange = useCallback((modeId: string) => { if (!sessionId || draft) { @@ -73,9 +77,11 @@ export function useSessionModeSelection( request: { sessionId, modeId, + workspaceId, workspacePath, remoteConnectionId, remoteSshHost, + includeInternal, }, publish: publishRef.current, reportFailure: failureRef.current, @@ -118,7 +124,7 @@ export function useSessionModeSelection( } }; void run(intent); - }, [draft, notifyQueueChanged, remoteConnectionId, remoteSshHost, sessionId, workspacePath]); + }, [draft, notifyQueueChanged, remoteConnectionId, remoteSshHost, sessionId, workspaceId, workspacePath, includeInternal]); return { isModeChangePending: Boolean(sessionId && sessionQueuesRef.current.has(sessionId)), diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts index 58f169dff0..846b0adda1 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts @@ -1947,15 +1947,18 @@ describe('handleSessionHistoryChanged', () => { expect(context.pendingHistoryFenceSessions.has('session-1')).toBe(false); }); - it('reloads an out-of-lifecycle edit even when the obsolete local tail is still finishing', () => { + it.each(['normal', 'miniapp', 'subagent'] as const)('reloads an out-of-lifecycle %s edit even when the obsolete local tail is still finishing', sessionKind => { createSessionWithTurn(createFinishingTurn()); const store = FlowChatStore.getInstance(); + store.setState(prev => ({ sessions: new Map(prev.sessions).set('session-1', { + ...prev.sessions.get('session-1')!, sessionKind, agentBackedTransient: sessionKind === 'miniapp', + }) })); const reload = vi.spyOn(store, 'loadSessionHistory').mockResolvedValue(undefined); const context = createFlowChatContext(); handleSessionHistoryChanged(context, { sessionId: 'session-1', settledTurnId: null }); - expect(reload).toHaveBeenCalledExactlyOnceWith('session-1', { includeInternal: false }); + expect(reload).toHaveBeenCalledExactlyOnceWith('session-1', { includeInternal: sessionKind !== 'normal' }); expect(context.pendingHistoryFenceSessions.has('session-1')).toBe(false); }); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts index 2b237edecf..b7b7ccc2ad 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts @@ -1,6 +1,7 @@ import { modelPoolAPI, supportsModelPools } from '@/infrastructure/api/service-api/ModelPoolAPI'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import { sessionWorkspaceId, sessionProjectWorkspacePath } from '../../utils/sessionWorkspace'; +import { shouldIncludeInternalSession } from '../../utils/internalSession'; /** * Event handling module * Initializes event listeners and handles various Agentic events @@ -1712,7 +1713,7 @@ export function handleSessionHistoryChanged(context: FlowChatContext, event: any clearPromptSuggestion(sessionId); context.pendingHistoryFenceSessions.delete(sessionId); void context.flowChatStore.loadSessionHistory(sessionId, { - includeInternal: session.sessionKind === 'subagent', + includeInternal: shouldIncludeInternalSession(session), }).catch(error => { log.warn('Failed to reload changed session history', { sessionId, error }); }); @@ -2488,7 +2489,7 @@ function handleModelRoundComplete(context: FlowChatContext, event: ModelRoundCom const selectionConfig = session.config; void modelPoolAPI.target({ sessionId, workspaceId: sessionWorkspaceId(session), workspacePath: sessionProjectWorkspacePath(session), remoteConnectionId: session.remoteConnectionId, - remoteSshHost: session.remoteSshHost, includeInternal: session.sessionKind === 'subagent' }) + remoteSshHost: session.remoteSshHost, includeInternal: shouldIncludeInternalSession(session) }) .then(target => { if (!scope.isCurrent() || store.getState().sessions.get(sessionId)?.config !== selectionConfig) return; if (target.selection.kind === 'pool') store.updateSessionModelPool(sessionId, target.selection.pool_id, target.binding); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.test.ts index 55a3026d9f..514088c4b6 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.test.ts @@ -1906,13 +1906,14 @@ describe('SessionModule historical session coordination', () => { }); }); - it('restores view-restored subagent sessions as internal coordinator sessions before send', async () => { + it.each(['subagent', 'miniapp'] as const)('restores view-restored %s sessions as internal coordinator sessions before send', async sessionKind => { const { context } = createContext(createSession({ isHistorical: false, historyState: 'ready', contextRestoreState: 'pending', dialogTurns: [{ id: 'turn-1' } as any], - sessionKind: 'subagent', + sessionKind, + agentBackedTransient: sessionKind === 'miniapp', parentSessionId: 'parent-1', subagentType: 'GeneralPurpose', } as any)); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts index cab364b8c7..c1de711f0c 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts @@ -1,5 +1,6 @@ import { requireSessionOwningWorkspaceId } from '../../utils/sessionOrdering'; import { isSessionEmptyForCopy } from '../../utils/sessionCopy'; +import { shouldIncludeInternalSession } from '../../utils/internalSession'; /** * Session management module * Handles session creation, switching, deletion, and other operations @@ -322,7 +323,7 @@ export async function hydrateSessionHistoryForDetail( const session = context.flowChatStore.getState().sessions.get(sessionId); await hydrateHistoricalSession(context, sessionId, false, { allowNonHistorical: true, - includeInternal: session?.sessionKind === 'subagent', + includeInternal: shouldIncludeInternalSession(session), deferFullHistoryUntilActive: false, }); } @@ -1115,7 +1116,7 @@ export async function ensureBackendSession( await agentAPI.ensureCoordinatorSession({ sessionId, workspaceId, - includeInternal: latestSession.sessionKind === 'subagent', + includeInternal: shouldIncludeInternalSession(latestSession), }); surfaceScope.assertCurrent('ensure coordinator session'); markBackendContextReady(); diff --git a/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.test.ts b/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.test.ts index 0bf772cef0..42469d4943 100644 --- a/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.test.ts +++ b/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.test.ts @@ -38,14 +38,34 @@ describe('inheritReviewPermissionMode', () => { expect(getMode).toHaveBeenCalledWith({ sessionId: 'parent', workspacePath: '/project/main', remoteConnectionId: 'ssh-1', remoteSshHost: 'host-1', + includeInternal: false, }); expect(updateMode).toHaveBeenCalledWith({ sessionId: 'child', workspacePath: '/project', remoteConnectionId: 'ssh-1', remoteSshHost: 'host-1', mode: 'auto_approve', + includeInternal: false, }); }, ); + it('inherits a MiniApp parent override using the same internal scope as its composer', async () => { + getMode.mockImplementation(async request => { + if (!request.includeInternal) throw new Error('Session not found'); + return { mode: 'ask' }; + }); + const parent = session({ sessionId: 'parent', sessionKind: 'miniapp', agentBackedTransient: true, + workspaceId: 'appdata-project', workspacePath: '/host/miniapp/topic', + }); + const child = session({ workspaceId: 'review-project' }); + await inheritReviewPermissionMode(child, new Map([['parent', parent]]), vi.fn()); + expect(getMode).toHaveBeenCalledWith(expect.objectContaining({ + sessionId: 'parent', workspaceId: 'appdata-project', includeInternal: true, + })); + expect(updateMode).toHaveBeenCalledWith(expect.objectContaining({ + sessionId: 'child', workspaceId: 'review-project', includeInternal: false, mode: 'ask', + })); + }); + it('refreshes the selection and clears inherited access when the parent resets to default', async () => { getMode.mockResolvedValueOnce({ mode: 'full_access' }) .mockResolvedValueOnce({ mode: 'ask' }) diff --git a/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.ts b/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.ts index e7d1e90958..c078b103f9 100644 --- a/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.ts +++ b/src/web-ui/src/flow_chat/services/inheritReviewPermissionMode.ts @@ -1,7 +1,7 @@ import { agentAPI } from '@/infrastructure/api/service-api/AgentAPI'; import type { Session } from '../types/flow-chat'; import { resolveSessionRelationship } from '../utils/sessionMetadata'; -import { sessionProjectWorkspacePath } from '../utils/sessionWorkspace'; +import { sessionPermissionModeScope } from '../utils/sessionPermissionMode'; /** Refresh the review session's permission selection before submitting work. */ export async function inheritReviewPermissionMode( @@ -17,7 +17,7 @@ export async function inheritReviewPermissionMode( const parent = sessions.get(relationship.parentSessionId); const parentScope = { sessionId: relationship.parentSessionId, - workspacePath: parent?.workspacePath ?? sessionProjectWorkspacePath(child), + ...sessionPermissionModeScope(parent ?? child), remoteConnectionId: parent?.remoteConnectionId ?? child.remoteConnectionId, remoteSshHost: parent?.remoteSshHost ?? child.remoteSshHost, }; @@ -28,9 +28,7 @@ export async function inheritReviewPermissionMode( // Turn-only grants remain scoped to the parent's exact turn. await agentAPI.updateSessionPermissionMode({ sessionId: child.sessionId, - workspacePath: child.workspacePath, - remoteConnectionId: child.remoteConnectionId, - remoteSshHost: child.remoteSshHost, + ...sessionPermissionModeScope(child), mode: mode ?? null, }); assertCurrent(); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 6af88ef7c7..db8d413e8c 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -4363,7 +4363,7 @@ describe('FlowChatStore historical session hydration state', () => { expect(stateMachineManagerMock.reset).not.toHaveBeenCalled(); }); - it('merges restored model and reasoning selections into an existing subagent shell', async () => { + it.each(['subagent', 'miniapp'] as const)('restores an internal %s shell without requiring callers to repeat its visibility', async sessionKind => { apiMocks.restoreSessionView.mockResolvedValueOnce({ session: { sessionId: 'subagent-1', @@ -4382,7 +4382,8 @@ describe('FlowChatStore historical session hydration state', () => { sessions: new Map([ ['subagent-1', createSession({ sessionId: 'subagent-1', - sessionKind: 'subagent', + sessionKind, + agentBackedTransient: sessionKind === 'miniapp', mode: 'Explore', config: { agentType: 'Explore' }, workspacePath: 'D:/workspace/OpenBitFun', @@ -4391,7 +4392,10 @@ describe('FlowChatStore historical session hydration state', () => { activeSessionId: 'parent-1', })); - await flowChatStore.loadSessionHistory('subagent-1', { includeInternal: true }); + await flowChatStore.loadSessionHistory('subagent-1'); + expect(apiMocks.restoreSessionView).toHaveBeenCalledWith( + 'subagent-1', expect.any(String), expect.any(String), true, expect.any(Number), + ); expect(flowChatStore.getState().sessions.get('subagent-1')?.config.modelName) .toBe('model-subagent'); @@ -6433,7 +6437,7 @@ describe('FlowChatStore historical session hydration state', () => { }); }); - it('seeds the restored tail, deduplicates target loads, and merges adjacent ranges', async () => { + it.each(['normal', 'miniapp'] as const)('seeds the %s tail, deduplicates target loads, and merges adjacent ranges', async sessionKind => { const catalog = createTurnCatalog(15); apiMocks.restoreSessionView.mockResolvedValueOnce({ session: { @@ -6456,6 +6460,8 @@ describe('FlowChatStore historical session hydration state', () => { 'history-1', createSession({ sessionId: 'history-1', + sessionKind, + agentBackedTransient: sessionKind === 'miniapp', isHistorical: true, historyState: 'metadata-only', }), @@ -6475,6 +6481,9 @@ describe('FlowChatStore historical session hydration state', () => { const firstLoad = flowChatStore.loadSessionTurnWindow('history-1', 3); const duplicateLoad = flowChatStore.loadSessionTurnWindow('history-1', 3); expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(1); + expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledWith(expect.objectContaining({ + includeInternal: sessionKind === 'miniapp', + })); deferred.resolve({ status: 'ready', catalogRevision: catalog.revision, @@ -8165,8 +8174,11 @@ describe('FlowChatStore reconcile snapshot content safety', () => { .toBeCloseTo(expectedOutput / 4.25); }); - it('repairs a settled local or Peer projection from the host tail', async () => { + it.each(['normal', 'miniapp', 'subagent'] as const)('repairs a settled %s projection from the host tail', async sessionKind => { await hydrateSessionWithContent(); + flowChatStore.setState(prev => ({ sessions: new Map(prev.sessions).set('history-1', { + ...prev.sessions.get('history-1')!, sessionKind, agentBackedTransient: sessionKind === 'miniapp', + }) })); const completeContent = 'OpenBitFun is an agentic IDE… with a complete persisted response.'; flowChatStore.addModelRoundItem('history-1', 'turn-0', { id: 'plan-display-test', @@ -8201,7 +8213,7 @@ describe('FlowChatStore reconcile snapshot content safety', () => { 'history-1', flowChatStore.getState().sessions.get('history-1')!.workspaceId, 'settled-turn-turn-0', - false, + sessionKind !== 'normal', 1, ); expect( diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 82e4fffbb6..4c7f35d029 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -3,6 +3,7 @@ import { forgetAgentCanvasSession, removeBtwSessionFromAgentCanvas } from '@/app import { resolveLegacySessionWorkspace } from '@/infrastructure/api/service-api/legacyWorkspaceCompatibility'; import { projectUserQuestionTiming } from '../utils/userQuestionTiming'; import { externalHistoryFromMetadata } from '../utils/externalHistory'; +import { shouldIncludeInternalSession } from '../utils/internalSession'; import { isExternalSessionEcosystem } from '@/shared/types/external-session'; /** * Flow Chat global state store @@ -3625,7 +3626,7 @@ export class FlowChatStore { workspaceId, remoteConnectionId: session.remoteConnectionId, remoteSshHost: session.remoteSshHost, - includeInternal: session.sessionKind === 'subagent', + includeInternal: shouldIncludeInternalSession(session), requireActiveSession: false, startImmediately: true, initialSessionTraceId: sessionTraceId, @@ -3849,7 +3850,7 @@ export class FlowChatStore { remoteSshHost: session.remoteSshHost, includeInternal: options?.includeInternal - ?? session.sessionKind === 'subagent', + ?? shouldIncludeInternalSession(session), targetOrdinal: normalizedTargetOrdinal, targetStorageTurnIndex: entry.storageTurnIndex, originalTargetTurnId: entry.turnId, @@ -9108,7 +9109,7 @@ export class FlowChatStore { sessionId, this.sessionHistoryWorkspaceId(sessionId), `settled-turn-${turnId.slice(0, 8)}`, - initialSession.sessionKind === 'subagent', + shouldIncludeInternalSession(initialSession), SETTLED_TURN_RECONCILE_TAIL_TURN_COUNT, ); scope.assertCurrent('reconcileSettledDialogTurn'); @@ -9277,6 +9278,8 @@ export class FlowChatStore { ): Promise { const traceStartedAt = nowMs(); const initialSession = this.state.sessions.get(sessionId); + const includeInternal = options?.includeInternal + ?? (shouldIncludeInternalSession(initialSession) || undefined); const prewarmStillApplies = (): boolean => { if (options?.retainInactiveTail !== true) return true; const session = this.state.sessions.get(sessionId); @@ -9431,7 +9434,7 @@ export class FlowChatStore { sessionId, this.sessionHistoryWorkspaceId(sessionId), sessionTraceId, - options?.includeInternal, + includeInternal, ); notifyHydratingState(); const restored = await restoredPromise; @@ -9459,7 +9462,7 @@ export class FlowChatStore { sessionId, this.sessionHistoryWorkspaceId(sessionId), sessionTraceId, - options?.includeInternal, + includeInternal, ); notifyHydratingState(); restoredSessionInfo = await restoredSessionPromise; @@ -9475,7 +9478,7 @@ export class FlowChatStore { sessionId, this.sessionHistoryWorkspaceId(sessionId), sessionTraceId, - options?.includeInternal, + includeInternal, historicalSessionInitialTailTurnCount(remote), ); notifyHydratingState(); @@ -9807,7 +9810,7 @@ export class FlowChatStore { workspaceId: this.sessionHistoryWorkspaceId(sessionId), remoteConnectionId, remoteSshHost, - includeInternal: options?.includeInternal, + includeInternal, requireActiveSession: options?.deferFullHistoryUntilActive === true, initialSessionTraceId: sessionTraceId, expectedDialogTurnIds: dialogTurns.map(turn => turn.id), diff --git a/src/web-ui/src/flow_chat/utils/internalSession.ts b/src/web-ui/src/flow_chat/utils/internalSession.ts new file mode 100644 index 0000000000..65db59cd4c --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/internalSession.ts @@ -0,0 +1,10 @@ +/** + * A UI projection can present a hidden runtime session as a MiniApp or BTW + * conversation. Reuse its runtime ownership marker for host reads and updates; + * presentation kind alone is not the host's visibility contract. + */ +export function shouldIncludeInternalSession( + session: { sessionKind?: string; agentBackedTransient?: boolean } | undefined, +): boolean { + return Boolean(session?.sessionKind === 'subagent' || session?.agentBackedTransient); +} diff --git a/src/web-ui/src/flow_chat/utils/modelSelectionTarget.ts b/src/web-ui/src/flow_chat/utils/modelSelectionTarget.ts index ed3a2db36b..442107df6a 100644 --- a/src/web-ui/src/flow_chat/utils/modelSelectionTarget.ts +++ b/src/web-ui/src/flow_chat/utils/modelSelectionTarget.ts @@ -30,9 +30,4 @@ export function shouldSyncSessionModelSelection