From 74d23283e011b433db197a15c9194914f84e65a1 Mon Sep 17 00:00:00 2001 From: wsp Date: Mon, 23 Nov 2026 10:33:00 +0800 Subject: [PATCH] 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. --- .../sections/devices/openOnDevice.test.ts | 1 - .../NavPanel/sections/devices/openOnDevice.ts | 6 +- .../sections/workspaces/WorkspaceItem.tsx | 18 +-- .../app/hooks/useAssistantBootstrap.test.tsx | 1 + .../src/app/hooks/useAssistantBootstrap.ts | 3 + .../app/utils/projectSessionWorkspace.test.ts | 60 +------- .../src/app/utils/projectSessionWorkspace.ts | 10 -- .../services/FlowChatManager.test.ts | 6 +- .../src/flow_chat/services/FlowChatManager.ts | 4 +- .../flow-chat-manager/MessageModule.test.ts | 14 +- .../flow-chat-manager/SessionModule.test.ts | 70 ++++++++- .../flow-chat-manager/SessionModule.ts | 11 ++ .../services/sessionDraftReuse.test.ts | 137 ++++++++++++++++++ .../flow_chat/services/sessionDraftReuse.ts | 59 ++++++++ .../services/sessionDraftService.test.ts | 62 +++++++- .../flow_chat/services/sessionDraftService.ts | 5 +- .../local/LocalSessionDriver.test.ts | 10 +- .../local/LocalSessionDriver.ts | 2 +- .../store/sessionComposerStore.test.ts | 11 ++ .../flow_chat/store/sessionComposerStore.ts | 10 +- .../src/infrastructure/peer-device/README.md | 7 + 21 files changed, 390 insertions(+), 117 deletions(-) create mode 100644 src/web-ui/src/flow_chat/services/sessionDraftReuse.test.ts create mode 100644 src/web-ui/src/flow_chat/services/sessionDraftReuse.ts diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts index b35e5707b5..ee0f53ea73 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts @@ -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 })); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts index 0c00b4d3bd..70f99641ea 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts @@ -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'; @@ -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 }); } diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceItem.tsx b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceItem.tsx index b0c62f029b..8cc8d2af8c 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceItem.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceItem.tsx @@ -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'; @@ -744,10 +741,7 @@ const WorkspaceItem: React.FC = ({ } }, [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') => { @@ -756,14 +750,6 @@ const WorkspaceItem: React.FC = ({ 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 diff --git a/src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx b/src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx index 08b4c8e6c4..9a4970b210 100644 --- a/src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx +++ b/src/web-ui/src/app/hooks/useAssistantBootstrap.test.tsx @@ -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(); }); diff --git a/src/web-ui/src/app/hooks/useAssistantBootstrap.ts b/src/web-ui/src/app/hooks/useAssistantBootstrap.ts index 17c4319a0f..dcd717832e 100644 --- a/src/web-ui/src/app/hooks/useAssistantBootstrap.ts +++ b/src/web-ui/src/app/hooks/useAssistantBootstrap.ts @@ -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. diff --git a/src/web-ui/src/app/utils/projectSessionWorkspace.test.ts b/src/web-ui/src/app/utils/projectSessionWorkspace.test.ts index eecc0b7bc0..b9afe1cc60 100644 --- a/src/web-ui/src/app/utils/projectSessionWorkspace.test.ts +++ b/src/web-ui/src/app/utils/projectSessionWorkspace.test.ts @@ -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 => ({ - 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, diff --git a/src/web-ui/src/app/utils/projectSessionWorkspace.ts b/src/web-ui/src/app/utils/projectSessionWorkspace.ts index 8bb2c99600..acf2bde66e 100644 --- a/src/web-ui/src/app/utils/projectSessionWorkspace.ts +++ b/src/web-ui/src/app/utils/projectSessionWorkspace.ts @@ -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. diff --git a/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts b/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts index 7d3d219e28..55bfa98531 100644 --- a/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts +++ b/src/web-ui/src/flow_chat/services/FlowChatManager.test.ts @@ -342,7 +342,7 @@ 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(() => []), @@ -350,13 +350,15 @@ describe('FlowChatManager initialization', () => { }; 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(); }); diff --git a/src/web-ui/src/flow_chat/services/FlowChatManager.ts b/src/web-ui/src/flow_chat/services/FlowChatManager.ts index c4f836e2ae..3b43b9871e 100644 --- a/src/web-ui/src/flow_chat/services/FlowChatManager.ts +++ b/src/web-ui/src/flow_chat/services/FlowChatManager.ts @@ -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 { return createChatSessionModule(this.context, config, mode, true); } @@ -827,7 +827,7 @@ export class FlowChatManager { sessionBelongsToWorkspaceNavRow(activeSession, workspace.id); if (!hasHistoricalSessions || !hasActiveWorkspaceSession) { - await this.createChatSession( + await this.createChatDraft( { workspacePath, workspaceId: workspace.id, diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts index 3b355349d3..ab9fb75e43 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts @@ -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' }, }]]) }; @@ -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(); @@ -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'); 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 3ae364a4e9..c3022a1985 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 @@ -64,6 +64,7 @@ const persistenceMocks = vi.hoisted(() => ({ const stateMachineMocks = vi.hoisted(() => ({ delete: vi.fn(), + getCurrentState: vi.fn(() => 'idle'), })); const dispatchStoreMocks = vi.hoisted(() => ({ @@ -127,6 +128,7 @@ vi.mock('./TextChunkModule', () => ({ vi.mock('../../state-machine', () => ({ stateMachineManager: stateMachineMocks, + SessionExecutionState: { IDLE: 'idle' }, })); vi.mock('@/features/dispatch/dispatchJobStore', () => ({ @@ -210,6 +212,8 @@ function createContext( workspacePath?: string, remoteConnectionId?: string, remoteSshHost?: string, + _titleDescriptor?: unknown, + draft?: Session['draft'], ) => { const nextSession = createSession({ sessionId, @@ -217,8 +221,11 @@ function createContext( 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, @@ -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(); } @@ -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 }>(); 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 16c88b7695..4d066f2f96 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 @@ -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, @@ -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); @@ -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), ); diff --git a/src/web-ui/src/flow_chat/services/sessionDraftReuse.test.ts b/src/web-ui/src/flow_chat/services/sessionDraftReuse.test.ts new file mode 100644 index 0000000000..e59cc9a6c9 --- /dev/null +++ b/src/web-ui/src/flow_chat/services/sessionDraftReuse.test.ts @@ -0,0 +1,137 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ContextItem } from '@/shared/types/context'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; +import { SessionExecutionState, stateMachineManager } from '../state-machine'; +import { beginComposerSubmission, sessionComposerStore } from '../store/sessionComposerStore'; +import type { FlowChatState, Session, SessionConfig } from '../types/flow-chat'; +import { pendingQueueManager } from './flow-chat-manager/PendingQueueModule'; +import { findReusableSessionDraft } from './sessionDraftReuse'; + +function session(overrides: Partial = {}): Session { + return { + sessionId: 'draft', workspaceId: 'workspace', workspacePath: '/repo', + mode: 'Standard', config: {}, dialogTurns: [], status: 'idle', error: null, + createdAt: 1, lastActiveAt: 1, historyState: 'new', sessionKind: 'normal', + draft: { workspaceId: 'workspace', phase: 'editing', turnId: 'first' }, + ...overrides, + }; +} + +function find(sessions: Session[], activeSessionId: string | null = null, config: SessionConfig = {}, mode = 'Standard') { + const state: FlowChatState = { + sessions: new Map(sessions.map(value => [value.sessionId, value])), activeSessionId, + }; + return findReusableSessionDraft(state, 'workspace', mode, config); +} + +beforeEach(() => { + resetDeviceSurfaceForTest(); + sessionComposerStore.setState({ drafts: {} }); +}); +afterEach(() => { + vi.restoreAllMocks(); + pendingQueueManager.clearSurface('local'); + pendingQueueManager.clearSurface('peer'); + resetDeviceSurfaceForTest(); +}); + +describe('blank conversation reuse', () => { + it('prefers the active blank draft, then the most recently active one', () => { + const older = session({ sessionId: 'older' }); + const newer = session({ sessionId: 'newer', lastActiveAt: 20 }); + expect(find([older, newer], older.sessionId)).toBe('older'); + expect(find([older, newer], 'unrelated')).toBe('newer'); + }); + + it.each(['Standard', 'Claw'])('reuses only the exact requested %s mode', mode => { + const draft = session({ mode }); + expect(find([draft], null, {}, mode)).toBe('draft'); + expect(find([draft], null, {}, 'Cowork')).toBeNull(); + }); + + it('uses workspace IDs even when two SSH hosts share the same path', () => { + expect(find([session({ workspaceId: 'other-host', remoteConnectionId: 'ssh-b' })])).toBeNull(); + expect(find([session({ workspaceId: undefined, workspacePath: '/repo' })])).toBeNull(); + expect(find([session({ remoteConnectionId: 'ssh-a' })], null, { + workspaceId: 'workspace', workspacePath: '/repo', remoteConnectionId: 'ssh-a', + })).toBe('draft'); + }); + + it('does not select a draft whose composer now targets another directory', () => { + expect(find([session({ draft: { workspaceId: 'other', phase: 'editing', turnId: 'first' } })])).toBeNull(); + }); + + it.each([ + { value: 'unfinished request' }, + { contexts: [{ id: 'file', type: 'file' } as ContextItem] }, + { pendingLargePastes: { placeholder: 'full text' } }, + ])('preserves occupied composers: %j', contents => { + sessionComposerStore.setState({ drafts: { + '["local","draft"]': { value: '', contexts: [], pendingLargePastes: {}, updatedAt: 1, ...contents }, + } }); + expect(find([session()])).toBeNull(); + }); + + it('reuses an untouched assistant bootstrap prefill, but preserves user edits', () => { + const composer = sessionComposerStore.getState(); + const claw = session({ mode: 'Claw' }); + composer.setPrefill('draft', 'Initialize my assistant', 'assistant-bootstrap', 'local'); + expect(find([claw], null, {}, 'Claw')).toBe('draft'); + composer.setValue('draft', 'Initialize my assistant with my own instructions'); + expect(find([claw], null, {}, 'Claw')).toBeNull(); + }); + + it('checks composer occupancy on the selected device only', () => { + sessionComposerStore.getState().setValue('draft', 'Local content'); + expect(find([session()])).toBeNull(); + activateSurface('peer'); + expect(find([session()])).toBe('draft'); + sessionComposerStore.getState().setValue('draft', 'Peer content'); + activateSurface('local'); + expect(sessionComposerStore.getState().getDraft('draft').value).toBe('Local content'); + }); + + it('does not reuse a cleared composer while attachments are being submitted', () => { + const finish = beginComposerSubmission('draft', 'local'); + try { expect(find([session()])).toBeNull(); } finally { finish(); } + expect(find([session()])).toBe('draft'); + }); + + it('preserves queued messages and running state even before a projected turn appears', () => { + pendingQueueManager.enqueue({ sessionId: 'draft', content: 'Waiting' }); + expect(find([session()])).toBeNull(); + pendingQueueManager.clear('draft'); + vi.spyOn(stateMachineManager, 'getCurrentState').mockReturnValue(SessionExecutionState.PROCESSING); + expect(find([session()])).toBeNull(); + }); + + it.each>([ + { draft: undefined, isHistorical: true, historyState: 'metadata-only' }, + { historyState: 'hydrating' }, + { historyState: 'failed' }, + { persistedTurnCount: 2 }, + { totalTurnCount: 2, isPartial: true }, + { lastSubmittedMode: 'Standard' }, + { sessionKind: 'subagent', parentSessionId: 'parent' }, + { isTransient: true }, + { externalHistory: { mode: 'follow' } }, + { mode: 'acp:client', config: { agentType: 'acp:client' } }, + { config: { dispatchJobId: 'job' } }, + ])('does not treat existing or special sessions as blank drafts: %j', overrides => { + expect(find([session(overrides)], null, {}, overrides.mode ?? 'Standard')).toBeNull(); + }); + + it.each(['creating', 'ready', 'submitting'] as const)('keeps a %s draft on its own recovery path', phase => { + expect(find([session({ draft: { workspaceId: 'workspace', phase, turnId: 'first' } })])).toBeNull(); + }); + + it('honors explicit model, reasoning and context choices', () => { + const config = { modelName: 'chosen', reasoningPreset: 'high', context: { key: 'value' } }; + const draft = session({ config }); + expect(find([draft], null, config)).toBe('draft'); + expect(find([draft], null, { modelName: 'other' })).toBeNull(); + expect(find([draft], null, { reasoningPreset: 'low' })).toBeNull(); + expect(find([draft], null, { context: { key: 'other' } })).toBeNull(); + expect(find([draft], null, { executionTargetRequest: { kind: 'local' } })).toBeNull(); + }); +}); diff --git a/src/web-ui/src/flow_chat/services/sessionDraftReuse.ts b/src/web-ui/src/flow_chat/services/sessionDraftReuse.ts new file mode 100644 index 0000000000..af53503727 --- /dev/null +++ b/src/web-ui/src/flow_chat/services/sessionDraftReuse.ts @@ -0,0 +1,59 @@ +import { getActiveSurfaceId } from '@/infrastructure/peer-device/deviceSurface'; +import { SessionExecutionState, stateMachineManager } from '../state-machine'; +import { isComposerSubmissionPending, sessionComposerStore } from '../store/sessionComposerStore'; +import type { FlowChatState, Session, SessionConfig } from '../types/flow-chat'; +import { isAcpFlowSession } from '../utils/acpSession'; +import { isSessionBindingLocked } from '../utils/sessionLifecycle'; +import { sessionOwningWorkspaceId } from '../utils/sessionOrdering'; +import { pendingQueueManager } from './flow-chat-manager/PendingQueueModule'; + +// Paths are execution projections; identity is the captured device's workspace ID. +const WORKSPACE_CONFIG_KEYS = new Set([ + 'workspaceId', 'workspacePath', 'projectWorkspaceId', 'projectWorkspacePath', + 'remoteConnectionId', 'remoteSshHost', 'agentType', +]); + +/** Only controller-owned, unsubmitted drafts are proof of an empty conversation. */ +export function findReusableSessionDraft( + state: FlowChatState, + workspaceId: string, + mode: string, + config: SessionConfig, +): string | null { + if (config.executionTargetRequest || config.dispatchTargetRequest + || config.dispatchTarget || config.dispatchJobId) return null; + + const surfaceId = getActiveSurfaceId(); + const reusable = (session: Session): boolean => { + if (session.draft?.phase !== 'editing' || session.draft.workspaceId !== workspaceId + || sessionOwningWorkspaceId(session) !== workspaceId || session.mode !== mode + || isSessionBindingLocked(session) || session.dialogTurns.length > 0 + || session.persistedTurnCount || session.isPartial + || session.sessionKind !== 'normal' || session.parentSessionId || session.isTransient + || session.agentBackedTransient || session.btwThreads?.length || session.externalHistory + || isAcpFlowSession(session) || session.error || session.persistedStatus === 'archived' + || session.config.executionTarget || session.config.executionTargetRequest + || session.config.dispatchTargetRequest || session.config.dispatchTarget || session.config.dispatchJobId) { + return false; + } + // Explicit caller choices must never be lost by selecting a different draft. + if (Object.entries(config).some(([key, value]) => value !== undefined + && !WORKSPACE_CONFIG_KEYS.has(key) + && JSON.stringify(session.config[key as keyof SessionConfig]) !== JSON.stringify(value))) return false; + const composer = sessionComposerStore.getState().getDraft(session.sessionId, surfaceId); + if ((composer.value.trim() && composer.prefillSource !== 'assistant-bootstrap') + || composer.contexts.length || Object.keys(composer.pendingLargePastes).length + || isComposerSubmissionPending(session.sessionId, surfaceId) + || pendingQueueManager.list(session.sessionId).length + || stateMachineManager.getCurrentState(session.sessionId) !== SessionExecutionState.IDLE) return false; + return true; + }; + + const active = state.activeSessionId ? state.sessions.get(state.activeSessionId) : undefined; + if (active && reusable(active)) return active.sessionId; + let latest: Session | undefined; + for (const session of state.sessions.values()) { + if (reusable(session) && (!latest || session.lastActiveAt > latest.lastActiveAt)) latest = session; + } + return latest?.sessionId ?? null; +} diff --git a/src/web-ui/src/flow_chat/services/sessionDraftService.test.ts b/src/web-ui/src/flow_chat/services/sessionDraftService.test.ts index bde83399b5..96dd513774 100644 --- a/src/web-ui/src/flow_chat/services/sessionDraftService.test.ts +++ b/src/web-ui/src/flow_chat/services/sessionDraftService.test.ts @@ -1,4 +1,5 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; import type { WorkspaceInfo } from '@/shared/types'; import type { Session } from '../types/flow-chat'; import type { FlowChatContext } from './flow-chat-manager/types'; @@ -9,14 +10,14 @@ import { shouldSyncSessionModelSelection } from '../utils/modelSelectionTarget'; import { chatInputSessionSubscriptionKey } from '../utils/chatInputSessionSubscription'; const ports = vi.hoisted(() => ({ create: vi.fn(), metadata: vi.fn(), permission: vi.fn(), routing: vi.fn(), model: vi.fn(), - workspaces: new Map() })); + workspaces: new Map(), assistants: [] as WorkspaceInfo[] })); vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: { createSession: ports.create, updateSessionPermissionMode: ports.permission, getModelRoutingStatus: ports.routing, updateSessionModel: ports.model, } })); vi.mock('@/infrastructure/api/service-api/SessionAPI', () => ({ sessionAPI: { loadSessionMetadata: ports.metadata } })); vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ workspaceManager: { - getState: () => ({ openedWorkspaces: ports.workspaces, recentWorkspaces: [] }), + getState: () => ({ openedWorkspaces: ports.workspaces, recentWorkspaces: [], assistantWorkspaces: ports.assistants }), } })); vi.mock('./sessionTitleMetadata', () => ({ initializeSessionTitleMetadata: vi.fn() })); vi.mock('@/infrastructure/i18n', () => ({ i18nService: { t: (key: string) => key } })); @@ -36,7 +37,9 @@ function harness(overrides: Partial = {}) { } beforeEach(() => { + resetDeviceSurfaceForTest(); vi.clearAllMocks(); + ports.assistants.length = 0; ports.workspaces.clear(); for (const id of ['a', 'b', 'c']) ports.workspaces.set(id, { id, rootPath: `/${id}`, workspaceKind: 'normal' } as WorkspaceInfo); ports.create.mockImplementation(async request => ({ ...request, modelId: request.config.modelName })); @@ -45,8 +48,61 @@ beforeEach(() => { ports.routing.mockResolvedValue({ apiVersion: 1, available: true }); ports.model.mockResolvedValue(undefined); }); +afterEach(() => resetDeviceSurfaceForTest()); describe('new conversation workspace ownership', () => { + it('materializes a Claw draft with its reserved identity and keeps its assistant workspace fixed', async () => { + const assistant = { id: 'a', rootPath: '/assistants/a', workspaceKind: 'assistant' } as WorkspaceInfo; + ports.workspaces.set('a', assistant); + const h = harness({ mode: 'Claw', config: { modelName: 'chosen', reasoningPreset: 'high' }, + draft: { workspaceId: 'a', phase: 'editing', turnId: 'first-turn', permissionMode: 'auto' } }); + expect(canSelectSessionWorkspace(h.read())).toBe(false); + expect(() => selectDraftWorkspace(h.context, 'reserved', 'b')).toThrow('locked'); + expect(ports.create).not.toHaveBeenCalled(); + await materializeSessionDraft(h.context, 'reserved'); + expect(ports.create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + sessionId: 'reserved', requestId: 'reserved', agentType: 'Claw', workspaceId: 'a', + workspacePath: '/assistants/a', config: expect.objectContaining({ modelName: 'chosen', reasoningPreset: 'high' }), + })); + expect(ports.permission).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'reserved', workspaceId: 'a', mode: 'auto' })); + expect(h.read().draft).toMatchObject({ phase: 'ready', turnId: 'first-turn' }); + await materializeSessionDraft(h.context, 'reserved'); + expect(ports.create).toHaveBeenCalledOnce(); + }); + + it('can materialize a known assistant opened from its catalog before workspace activation finishes', async () => { + ports.workspaces.delete('a'); + ports.assistants.push({ id: 'a', rootPath: '/assistants/a', workspaceKind: 'assistant' } as WorkspaceInfo); + const h = harness({ mode: 'Claw' }); + expect(canSelectSessionWorkspace(h.read())).toBe(false); + await materializeSessionDraft(h.context, 'reserved'); + expect(ports.create).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: 'a', workspacePath: '/assistants/a' })); + }); + + it('recovers Claw creation from an existing host record after a lost reply', async () => { + const h = harness({ mode: 'Claw' }); + ports.create.mockRejectedValueOnce(new Error('Reply lost')); + await expect(materializeSessionDraft(h.context, 'reserved')).rejects.toThrow('Reply lost'); + ports.metadata.mockResolvedValueOnce({ sessionId: 'reserved', workspaceId: 'a', + sessionName: 'New', agentType: 'Claw', modelName: 'model' }); + await materializeSessionDraft(h.context, 'reserved'); + expect(ports.create).toHaveBeenCalledOnce(); + expect(h.read().mode).toBe('Claw'); + expect(h.read().draft?.phase).toBe('ready'); + }); + + it('rejects a late Claw create reply after switching devices', async () => { + let finish!: (value: object) => void; + ports.create.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })); + const h = harness({ mode: 'Claw' }); + const creating = materializeSessionDraft(h.context, 'reserved'); + activateSurface('peer'); + finish({ sessionId: 'reserved', workspaceId: 'a' }); + await expect(creating).rejects.toMatchObject({ isSurfaceChangedError: true }); + expect(h.read().draft?.phase).toBe('creating'); + expect(ports.permission).not.toHaveBeenCalled(); + }); + it('changes the draft target without navigating or creating anything; only first send binds the target', async () => { const h = harness(); const before = chatInputSessionSubscriptionKey(h.read()); diff --git a/src/web-ui/src/flow_chat/services/sessionDraftService.ts b/src/web-ui/src/flow_chat/services/sessionDraftService.ts index 8c7fdd653a..2311a9892f 100644 --- a/src/web-ui/src/flow_chat/services/sessionDraftService.ts +++ b/src/web-ui/src/flow_chat/services/sessionDraftService.ts @@ -48,11 +48,14 @@ export async function prepareSessionDraftForCommand(session: Session): Promise workspace.id === id); } export function canSelectSessionWorkspace(session: Session | undefined, submitting = false): boolean { return !!session && !!session.draft && session.draft.phase === 'editing' + && draftWorkspace(session)?.workspaceKind !== WorkspaceKind.Assistant && !isSessionBindingLocked(session, submitting) && !session.parentSessionId && !session.isTransient && !session.config.dispatchTarget && !session.config.dispatchJobId; diff --git a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.test.ts b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.test.ts index 68ffd0d028..49e02344a5 100644 --- a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.test.ts +++ b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.test.ts @@ -101,10 +101,10 @@ describe('localSessionDriver conversation creation', () => { }; } - it('reserves a frontend conversation without creating a host session', async () => { + it.each(['Standard', 'Claw'])('reserves a frontend %s conversation without creating a host session', async agentType => { const createSession = vi.fn(); const context = { flowChatStore: { createSession } } as any; - await expect(localSessionDriver.createSession(context, seed())).resolves.toBe('reserved-session'); + await expect(localSessionDriver.createSession(context, seed(agentType))).resolves.toBe('reserved-session'); expect(mockCreateSession).not.toHaveBeenCalled(); expect(createSession).toHaveBeenCalledTimes(1); expect(createSession.mock.calls[0][0]).toBe('reserved-session'); @@ -157,7 +157,7 @@ describe('localSessionDriver conversation creation', () => { const createSession = vi.fn(); await expect(localSessionDriver.createSession( { flowChatStore: { createSession } } as any, - { ...seed('Claw'), titleDescriptor: descriptor }, + { ...seed('Claw'), draftId: undefined, titleDescriptor: descriptor }, )).resolves.toBe('host-session'); expect(createSession).toHaveBeenCalledTimes(1); expect(createSession.mock.calls[0].at(-1)).toBe(descriptor); @@ -184,10 +184,10 @@ describe('localSessionDriver conversation creation', () => { expect(mockCreateSession).not.toHaveBeenCalled(); }); - it('keeps assistant bootstrap on the existing immediate creation path', async () => { + it('keeps explicit backend assistant creation available for non-composer workflows', async () => { const createSession = vi.fn(); const context = { flowChatStore: { createSession } } as any; - await expect(localSessionDriver.createSession(context, seed('Claw'))).resolves.toBe('host-session'); + await expect(localSessionDriver.createSession(context, { ...seed('Claw'), draftId: undefined })).resolves.toBe('host-session'); expect(mockCreateSession).toHaveBeenCalledWith(expect.objectContaining({ agentType: 'Claw', workspaceId: 'project', workspacePath: WORKSPACE_PATH, })); diff --git a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts index 6b83564dd7..ad49619daa 100644 --- a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts +++ b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts @@ -184,7 +184,7 @@ export const localSessionDriver: SessionDriver = { : resolveReasoningPresetForSessionCreation(explicitModelName) ); - if (seed.draftId && agentType !== 'Claw' && !config.executionTargetRequest) { + if (seed.draftId && !config.executionTargetRequest) { if (!workspaceId) throw new Error('Draft workspace ID is unavailable'); // Both reads only depend on the model already resolved above. const [reasoningPreset, maxContextTokens] = await Promise.all([ diff --git a/src/web-ui/src/flow_chat/store/sessionComposerStore.test.ts b/src/web-ui/src/flow_chat/store/sessionComposerStore.test.ts index 4eeb7f2fc0..8c19049181 100644 --- a/src/web-ui/src/flow_chat/store/sessionComposerStore.test.ts +++ b/src/web-ui/src/flow_chat/store/sessionComposerStore.test.ts @@ -54,6 +54,17 @@ describe('sessionComposerStore', () => { expect(sessionComposerStore.getState().getDraft('session-b').value).toBe('draft b'); }); + it('keeps bootstrap ownership on restoration and clears it when text is edited', () => { + const store = sessionComposerStore.getState(); + store.setPrefill('assistant', 'Initialize', 'assistant-bootstrap', LOCAL_SURFACE_ID); + store.setValue('assistant', 'Initialize'); + expect(store.getDraft('assistant').prefillSource).toBe('assistant-bootstrap'); + store.setValue('assistant', 'My own prompt'); + expect(store.getDraft('assistant').prefillSource).toBeUndefined(); + store.setValue('assistant', 'Initialize'); + expect(store.getDraft('assistant').prefillSource).toBeUndefined(); + }); + it('saves the previous contexts and restores the complete next draft on activation', () => { const store = sessionComposerStore.getState(); store.setValue('session-a', 'draft a'); diff --git a/src/web-ui/src/flow_chat/store/sessionComposerStore.ts b/src/web-ui/src/flow_chat/store/sessionComposerStore.ts index 874232676d..ddf247605c 100644 --- a/src/web-ui/src/flow_chat/store/sessionComposerStore.ts +++ b/src/web-ui/src/flow_chat/store/sessionComposerStore.ts @@ -8,7 +8,7 @@ import { } from '@/infrastructure/peer-device/deviceSurface'; export type PendingLargePasteMap = Record; -type ComposerPrefillSource = 'skin-design'; +type ComposerPrefillSource = 'skin-design' | 'assistant-bootstrap'; export interface SessionComposerDraft { value: string; @@ -110,7 +110,13 @@ export const useSessionComposerStore = create((set, get) = }, setValue: (sessionId, value, surfaceId) => { - set(state => updateDraft(state, sessionId, { value }, surfaceId)); + set(state => { + const current = state.drafts[draftKey(sessionId, surfaceId)]; + // Passive restoration keeps the template marker; editing makes it user content. + const prefillSource = current?.prefillSource === 'assistant-bootstrap' && current.value !== value + ? undefined : current?.prefillSource; + return updateDraft(state, sessionId, { value, prefillSource }, surfaceId); + }); }, setPrefill: (sessionId, value, prefillSource, surfaceId) => { diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index 88fe2653d0..56892a2b45 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -14,6 +14,13 @@ never seen, so it opens no subscription and reads no history; a host rejection there would falsely lock an empty session as a failed restore. The subscription starts when the host accepts the draft. +Opening a blank conversation in the UI, including Claw, reserves a frontend draft. +Creation reuses a blank, unsubmitted draft on the rendered device after resolving +the workspace's actual mode. User text, attachments, pending submissions and +recovery states prevent reuse; an untouched assistant bootstrap prefill is kept. +An explicit command such as setting an assistant's default session may materialize +the draft before the first message so its persisted pointer addresses a host record. + `RelaySessionHistory` owns one subscription per visible surface/session. `SessionRecordReplica` applies both replayed pages and live canonical records using stable IDs, revisions and tombstones; every page comes from the online