Skip to content

Commit 002dfc0

Browse files
committed
fix(flow-chat): Reuse blank drafts and defer Claw creation
Keep blank Claw conversations as frontend drafts until first submission. Reuse eligible drafts across new-session entry points while preserving user input, attachments, recovery state, and device isolation. Preserve assistant bootstrap prefills and materialize explicit default session selections before persisting their host pointers. Validation: 467 focused tests, check:web, and TypeScript checks passed. Remote coverage uses simulated workspace and device fixtures.
1 parent de50758 commit 002dfc0

21 files changed

Lines changed: 390 additions & 117 deletions

‎src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ vi.mock('@/infrastructure/services/business/workspaceManager', () => ({
6666
workspaceManager: { getState: () => ({ openedWorkspaces: mocks.workspaces }), setActiveWorkspace: vi.fn() },
6767
}));
6868
vi.mock('@/app/utils/projectSessionWorkspace', () => ({
69-
findReusableEmptySessionId: () => null,
7069
flowChatSessionConfigForWorkspace: (workspace: { id: string }) => ({ workspaceId: workspace.id }),
7170
}));
7271
vi.mock('../workspaces/openLatestAssistantSession', () => ({ openLatestAssistantSession: mocks.openLatestAssistant }));

‎src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { flowChatStore } from '@/flow_chat/store/FlowChatStore';
1818
import { flowChatManager } from '@/flow_chat/services/FlowChatManager';
1919
import { openMainSession } from '@/flow_chat/services/sessionActivation';
2020
import { prewarmRelaySessionHistory } from '@/flow_chat/services/RelaySessionHistory';
21-
import { findReusableEmptySessionId, flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
21+
import { flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
2222
import { WorkspaceKind, type WorkspaceInfo } from '@/shared/types';
2323
import { openLatestAssistantSession } from '../workspaces/openLatestAssistantSession';
2424
import { useSceneStore } from '@/app/stores/sceneStore';
@@ -177,9 +177,7 @@ export async function createDeviceSession(
177177
const scope = getActiveSurfaceScope();
178178
const workspace = liveWorkspace(workspaceId);
179179
const mode = workspace.workspaceKind === WorkspaceKind.Assistant ? 'Claw' : undefined;
180-
// Same reuse rule as the local "new session" action.
181-
const sessionId = findReusableEmptySessionId(workspace, mode)
182-
?? await flowChatManager.createChatDraft(flowChatSessionConfigForWorkspace(workspace), mode);
180+
const sessionId = await flowChatManager.createChatDraft(flowChatSessionConfigForWorkspace(workspace), mode);
183181
scope.assertCurrent('open new device session');
184182
await openMainSession(sessionId, { workspaceId, activateWorkspace, isCurrent: scope.isCurrent });
185183
}

‎src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceItem.tsx‎

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,7 @@ import {
5050
SESSION_LOADING_DELAY_MS,
5151
subscribeHistorySessionOpenTransition,
5252
} from '@/flow_chat/services/sessionOpenIntent';
53-
import {
54-
findReusableEmptySessionId,
55-
flowChatSessionConfigForWorkspace,
56-
} from '@/app/utils/projectSessionWorkspace';
53+
import { flowChatSessionConfigForWorkspace } from '@/app/utils/projectSessionWorkspace';
5754
import type { AcpClientInfo } from '@/infrastructure/api/service-api/ACPClientAPI';
5855
import { loadWorkspaceAcpMenuClients } from './workspaceAcpMenuClients';
5956
import WorkspaceAcpSessionSubmenu from './WorkspaceAcpSessionSubmenu';
@@ -744,10 +741,7 @@ const WorkspaceItem: React.FC<WorkspaceItemProps> = ({
744741
}
745742
}, [t, workspace.rootPath]);
746743

747-
// One new session per gesture: a second click while the first is being
748-
// created would open a second draft. The pending state is rendered on the
749-
// button (busy + disabled) so a slow create, e.g. over a peer relay, is
750-
// visibly in progress instead of silently swallowing clicks.
744+
// Keep slow draft preparation visible, including over a peer relay.
751745
const [creatingSession, setCreatingSession] = useState(false);
752746
const showCreatingSessionIndicator = useDelayedPendingIndicator(creatingSession);
753747
const handleCreateSession = useCallback(async (mode?: 'Standard' | 'Cowork' | 'Claw') => {
@@ -756,14 +750,6 @@ const WorkspaceItem: React.FC<WorkspaceItemProps> = ({
756750
setCreatingSession(true);
757751
const resolvedMode = mode ?? (workspace.workspaceKind === WorkspaceKind.Assistant ? 'Claw' : undefined);
758752
try {
759-
const reusableId = findReusableEmptySessionId(workspace, resolvedMode);
760-
if (reusableId) {
761-
await openMainSession(reusableId, {
762-
workspaceId: workspace.id,
763-
activateWorkspace: setActiveWorkspace,
764-
});
765-
return;
766-
}
767753
const newSessionId = await flowChatManager.createChatDraft(
768754
flowChatSessionConfigForWorkspace(workspace),
769755
resolvedMode

‎src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ describe('assistant bootstrap draft', () => {
6262
await render();
6363
expect(readWorkspaceFile).toHaveBeenCalledWith('assistant-default', '/assistants/default/BOOTSTRAP.md');
6464
expect(sessionComposerStore.getState().getDraft('claw-1').value).toBe('nav.sessions.assistantBootstrapDraft');
65+
expect(sessionComposerStore.getState().getDraft('claw-1').prefillSource).toBe('assistant-bootstrap');
6566
expect(submit).not.toHaveBeenCalled();
6667
});
6768

‎src/web-ui/src/app/hooks/useAssistantBootstrap.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ export function useAssistantBootstrap(
4343
const latest = sessionComposerStore.getState().getDraft(sessionId);
4444
if (latest.updatedAt !== draft.updatedAt || latest.value || latest.contexts.length) return;
4545
onDraftReady(t('nav.sessions.assistantBootstrapDraft'));
46+
sessionComposerStore.getState().setPrefill(
47+
sessionId, t('nav.sessions.assistantBootstrapDraft'), 'assistant-bootstrap', requestScope.surfaceId,
48+
);
4649
}).catch(error => {
4750
if (cancelled || !requestScope.isCurrent()) return;
4851
// Completed assistants no longer have BOOTSTRAP.md. Other failures remain diagnosable.

‎src/web-ui/src/app/utils/projectSessionWorkspace.test.ts‎

Lines changed: 1 addition & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,9 @@
1-
import { afterEach, describe, expect, it } from 'vitest';
2-
import { flowChatStore } from '@/flow_chat/store/FlowChatStore';
3-
import type { FlowChatState, Session } from '@/flow_chat/types/flow-chat';
1+
import { describe, expect, it } from 'vitest';
42
import { WorkspaceKind, type WorkspaceInfo } from '@/shared/types';
53
import {
6-
findReusableEmptySessionId,
74
pickPrimaryAssistantWorkspace,
85
} from './projectSessionWorkspace';
96

10-
const resetStore = () => {
11-
flowChatStore.setState((): FlowChatState => ({
12-
sessions: new Map(),
13-
activeSessionId: null,
14-
}));
15-
};
16-
17-
const createWorkspace = (): WorkspaceInfo => ({
18-
id: 'workspace-1',
19-
name: 'OpenBitFun',
20-
rootPath: '/workspace/OpenBitFun',
21-
workspaceKind: WorkspaceKind.Normal,
22-
});
23-
24-
const createSession = (overrides: Partial<Session> = {}): Session => ({
25-
sessionId: 'session-1',
26-
title: 'Session 1',
27-
dialogTurns: [],
28-
status: 'idle',
29-
config: { agentType: 'Standard' },
30-
createdAt: 1,
31-
lastActiveAt: 1,
32-
error: null,
33-
isHistorical: false,
34-
maxContextTokens: 128128,
35-
mode: 'Standard',
36-
workspacePath: '/workspace/OpenBitFun',
37-
workspaceId: 'workspace-1',
38-
sessionKind: 'normal',
39-
btwThreads: [],
40-
isTransient: false,
41-
...overrides,
42-
});
43-
44-
describe('findReusableEmptySessionId', () => {
45-
afterEach(() => {
46-
resetStore();
47-
});
48-
49-
it('never reuses an existing session', () => {
50-
const workspace = createWorkspace();
51-
const codeSession = createSession({
52-
sessionId: 'code-session',
53-
lastActiveAt: 5,
54-
});
55-
56-
flowChatStore.setState(() => ({
57-
sessions: new Map([[codeSession.sessionId, codeSession]]),
58-
activeSessionId: codeSession.sessionId,
59-
}));
60-
61-
expect(findReusableEmptySessionId(workspace, 'Standard')).toBeNull();
62-
});
63-
});
64-
657
describe('pickPrimaryAssistantWorkspace', () => {
668
const createAssistantWorkspace = (
679
id: string,

‎src/web-ui/src/app/utils/projectSessionWorkspace.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,6 @@
11
import { WorkspaceKind, isRemoteWorkspace, type WorkspaceInfo } from '@/shared/types';
22
import { workspaceManager } from '@/infrastructure/services/business/workspaceManager';
33

4-
/**
5-
* Always create a new session instead of reusing an existing empty one.
6-
*/
7-
export function findReusableEmptySessionId(
8-
_workspace: WorkspaceInfo,
9-
_requestedMode?: string
10-
): string | null {
11-
return null;
12-
}
13-
144
/**
155
* Code / Cowork sessions belong to project (non-assistant) workspaces only.
166
* Assistant “instances” use Claw sessions under their own storage.

‎src/web-ui/src/flow_chat/services/FlowChatManager.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -342,21 +342,23 @@ describe('FlowChatManager initialization', () => {
342342
}
343343
});
344344

345-
it('creates one empty Claw session when reinitializing a reset workspace', async () => {
345+
it('creates one Claw draft when reinitializing a reset workspace', async () => {
346346
storeMocks.store = {
347347
registerPersistUnreadCompletionCallback: vi.fn(),
348348
removeSessionsForWorkspace: vi.fn(() => []),
349349
getState: () => ({ activeSessionId: null, sessions: new Map() }),
350350
};
351351
const manager = FlowChatManager.getInstance();
352352
const initialize = vi.spyOn(manager, 'initialize').mockResolvedValue(false);
353-
const create = vi.spyOn(manager, 'createChatSession').mockResolvedValue('claw-new');
353+
const create = vi.spyOn(manager, 'createChatDraft').mockResolvedValue('claw-new');
354+
const backendCreate = vi.spyOn(manager, 'createChatSession');
354355
const send = vi.spyOn(manager, 'sendMessage');
355356
await manager.resetWorkspaceSessions({ id: 'assistant', rootPath: '/assistants/default', workspaceKind: 'assistant' as any }, {
356357
reinitialize: true, preferredMode: 'Claw',
357358
});
358359
expect(initialize).toHaveBeenCalledWith(expect.objectContaining({ id: 'assistant' }), 'Claw');
359360
expect(create).toHaveBeenCalledExactlyOnceWith({ workspacePath: '/assistants/default', workspaceId: 'assistant' }, 'Claw');
361+
expect(backendCreate).not.toHaveBeenCalled();
360362
expect(send).not.toHaveBeenCalled();
361363
manager.destroy();
362364
});

‎src/web-ui/src/flow_chat/services/FlowChatManager.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ export class FlowChatManager {
625625
return createChatSessionModule(this.context, config, mode);
626626
}
627627

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

829829
if (!hasHistoricalSessions || !hasActiveWorkspaceSession) {
830-
await this.createChatSession(
830+
await this.createChatDraft(
831831
{
832832
workspacePath,
833833
workspaceId: workspace.id,

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -666,9 +666,9 @@ describe('MessageModule session writer conflict', () => {
666666
});
667667

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

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

719-
it('preserves the first turn identity and locked target across an ambiguous acknowledgement', async () => {
720-
const { context, store } = draftContext();
719+
it.each(['Standard', 'Claw'])('preserves the first %s turn identity across an ambiguous acknowledgement', async mode => {
720+
const { context, store } = draftContext(mode);
721721
mockHostQueueSubmit.mockRejectedValueOnce(new Error('Connection lost'));
722722
await expect(sendMessage(context, 'First message', 'draft-first')).rejects.toThrow('Connection lost');
723723
expect(store.getState().sessions.get('draft-first').draft.phase).toBe('submitting');

0 commit comments

Comments
 (0)