Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/web-ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,18 @@ 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 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/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,
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
Expand Down
46 changes: 10 additions & 36 deletions src/web-ui/src/flow_chat/components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,12 @@ 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,
isSessionNotFoundError,
sessionPermissionModeScope,
} from '../utils/sessionPermissionMode';
import { prepareSessionDraftForCommand } from '../services/sessionDraftService';
import { useSessionWorkspaceSelection } from '../hooks/useSessionWorkspaceSelection';
Expand Down Expand Up @@ -1239,9 +1241,6 @@ export const ChatInput: React.FC<ChatInputProps> = ({
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.
Expand Down Expand Up @@ -2650,10 +2649,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
}, () => 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);
Expand Down Expand Up @@ -2707,19 +2703,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
}, [
activePermissionTurnId,
effectiveTargetSessionId,
sessionOwningId,
sessionOwningPath,
effectiveTargetSession?.workspacePath,
effectiveTargetSession?.dialogTurns,
effectiveTargetSession?.historyState,
effectiveTargetSession?.isHistorical,
effectiveTargetSession?.persistedTurnCount,
effectiveTargetSession?.remoteConnectionId,
effectiveTargetSession?.remoteSshHost,
effectiveTargetSession?.parentSessionId,
effectiveTargetSession?.draft,
effectiveTargetSession?.externalHistory,
effectiveTargetSession?.externalContinuationPermissionMode,
effectiveTargetSession,
isBtwDraftTarget,
isBtwParentBackedTarget,
isAcpTargetSession,
Expand Down Expand Up @@ -2774,10 +2758,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
sessionId: targetSessionId,
mode: nextMode,
turnId: targetTurnId ?? undefined,
workspaceId: sessionOwningId,
workspacePath: sessionOwningPath,
remoteConnectionId: effectiveTargetSession?.remoteConnectionId,
remoteSshHost: effectiveTargetSession?.remoteSshHost,
...sessionPermissionModeScope(effectiveTargetSession),
});
if (
permissionModeRequestGenerationRef.current === generation
Expand Down Expand Up @@ -2809,10 +2790,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
}
}, [
effectiveTargetSessionId,
sessionOwningId,
sessionOwningPath,
effectiveTargetSession?.remoteConnectionId,
effectiveTargetSession?.remoteSshHost,
effectiveTargetSession,
activeTurnPermissionMode,
sessionPermissionMode,
t,
Expand Down Expand Up @@ -2897,10 +2875,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
sessionId: targetSessionId,
turnId: targetTurnId,
mode: nextTemporaryMode,
workspaceId: sessionOwningId,
workspacePath: sessionOwningPath,
remoteConnectionId: effectiveTargetSession?.remoteConnectionId,
remoteSshHost: effectiveTargetSession?.remoteSshHost,
...sessionPermissionModeScope(effectiveTargetSession),
});
if (
permissionModeRequestGenerationRef.current === generation
Expand Down Expand Up @@ -2933,12 +2908,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
activeTurnPermissionMode,
armedTurnPermissionMode,
confirmFullAccessIfNeeded,
effectiveTargetSession?.remoteConnectionId,
effectiveTargetSession?.remoteSshHost,
effectiveTargetSession,
effectiveTargetSessionId,
isAcpTargetSession,
sessionOwningId,
sessionOwningPath,
permissionModeSaving,
t,
]);
Expand Down Expand Up @@ -4819,7 +4791,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
? {
sessionId: effectiveTargetSessionId,
draft: !!effectiveTargetSession.draft,
workspaceId: sessionOwningWorkspaceId(effectiveTargetSession),
workspacePath: sessionProjectWorkspacePath(effectiveTargetSession),
includeInternal: shouldIncludeInternalSession(effectiveTargetSession),
remoteConnectionId:
effectiveTargetSession.remoteConnectionId ||
effectiveTargetSession.config.remoteConnectionId,
Expand Down
3 changes: 2 additions & 1 deletion src/web-ui/src/flow_chat/components/ModelSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(<DefaultModelConfig models={CATALOG_MODELS} defaultModels={{ primary: 'acme-fast' }}
loading={false} disabled={false} onDefaultModelsChange={vi.fn()} />));
Expand Down
13 changes: 13 additions & 0 deletions src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,20 @@ 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(
{
sessionId,
draft,
workspacePath: 'D:/workspace/project',
...(internal ? { workspaceId: 'miniapp-workspace', includeInternal: true } : {}),
},
publish,
mocks.reportFailure,
Expand Down Expand Up @@ -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(<Probe internal />));
await act(async () => container.querySelector<HTMLButtonElement>('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(<Probe draft />));
const select = Array.from(container.querySelectorAll('button'))[1];
Expand Down
8 changes: 7 additions & 1 deletion src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand All @@ -73,9 +77,11 @@ export function useSessionModeSelection(
request: {
sessionId,
modeId,
workspaceId,
workspacePath,
remoteConnectionId,
remoteSshHost,
includeInternal,
},
publish: publishRef.current,
reportFailure: failureRef.current,
Expand Down Expand Up @@ -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)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 });
});
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
});
}
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
Expand Down
Loading
Loading