Skip to content

Commit 52361cd

Browse files
committed
fix(web-ui): preserve internal scope across MiniApp session recovery
1 parent 0bff939 commit 52361cd

18 files changed

Lines changed: 130 additions & 70 deletions

‎src/web-ui/AGENTS.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -285,14 +285,16 @@ pnpm --dir src/web-ui run test:run src/flow_chat/hooks/useChatInputModeSync.test
285285
These state/hook fixtures cover delayed session loading and selected peer-surface
286286
replacement; they do not establish native rendering or live remote behavior.
287287

288-
For composer permission reads and updates, including internal MiniApp sessions:
288+
For internal MiniApp session visibility across composer permissions, selectors,
289+
history paging/settlement, and runtime restoration:
289290

290291
```bash
291292
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
293+
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
292294
```
293295

294-
These request/bridge fixtures cover restored topics, legacy path-only scopes and
295-
simulated remote workspace identity. They do not establish native rendering or
296+
These request/bridge/store fixtures cover restored topics, legacy path-only scopes,
297+
history repair, and simulated remote workspace/Peer identity. They do not establish native rendering or
296298
live SSH, Remote Control, Peer Device or Detached Dispatch behavior.
297299

298300
For cross-device undo/redo/rollback history invalidation and settled-Turn fences,

