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
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ vi.mock('@/infrastructure/services/business/workspaceManager', () => ({
workspaceManager: { getState: () => ({ openedWorkspaces: mocks.workspaces }), setActiveWorkspace: vi.fn() },
}));
vi.mock('@/app/utils/projectSessionWorkspace', () => ({
findReusableEmptySessionId: () => null,
flowChatSessionConfigForWorkspace: (workspace: { id: string }) => ({ workspaceId: workspace.id }),
}));
vi.mock('../workspaces/openLatestAssistantSession', () => ({ openLatestAssistantSession: mocks.openLatestAssistant }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { flowChatStore } from '@/flow_chat/store/FlowChatStore';
import { flowChatManager } from '@/flow_chat/services/FlowChatManager';
import { openMainSession } from '@/flow_chat/services/sessionActivation';
import { prewarmRelaySessionHistory } from '@/flow_chat/services/RelaySessionHistory';
import { findReusableEmptySessionId, flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
import { flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
import { WorkspaceKind, type WorkspaceInfo } from '@/shared/types';
import { openLatestAssistantSession } from '../workspaces/openLatestAssistantSession';
import { useSceneStore } from '@/app/stores/sceneStore';
Expand Down Expand Up @@ -177,9 +177,7 @@ export async function createDeviceSession(
const scope = getActiveSurfaceScope();
const workspace = liveWorkspace(workspaceId);
const mode = workspace.workspaceKind === WorkspaceKind.Assistant ? 'Claw' : undefined;
// Same reuse rule as the local "new session" action.
const sessionId = findReusableEmptySessionId(workspace, mode)
?? await flowChatManager.createChatDraft(flowChatSessionConfigForWorkspace(workspace), mode);
const sessionId = await flowChatManager.createChatDraft(flowChatSessionConfigForWorkspace(workspace), mode);
scope.assertCurrent('open new device session');
await openMainSession(sessionId, { workspaceId, activateWorkspace, isCurrent: scope.isCurrent });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ import {
SESSION_LOADING_DELAY_MS,
subscribeHistorySessionOpenTransition,
} from '@/flow_chat/services/sessionOpenIntent';
import {
findReusableEmptySessionId,
flowChatSessionConfigForWorkspace,
} from '@/app/utils/projectSessionWorkspace';
import { flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
import type { AcpClientInfo } from '@/infrastructure/api/service-api/ACPClientAPI';
import { loadWorkspaceAcpMenuClients } from './workspaceAcpMenuClients';
import WorkspaceAcpSessionSubmenu from './WorkspaceAcpSessionSubmenu';
Expand Down Expand Up @@ -744,10 +741,7 @@ const WorkspaceItem: React.FC<WorkspaceItemProps> = ({
}
}, [t, workspace.rootPath]);

// One new session per gesture: a second click while the first is being
// created would open a second draft. The pending state is rendered on the
// button (busy + disabled) so a slow create, e.g. over a peer relay, is
// visibly in progress instead of silently swallowing clicks.
// Keep slow draft preparation visible, including over a peer relay.
const [creatingSession, setCreatingSession] = useState(false);
const showCreatingSessionIndicator = useDelayedPendingIndicator(creatingSession);
const handleCreateSession = useCallback(async (mode?: 'Standard' | 'Cowork' | 'Claw') => {
Expand All @@ -756,14 +750,6 @@ const WorkspaceItem: React.FC<WorkspaceItemProps> = ({
setCreatingSession(true);
const resolvedMode = mode ?? (workspace.workspaceKind === WorkspaceKind.Assistant ? 'Claw' : undefined);
try {
const reusableId = findReusableEmptySessionId(workspace, resolvedMode);
if (reusableId) {
await openMainSession(reusableId, {
workspaceId: workspace.id,
activateWorkspace: setActiveWorkspace,
});
return;
}
const newSessionId = await flowChatManager.createChatDraft(
flowChatSessionConfigForWorkspace(workspace),
resolvedMode
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe('assistant bootstrap draft', () => {
await render();
expect(readWorkspaceFile).toHaveBeenCalledWith('assistant-default', '/assistants/default/BOOTSTRAP.md');
expect(sessionComposerStore.getState().getDraft('claw-1').value).toBe('nav.sessions.assistantBootstrapDraft');
expect(sessionComposerStore.getState().getDraft('claw-1').prefillSource).toBe('assistant-bootstrap');
expect(submit).not.toHaveBeenCalled();
});

Expand Down
3 changes: 3 additions & 0 deletions src/web-ui/src/app/hooks/useAssistantBootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export function useAssistantBootstrap(
const latest = sessionComposerStore.getState().getDraft(sessionId);
if (latest.updatedAt !== draft.updatedAt || latest.value || latest.contexts.length) return;
onDraftReady(t('nav.sessions.assistantBootstrapDraft'));
sessionComposerStore.getState().setPrefill(
sessionId, t('nav.sessions.assistantBootstrapDraft'), 'assistant-bootstrap', requestScope.surfaceId,
);
}).catch(error => {
if (cancelled || !requestScope.isCurrent()) return;
// Completed assistants no longer have BOOTSTRAP.md. Other failures remain diagnosable.
Expand Down
60 changes: 1 addition & 59 deletions src/web-ui/src/app/utils/projectSessionWorkspace.test.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,9 @@
import { afterEach, describe, expect, it } from 'vitest';
import { flowChatStore } from '@/flow_chat/store/FlowChatStore';
import type { FlowChatState, Session } from '@/flow_chat/types/flow-chat';
import { describe, expect, it } from 'vitest';
import { WorkspaceKind, type WorkspaceInfo } from '@/shared/types';
import {
findReusableEmptySessionId,
pickPrimaryAssistantWorkspace,
} from './projectSessionWorkspace';

const resetStore = () => {
flowChatStore.setState((): FlowChatState => ({
sessions: new Map(),
activeSessionId: null,
}));
};

const createWorkspace = (): WorkspaceInfo => ({
id: 'workspace-1',
name: 'OpenBitFun',
rootPath: '/workspace/OpenBitFun',
workspaceKind: WorkspaceKind.Normal,
});

const createSession = (overrides: Partial<Session> = {}): Session => ({
sessionId: 'session-1',
title: 'Session 1',
dialogTurns: [],
status: 'idle',
config: { agentType: 'Standard' },
createdAt: 1,
lastActiveAt: 1,
error: null,
isHistorical: false,
maxContextTokens: 128128,
mode: 'Standard',
workspacePath: '/workspace/OpenBitFun',
workspaceId: 'workspace-1',
sessionKind: 'normal',
btwThreads: [],
isTransient: false,
...overrides,
});

describe('findReusableEmptySessionId', () => {
afterEach(() => {
resetStore();
});

it('never reuses an existing session', () => {
const workspace = createWorkspace();
const codeSession = createSession({
sessionId: 'code-session',
lastActiveAt: 5,
});

flowChatStore.setState(() => ({
sessions: new Map([[codeSession.sessionId, codeSession]]),
activeSessionId: codeSession.sessionId,
}));

expect(findReusableEmptySessionId(workspace, 'Standard')).toBeNull();
});
});

describe('pickPrimaryAssistantWorkspace', () => {
const createAssistantWorkspace = (
id: string,
Expand Down
10 changes: 0 additions & 10 deletions src/web-ui/src/app/utils/projectSessionWorkspace.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
import { WorkspaceKind, isRemoteWorkspace, type WorkspaceInfo } from '@/shared/types';
import { workspaceManager } from '@/infrastructure/services/business/workspaceManager';

/**
* Always create a new session instead of reusing an existing empty one.
*/
export function findReusableEmptySessionId(
_workspace: WorkspaceInfo,
_requestedMode?: string
): string | null {
return null;
}

/**
* Code / Cowork sessions belong to project (non-assistant) workspaces only.
* Assistant “instances” use Claw sessions under their own storage.
Expand Down
6 changes: 4 additions & 2 deletions src/web-ui/src/flow_chat/services/FlowChatManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,21 +342,23 @@ describe('FlowChatManager initialization', () => {
}
});

it('creates one empty Claw session when reinitializing a reset workspace', async () => {
it('creates one Claw draft when reinitializing a reset workspace', async () => {
storeMocks.store = {
registerPersistUnreadCompletionCallback: vi.fn(),
removeSessionsForWorkspace: vi.fn(() => []),
getState: () => ({ activeSessionId: null, sessions: new Map() }),
};
const manager = FlowChatManager.getInstance();
const initialize = vi.spyOn(manager, 'initialize').mockResolvedValue(false);
const create = vi.spyOn(manager, 'createChatSession').mockResolvedValue('claw-new');
const create = vi.spyOn(manager, 'createChatDraft').mockResolvedValue('claw-new');
const backendCreate = vi.spyOn(manager, 'createChatSession');
const send = vi.spyOn(manager, 'sendMessage');
await manager.resetWorkspaceSessions({ id: 'assistant', rootPath: '/assistants/default', workspaceKind: 'assistant' as any }, {
reinitialize: true, preferredMode: 'Claw',
});
expect(initialize).toHaveBeenCalledWith(expect.objectContaining({ id: 'assistant' }), 'Claw');
expect(create).toHaveBeenCalledExactlyOnceWith({ workspacePath: '/assistants/default', workspaceId: 'assistant' }, 'Claw');
expect(backendCreate).not.toHaveBeenCalled();
expect(send).not.toHaveBeenCalled();
manager.destroy();
});
Expand Down
4 changes: 2 additions & 2 deletions src/web-ui/src/flow_chat/services/FlowChatManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ export class FlowChatManager {
return createChatSessionModule(this.context, config, mode);
}

/** User-facing new conversations acquire their host session on first submission. */
/** Reuse a blank draft, or reserve a conversation that reaches its host on first submission. */
async createChatDraft(config: SessionConfig, mode?: string): Promise<string> {
return createChatSessionModule(this.context, config, mode, true);
}
Expand Down Expand Up @@ -827,7 +827,7 @@ export class FlowChatManager {
sessionBelongsToWorkspaceNavRow(activeSession, workspace.id);

if (!hasHistoricalSessions || !hasActiveWorkspaceSession) {
await this.createChatSession(
await this.createChatDraft(
{
workspacePath,
workspaceId: workspace.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -666,9 +666,9 @@ describe('MessageModule session writer conflict', () => {
});

describe('MessageModule first draft submission', () => {
function draftContext() {
function draftContext(mode = 'Standard') {
let state: any = { activeSessionId: 'draft-first', sessions: new Map([['draft-first', {
sessionId: 'draft-first', mode: 'Standard', workspaceId: 'b', workspacePath: '/b',
sessionId: 'draft-first', mode, workspaceId: 'b', workspacePath: '/b',
dialogTurns: [], config: { modelName: 'primary' }, titleStatus: 'generated',
maxContextTokens: 32000, draft: { workspaceId: 'b', phase: 'ready', turnId: 'reserved-first-turn' },
}]]) };
Expand Down Expand Up @@ -702,8 +702,8 @@ describe('MessageModule first draft submission', () => {
mockHostQueueSupported.mockReturnValue(false);
});

it('commits the draft and selects the target session only after the host accepts its first message', async () => {
const { context, store } = draftContext();
it.each(['Standard', 'Claw'])('commits the %s draft only after the host accepts its first message', async mode => {
const { context, store } = draftContext(mode);
mockHostQueueSubmit.mockImplementation(async () => {
expect(store.getState().sessions.get('draft-first').draft.phase).toBe('submitting');
expect(mockActivateMainSession).not.toHaveBeenCalled();
Expand All @@ -712,12 +712,12 @@ describe('MessageModule first draft submission', () => {
await sendMessage(context, 'First message', 'draft-first');
expect(mockHostQueueSubmit.mock.calls[0][2]).toBe('reserved-first-turn');
expect(store.getState().sessions.get('draft-first').draft).toBeUndefined();
expect(store.getState().sessions.get('draft-first').lastSubmittedMode).toBe('Standard');
expect(store.getState().sessions.get('draft-first').lastSubmittedMode).toBe(mode);
expect(mockActivateMainSession).toHaveBeenCalledWith('draft-first', expect.any(Object));
});

it('preserves the first turn identity and locked target across an ambiguous acknowledgement', async () => {
const { context, store } = draftContext();
it.each(['Standard', 'Claw'])('preserves the first %s turn identity across an ambiguous acknowledgement', async mode => {
const { context, store } = draftContext(mode);
mockHostQueueSubmit.mockRejectedValueOnce(new Error('Connection lost'));
await expect(sendMessage(context, 'First message', 'draft-first')).rejects.toThrow('Connection lost');
expect(store.getState().sessions.get('draft-first').draft.phase).toBe('submitting');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const persistenceMocks = vi.hoisted(() => ({

const stateMachineMocks = vi.hoisted(() => ({
delete: vi.fn(),
getCurrentState: vi.fn(() => 'idle'),
}));

const dispatchStoreMocks = vi.hoisted(() => ({
Expand Down Expand Up @@ -127,6 +128,7 @@ vi.mock('./TextChunkModule', () => ({

vi.mock('../../state-machine', () => ({
stateMachineManager: stateMachineMocks,
SessionExecutionState: { IDLE: 'idle' },
}));

vi.mock('@/features/dispatch/dispatchJobStore', () => ({
Expand Down Expand Up @@ -210,15 +212,20 @@ function createContext(
workspacePath?: string,
remoteConnectionId?: string,
remoteSshHost?: string,
_titleDescriptor?: unknown,
draft?: Session['draft'],
) => {
const nextSession = createSession({
sessionId,
title: title ?? sessionId,
isHistorical: false,
historyState: 'ready',
config: {
...config,
agentType: agentType ?? (config?.agentType as string | undefined) ?? 'Standard',
},
workspaceId: config?.workspaceId as string | undefined,
draft,
mode: agentType ?? 'Standard',
workspacePath: workspacePath ?? (config?.workspacePath as string | undefined) ?? session.workspacePath,
remoteConnectionId,
Expand Down Expand Up @@ -422,10 +429,12 @@ describe('createChatSession', () => {
});
const { context } = createContext(createSession());
try {
await expect(createChatSession(context, { workspaceId: assistant.id }, 'Claw', true)).resolves.toBe('created-1');
expect(agentApiMocks.createSession).toHaveBeenCalledWith(expect.objectContaining({
workspaceId: assistant.id, workspacePath: assistant.rootPath, agentType: 'Claw',
}));
const id = await createChatSession(context, { workspaceId: assistant.id }, 'Claw', true);
expect(context.flowChatStore.getState().sessions.get(id)).toMatchObject({
workspaceId: assistant.id, workspacePath: assistant.rootPath, mode: 'Claw',
draft: { workspaceId: assistant.id, phase: 'editing' },
});
expect(agentApiMocks.createSession).not.toHaveBeenCalled();
} finally {
workspaceState.mockRestore();
}
Expand Down Expand Up @@ -459,6 +468,59 @@ describe('createChatSession', () => {
expect(agentApiMocks.createSession).toHaveBeenCalledTimes(1);
});

it.each(['Standard', 'Claw'])('reuses sequential and concurrent %s draft requests without a host create', async mode => {
const { context, flowChatStore } = createContext(createSession());
const config = { workspaceId: 'workspace-1' };
const ids = await Promise.all([
createChatSession(context, config, mode, true),
createChatSession(context, config, mode, true),
]);
expect(ids[0]).toBe(ids[1]);
flowChatStore.switchSession('history-1');
expect(await createChatSession(context, config, mode, true)).toBe(ids[0]);
expect(flowChatStore.getState().activeSessionId).toBe(ids[0]);
expect(flowChatStore.createSession).toHaveBeenCalledOnce();
expect(agentApiMocks.createSession).not.toHaveBeenCalled();
});

it('resolves the configured default mode before looking for reusable drafts', async () => {
projectDefaults.read.mockResolvedValueOnce({ supported: true, defaults: { mode: 'Cowork' } });
agentApiMocks.getAvailableModes.mockResolvedValue([{ id: 'Standard' }, { id: 'Cowork' }]);
const { context, flowChatStore } = createContext(createSession({
sessionId: 'cowork-draft', mode: 'Cowork', sessionKind: 'normal',
isHistorical: false, historyState: 'new',
draft: { workspaceId: 'workspace-1', phase: 'editing', turnId: 'first' },
}));
expect(await createChatSession(context, { workspaceId: 'workspace-1' }, undefined, true)).toBe('cowork-draft');
expect(flowChatStore.createSession).not.toHaveBeenCalled();
expect(agentApiMocks.createSession).not.toHaveBeenCalled();
});

it('creates another draft once the existing composer has user content', async () => {
const { sessionComposerStore } = await import('../../store/sessionComposerStore');
const { context, flowChatStore } = createContext(createSession());
const first = await createChatSession(context, { workspaceId: 'workspace-1' }, 'Claw', true);
sessionComposerStore.getState().setValue(first, 'Unsent request');
try {
const second = await createChatSession(context, { workspaceId: 'workspace-1' }, 'Claw', true);
expect(second).not.toBe(first);
expect(flowChatStore.createSession).toHaveBeenCalledTimes(2);
expect(sessionComposerStore.getState().getDraft(first).value).toBe('Unsent request');
expect(agentApiMocks.createSession).not.toHaveBeenCalled();
} finally { sessionComposerStore.getState().removeDrafts([first]); }
});

it('keeps concurrent drafts with explicit different models separate', async () => {
const { context, flowChatStore } = createContext(createSession());
const [first, second] = await Promise.all([
createChatSession(context, { workspaceId: 'workspace-1', modelName: 'a' }, 'Standard', true),
createChatSession(context, { workspaceId: 'workspace-1', modelName: 'b' }, 'Standard', true),
]);
expect(first).not.toBe(second);
expect(flowChatStore.getState().sessions.get(first)?.config.modelName).toBe('a');
expect(flowChatStore.getState().sessions.get(second)?.config.modelName).toBe('b');
});

it('does not reuse or project a session creation from a superseded device activation', async () => {
const firstResponse = createDeferred<{ sessionId: string }>();
const secondResponse = createDeferred<{ sessionId: string }>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
} from '../../utils/sessionWorkspace';
import { driverForCreation, driverForSession } from '../../session-drivers/registry';
import { materializeSessionDraft } from '../sessionDraftService';
import { findReusableSessionDraft } from '../sessionDraftReuse';
import {
isProjectedFirstRuntimeTurn,
isProjectedSessionEmpty,
Expand Down Expand Up @@ -558,6 +559,7 @@ export async function createChatSession(
agentType,
JSON.stringify(config.executionTargetRequest ?? { kind: 'local' }),
JSON.stringify(config.dispatchTargetRequest ?? { kind: 'local' }),
draft ? JSON.stringify(config) : undefined,
);

const pendingCreation = pendingSessionCreations.get(creationKey);
Expand All @@ -569,6 +571,15 @@ export async function createChatSession(
// activation can rerun initialization while model config is still loading.
const createPromise = Promise.resolve().then(async () => {
surfaceScope.assertCurrent('start session creation');
if (draft) {
const reusableId = findReusableSessionDraft(
context.flowChatStore.getState(), workspace.id, agentType, config,
);
if (reusableId) {
context.flowChatStore.switchSession(reusableId);
return reusableId;
}
}
const titleDescriptor = createDefaultSessionTitleDescriptor(
(key, options) => i18nService.t(key, options),
);
Expand Down
Loading
Loading