‎src/web-ui/src/flow_chat/components/ChatInput.tsx‎

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ import {
255255
import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag';
256256
import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState';
257257
import { isBtwParentBackedSession, isBtwSessionDraft } from '../utils/modelSelectionTarget';
258+
import { shouldIncludeInternalSession } from '../utils/internalSession';
258259
import { hasSessionStarted, isSessionBindingLocked } from '../utils/sessionLifecycle';
259260
import {
260261
canTreatMissingPermissionModeAsDefault,
@@ -1240,9 +1241,6 @@ export const ChatInput: React.FC<ChatInputProps> = ({
12401241
const sessionOwningId = effectiveTargetSession
12411242
? sessionOwningWorkspaceId(effectiveTargetSession)
12421243
: undefined;
1243-
const sessionOwningPath = effectiveTargetSession
1244-
? sessionProjectWorkspacePath(effectiveTargetSession)
1245-
: undefined;
12461244
// Workspace record the input addresses, or the context workspace while no
12471245
// session exists yet. An empty string means the targeted session has no
12481246
// record; it must not fall back to the context.
@@ -2705,21 +2703,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
27052703
}, [
27062704
activePermissionTurnId,
27072705
effectiveTargetSessionId,
2708-
sessionOwningId,
2709-
sessionOwningPath,
2710-
effectiveTargetSession?.workspacePath,
2711-
effectiveTargetSession?.dialogTurns,
2712-
effectiveTargetSession?.historyState,
2713-
effectiveTargetSession?.isHistorical,
2714-
effectiveTargetSession?.persistedTurnCount,
2715-
effectiveTargetSession?.remoteConnectionId,
2716-
effectiveTargetSession?.remoteSshHost,
2717-
effectiveTargetSession?.sessionKind,
2718-
effectiveTargetSession?.agentBackedTransient,
2719-
effectiveTargetSession?.parentSessionId,
2720-
effectiveTargetSession?.draft,
2721-
effectiveTargetSession?.externalHistory,
2722-
effectiveTargetSession?.externalContinuationPermissionMode,
2706+
effectiveTargetSession,
27232707
isBtwDraftTarget,
27242708
isBtwParentBackedTarget,
27252709
isAcpTargetSession,
@@ -2806,12 +2790,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
28062790
}
28072791
}, [
28082792
effectiveTargetSessionId,
2809-
sessionOwningId,
2810-
sessionOwningPath,
2811-
effectiveTargetSession?.remoteConnectionId,
2812-
effectiveTargetSession?.remoteSshHost,
2813-
effectiveTargetSession?.sessionKind,
2814-
effectiveTargetSession?.agentBackedTransient,
2793+
effectiveTargetSession,
28152794
activeTurnPermissionMode,
28162795
sessionPermissionMode,
28172796
t,
@@ -2929,14 +2908,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
29292908
activeTurnPermissionMode,
29302909
armedTurnPermissionMode,
29312910
confirmFullAccessIfNeeded,
2932-
effectiveTargetSession?.remoteConnectionId,
2933-
effectiveTargetSession?.remoteSshHost,
2934-
effectiveTargetSession?.sessionKind,
2935-
effectiveTargetSession?.agentBackedTransient,
2911+
effectiveTargetSession,
29362912
effectiveTargetSessionId,
29372913
isAcpTargetSession,
2938-
sessionOwningId,
2939-
sessionOwningPath,
29402914
permissionModeSaving,
29412915
t,
29422916
]);
@@ -4817,7 +4791,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
48174791
? {
48184792
sessionId: effectiveTargetSessionId,
48194793
draft: !!effectiveTargetSession.draft,
4794+
workspaceId: sessionOwningWorkspaceId(effectiveTargetSession),
48204795
workspacePath: sessionProjectWorkspacePath(effectiveTargetSession),
4796+
includeInternal: shouldIncludeInternalSession(effectiveTargetSession),
48214797
remoteConnectionId:
48224798
effectiveTargetSession.remoteConnectionId ||
48234799
effectiveTargetSession.config.remoteConnectionId,

‎src/web-ui/src/flow_chat/components/ModelSelector.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1329,7 +1329,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
13291329
identity: routingIdentity, epoch: deviceSurfaceScope.epoch,
13301330
request: { sessionId, workspaceId: activeSession?.workspaceId || activeSession?.config.workspaceId,
13311331
workspacePath: activeSession ? sessionProjectWorkspacePath(activeSession) : undefined,
1332-
remoteConnectionId: activeSession?.remoteConnectionId, remoteSshHost: activeSession?.remoteSshHost },
1332+
remoteConnectionId: activeSession?.remoteConnectionId, remoteSshHost: activeSession?.remoteSshHost,
1333+
includeInternal: shouldIncludeInternalModelSession(activeSession) },
13331334
allowed: canConfigureNativeDefaults, open: dropdownOpen,
13341335
draft: sessionDraft ? { mode: sessionDraft.modelRouting, onChange: mode => {
13351336
if (!sessionId) return;

‎src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1406,6 +1406,24 @@ describe('ModelSelector provider levels', () => {
14061406
expect(document.body.querySelector('[data-testid="model-selection-scope"]')).toBeNull();
14071407
});
14081408

1409+
it('reads the host routing restriction for a MiniApp instead of losing its status to a visibility error', async () => {
1410+
flowChatStoreMocks.sessions.set('miniapp-session', {
1411+
sessionKind: 'miniapp', agentBackedTransient: true, isTransient: true,
1412+
config: { modelName: 'umbra-main' },
1413+
});
1414+
vi.mocked(agentAPI.getModelRoutingStatus).mockImplementation(async request => {
1415+
if (!request?.includeInternal) throw new Error('Session not found');
1416+
return { ...routingHost, ready: false, issue: 'Smart mode is unavailable for subagents' };
1417+
});
1418+
await renderSelector(CATALOG_MODELS, 'umbra-main', 'miniapp-session');
1419+
await openModeMenu();
1420+
expect(agentAPI.getModelRoutingStatus).toHaveBeenCalledWith(expect.objectContaining({
1421+
sessionId: 'miniapp-session', includeInternal: true,
1422+
}));
1423+
expect(modeAction('smart')?.dataset.tooltip).toBe('modelSelector.modes.smart · modelSelector.routing.configurationIssue');
1424+
expect(agentAPI.updateSessionModel).not.toHaveBeenCalled();
1425+
});
1426+
14091427
it('keeps routing and billing configuration out of the all-models defaults', async () => {
14101428
await act(async () => root.render(<DefaultModelConfig models={CATALOG_MODELS} defaultModels={{ primary: 'acme-fast' }}
14111429
loading={false} disabled={false} onDefaultModelsChange={vi.fn()} />));

‎src/web-ui/src/flow_chat/hooks/useSessionModeSelection.test.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,20 @@ vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({
2222
function Probe({
2323
sessionId = 'session-1',
2424
draft = false,
25+
internal = false,
2526
publish = mocks.publish,
2627
}: {
2728
sessionId?: string;
2829
draft?: boolean;
30+
internal?: boolean;
2931
publish?: (modeId: string) => void;
3032
}) {
3133
const selection = useSessionModeSelection(
3234
{
3335
sessionId,
3436
draft,
3537
workspacePath: 'D:/workspace/project',
38+
...(internal ? { workspaceId: 'miniapp-workspace', includeInternal: true } : {}),
3639
},
3740
publish,
3841
mocks.reportFailure,
@@ -69,6 +72,16 @@ describe('useSessionModeSelection', () => {
6972
vi.clearAllMocks();
7073
});
7174

75+
it('preserves the internal MiniApp workspace scope when changing its mode', async () => {
76+
await act(async () => root.render(<Probe internal />));
77+
await act(async () => container.querySelector<HTMLButtonElement>('button')!.click());
78+
expect(mocks.updateSessionMode).toHaveBeenCalledWith(expect.objectContaining({
79+
sessionId: 'session-1', workspaceId: 'miniapp-workspace', includeInternal: true, modeId: 'Standard',
80+
}));
81+
expect(mocks.publish).toHaveBeenCalledWith('Standard');
82+
expect(mocks.reportFailure).not.toHaveBeenCalled();
83+
});
84+
7285
it('keeps an explicit draft selection local until a host session exists', async () => {
7386
await act(async () => root.render(<Probe draft />));
7487
const select = Array.from(container.querySelectorAll('button'))[1];

‎src/web-ui/src/flow_chat/hooks/useSessionModeSelection.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import { agentAPI } from '@/infrastructure/api/service-api/AgentAPI';
55
export interface SessionModeSelectionTarget {
66
draft?: boolean;
77
sessionId: string;
8+
workspaceId?: string;
89
workspacePath?: string;
910
remoteConnectionId?: string;
1011
remoteSshHost?: string;
12+
includeInternal?: boolean;
1113
}
1214

1315
interface ModeSelectionIntent {
@@ -59,9 +61,11 @@ export function useSessionModeSelection(
5961

6062
const sessionId = target?.sessionId;
6163
const draft = target?.draft;
64+
const workspaceId = target?.workspaceId;
6265
const workspacePath = target?.workspacePath;
6366
const remoteConnectionId = target?.remoteConnectionId;
6467
const remoteSshHost = target?.remoteSshHost;
68+
const includeInternal = target?.includeInternal;
6569

6670
const requestModeChange = useCallback((modeId: string) => {
6771
if (!sessionId || draft) {
@@ -73,9 +77,11 @@ export function useSessionModeSelection(
7377
request: {
7478
sessionId,
7579
modeId,
80+
workspaceId,
7681
workspacePath,
7782
remoteConnectionId,
7883
remoteSshHost,
84+
includeInternal,
7985
},
8086
publish: publishRef.current,
8187
reportFailure: failureRef.current,
@@ -118,7 +124,7 @@ export function useSessionModeSelection(
118124
}
119125
};
120126
void run(intent);
121-
}, [draft, notifyQueueChanged, remoteConnectionId, remoteSshHost, sessionId, workspacePath]);
127+
}, [draft, notifyQueueChanged, remoteConnectionId, remoteSshHost, sessionId, workspaceId, workspacePath, includeInternal]);
122128

123129
return {
124130
isModeChangePending: Boolean(sessionId && sessionQueuesRef.current.has(sessionId)),

‎src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1947,15 +1947,18 @@ describe('handleSessionHistoryChanged', () => {
19471947
expect(context.pendingHistoryFenceSessions.has('session-1')).toBe(false);
19481948
});
19491949

1950-
it('reloads an out-of-lifecycle edit even when the obsolete local tail is still finishing', () => {
1950+
it.each(['normal', 'miniapp', 'subagent'] as const)('reloads an out-of-lifecycle %s edit even when the obsolete local tail is still finishing', sessionKind => {
19511951
createSessionWithTurn(createFinishingTurn());
19521952
const store = FlowChatStore.getInstance();
1953+
store.setState(prev => ({ sessions: new Map(prev.sessions).set('session-1', {
1954+
...prev.sessions.get('session-1')!, sessionKind, agentBackedTransient: sessionKind === 'miniapp',
1955+
}) }));
19531956
const reload = vi.spyOn(store, 'loadSessionHistory').mockResolvedValue(undefined);
19541957
const context = createFlowChatContext();
19551958

19561959
handleSessionHistoryChanged(context, { sessionId: 'session-1', settledTurnId: null });
19571960

1958-
expect(reload).toHaveBeenCalledExactlyOnceWith('session-1', { includeInternal: false });
1961+
expect(reload).toHaveBeenCalledExactlyOnceWith('session-1', { includeInternal: sessionKind !== 'normal' });
19591962
expect(context.pendingHistoryFenceSessions.has('session-1')).toBe(false);
19601963
});
19611964

‎src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { modelPoolAPI, supportsModelPools } from '@/infrastructure/api/service-api/ModelPoolAPI';
22
import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface';
33
import { sessionWorkspaceId, sessionProjectWorkspacePath } from '../../utils/sessionWorkspace';
4+
import { shouldIncludeInternalSession } from '../../utils/internalSession';
45
/**
56
* Event handling module
67
* Initializes event listeners and handles various Agentic events
@@ -1712,7 +1713,7 @@ export function handleSessionHistoryChanged(context: FlowChatContext, event: any
17121713
clearPromptSuggestion(sessionId);
17131714
context.pendingHistoryFenceSessions.delete(sessionId);
17141715
void context.flowChatStore.loadSessionHistory(sessionId, {
1715-
includeInternal: session.sessionKind === 'subagent',
1716+
includeInternal: shouldIncludeInternalSession(session),
17161717
}).catch(error => {
17171718
log.warn('Failed to reload changed session history', { sessionId, error });
17181719
});
@@ -2488,7 +2489,7 @@ function handleModelRoundComplete(context: FlowChatContext, event: ModelRoundCom
24882489
const selectionConfig = session.config;
24892490
void modelPoolAPI.target({ sessionId, workspaceId: sessionWorkspaceId(session),
24902491
workspacePath: sessionProjectWorkspacePath(session), remoteConnectionId: session.remoteConnectionId,
2491-
remoteSshHost: session.remoteSshHost, includeInternal: session.sessionKind === 'subagent' })
2492+
remoteSshHost: session.remoteSshHost, includeInternal: shouldIncludeInternalSession(session) })
24922493
.then(target => {
24932494
if (!scope.isCurrent() || store.getState().sessions.get(sessionId)?.config !== selectionConfig) return;
24942495
if (target.selection.kind === 'pool') store.updateSessionModelPool(sessionId, target.selection.pool_id, target.binding);

‎src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1906,13 +1906,14 @@ describe('SessionModule historical session coordination', () => {
19061906
});
19071907
});
19081908

1909-
it('restores view-restored subagent sessions as internal coordinator sessions before send', async () => {
1909+
it.each(['subagent', 'miniapp'] as const)('restores view-restored %s sessions as internal coordinator sessions before send', async sessionKind => {
19101910
const { context } = createContext(createSession({
19111911
isHistorical: false,
19121912
historyState: 'ready',
19131913
contextRestoreState: 'pending',
19141914
dialogTurns: [{ id: 'turn-1' } as any],
1915-
sessionKind: 'subagent',
1915+
sessionKind,
1916+
agentBackedTransient: sessionKind === 'miniapp',
19161917
parentSessionId: 'parent-1',
19171918
subagentType: 'GeneralPurpose',
19181919
} as any));

‎src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { requireSessionOwningWorkspaceId } from '../../utils/sessionOrdering';
22
import { isSessionEmptyForCopy } from '../../utils/sessionCopy';
3+
import { shouldIncludeInternalSession } from '../../utils/internalSession';
34
/**
45
* Session management module
56
* Handles session creation, switching, deletion, and other operations
@@ -322,7 +323,7 @@ export async function hydrateSessionHistoryForDetail(
322323
const session = context.flowChatStore.getState().sessions.get(sessionId);
323324
await hydrateHistoricalSession(context, sessionId, false, {
324325
allowNonHistorical: true,
325-
includeInternal: session?.sessionKind === 'subagent',
326+
includeInternal: shouldIncludeInternalSession(session),
326327
deferFullHistoryUntilActive: false,
327328
});
328329
}
@@ -1115,7 +1116,7 @@ export async function ensureBackendSession(
11151116
await agentAPI.ensureCoordinatorSession({
11161117
sessionId,
11171118
workspaceId,
1118-
includeInternal: latestSession.sessionKind === 'subagent',
1119+
includeInternal: shouldIncludeInternalSession(latestSession),
11191120
});
11201121
surfaceScope.assertCurrent('ensure coordinator session');
11211122
markBackendContextReady();

0 commit comments

Comments
 (0)