import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition' import { IDENTITY_ICON_IDS } from '@/lib/identity-icons' import { viewBuildDirectives } from '@/lib/view-build-directives' import { viewIdFromTab, viewTabId } from '@/lib/workspace-tabs' import type { PendingView, SelectedSessionScope, WorkspaceEntry, WorkspaceTabId } from '@/lib/types' import { getCollabReferencePath } from '../collab/config' import { harnessFor } from '../harness/registry' import type { SendMessageInput } from '../harness/types' import { ForkUnsupportedError, inheritedHistoryBoundary } from '../harness/fork' import { updateWorkspaceState } from '../workspace-state' import { getPinnedSession, saveSelectedSession, resolveRenamedSession, selectSessionForTab } from './selected' import { getSessionEntry, setSessionTab, updateSessionEntry } from './store' import { getSessionConfig, saveSessionConfig } from './config' import { createPendingView, getPendingView, listPendingViews, patchPendingView, PendingViewError, startViewBuild } from './pending-views' export class ViewStartupError extends Error { constructor( error: unknown, public sessionId?: string, public viewId?: string ) { super(error instanceof Error ? error.message : 'Couldn’t start view chat') } } type BuildSendOptions = Pick< SendMessageInput, 'attachments' | 'optimisticId' | 'model' | 'effort' | 'speedMode' | 'stream' > & { selectedSessionScope?: SelectedSessionScope } export type SubmitViewInput = BuildSendOptions & { requirements: string; sessionId?: string } // Both ordinary chat and initial build requests use this boundary. export async function sendWorkspaceMessage( ws: WorkspaceEntry, input: SendMessageInput & { selectedSessionScope?: SelectedSessionScope; viewBuildId?: string } ) { const release = reserveWorkspaceOperation(ws.id) try { const { getWorkspace } = await import('../workspaces/registry') const current = await getWorkspace(ws.id) if (current && (current.type ?? 'claude-code') !== (ws.type ?? 'claude-code')) throw new HarnessTransitionError('Agent changed. Start a new chat') const { prepareWorkspaceHarness } = await import('../workspaces/change-harness') await prepareWorkspaceHarness(ws) const { selectedSessionScope, viewBuildId, ...message } = input const sessionId = resolveRenamedSession(ws.id, input.sessionId) const record = await getSessionEntry(ws, sessionId) const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview' const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined) const ownedViews = targetViewId ? [] : (await listPendingViews(ws)).filter(view => view.buildSessionId === sessionId) const pending = targetViewId ? await getPendingView(ws, targetViewId) : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0]) const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew) if ( isBuildRequest && pending.buildSessionId && pending.buildSessionId !== sessionId && (pending.status === 'starting' || harnessFor(ws) .activeSessions() .some( session => session.workspaceId === ws.id && session.sessionId === pending.buildSessionId )) ) throw new PendingViewError('This view is already being built in another chat', 409) if (input.isNew && record.tabId !== tabId) { record.tabId = tabId === 'overview' ? undefined : tabId await attachSession(ws, tabId, sessionId, null, selectedSessionScope) } if (isBuildRequest) await patchPendingView(ws, pending.id, { buildSessionId: sessionId }) const collabReference = await getCollabReferencePath(ws.path, ws.type) const pinnedSessionId = await getPinnedSession(ws) await harnessFor(ws).sendMessage({ ...message, sessionId, context: { ...input.context, session: { id: sessionId, tabId: record.tabId, pinned: pinnedSessionId === sessionId }, ...(collabReference ? { collabReference } : {}), directives: [ ...(input.context?.directives ?? []), ...(isBuildRequest ? viewBuildDirectives(pending.id, IDENTITY_ICON_IDS) : []), ...(isBuildRequest && record.fork ? [ 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.' ] : []), ...(pending && input.isNew && pending.requirements !== input.content ? [`Original view requirements:\n${pending.requirements}`] : []), ...(pending && input.attachments?.length ? ['Use the attachments as reference material for the intended view.'] : []) ] } }) if (pending && pending.status !== 'starting') await patchPendingView(ws, pending.id, { status: 'submitted', error: undefined }) } finally { release() } } async function attachSession( ws: WorkspaceEntry, tabId: WorkspaceTabId, sessionId: string, ifMatch?: string | null, selectedSessionScope: SelectedSessionScope = 'shared' ) { await updateSessionEntry(ws, sessionId, { tabId: tabId === 'overview' ? undefined : tabId }) if (selectedSessionScope === 'shared') await saveSelectedSession(ws, sessionId, tabId, ifMatch) } async function sendBuild( ws: WorkspaceEntry, view: PendingView, sessionId: string, isNew: boolean, options: BuildSendOptions ) { await sendWorkspaceMessage(ws, { ...options, workspaceId: ws.id, workspacePath: ws.path, agentId: ws.agentId, sessionId, isNew, viewBuildId: view.id, content: view.requirements }) await patchPendingView(ws, view.id, { status: 'submitted' }, 'starting') } async function failStartup( ws: WorkspaceEntry, error: unknown, sessionId?: string, view?: PendingView ): Promise { if (view) await patchPendingView( ws, view.id, { status: 'failed', error: error instanceof Error ? error.message : 'Couldn’t start view chat' }, 'starting' ) throw new ViewStartupError( error, sessionId ? resolveRenamedSession(ws.id, sessionId) : undefined, view?.id ) } export async function submitView(ws: WorkspaceEntry, viewId: string, input: SubmitViewInput) { const tabId = viewTabId(viewId) const shared = (input.selectedSessionScope ?? 'shared') === 'shared' // The build, the chat's tab and the tab's selection start in one write. A // pinned chat takes the build and keeps its own tab. const { view, sessionId, pinned } = await updateWorkspaceState(ws, state => { const pinned = state.pinnedSessionId const sessionId = pinned ?? input.sessionId ?? crypto.randomUUID() const view = startViewBuild( state, viewId, input.requirements, sessionId, !!input.attachments?.length ) if (!pinned) { setSessionTab(state, sessionId, tabId) if (shared) selectSessionForTab(state, ws.id, sessionId, tabId) } return { view, sessionId, pinned } }) try { await sendBuild(ws, view, sessionId, !pinned, input) } catch (error) { return failStartup(ws, error, sessionId, view) } return { viewId, sessionId: resolveRenamedSession(ws.id, sessionId) } } export async function createViewFromSession( ws: WorkspaceEntry, fromSessionId: string | undefined, requirements: string ) { if (!requirements.trim()) throw new Error('View requirements are required') if (fromSessionId === undefined) { const view = await createPendingView(ws, { requirements: requirements.trim(), status: 'submitted' }) return { viewId: view.id, mode: 'in-place' as const, buildInstructions: viewBuildDirectives(view.id, IDENTITY_ICON_IDS) } } if (!fromSessionId) throw new Error('Session id cannot be empty') fromSessionId = resolveRenamedSession(ws.id, fromSessionId) const harness = harnessFor(ws) if ( !(await harness.listSessions(ws)).some(session => session.sessionId === fromSessionId) && !harness .activeSessions() .some(session => session.workspaceId === ws.id && session.sessionId === fromSessionId) ) throw new Error('Source chat not found') let sessionId: string | undefined let view: PendingView | undefined try { const sourceConfig = await getSessionConfig(ws, fromSessionId) try { sessionId = await harness.forkSession?.(ws, fromSessionId, sourceConfig) } catch (error) { if (!(error instanceof ForkUnsupportedError)) throw error } const isNew = !sessionId sessionId ??= crypto.randomUUID() if (!isNew) { await updateSessionEntry(ws, sessionId, { fork: { fromSessionId } }) // The fork API returns only a child ID. A failed history read leaves the // child usable and its full transcript visible. const history = await harness.sessionEvents(ws, sessionId).catch(() => undefined) if (history) await updateSessionEntry(ws, sessionId, { fork: { fromSessionId, ...inheritedHistoryBoundary(history) } }) } const config = await saveSessionConfig(ws, sessionId, sourceConfig) view = await createPendingView(ws, { status: 'starting', requirements: requirements.trim(), buildSessionId: sessionId }) await attachSession(ws, viewTabId(view.id), sessionId) await sendBuild(ws, view, sessionId, isNew, config) return { viewId: view.id, mode: 'handoff' as const, sessionId: resolveRenamedSession(ws.id, sessionId) } } catch (error) { return failStartup(ws, error, sessionId, view) } } export async function failInterruptedViewStarts(ws: WorkspaceEntry) { for (const view of await listPendingViews(ws)) { if (view.status === 'starting') await patchPendingView( ws, view.id, { status: 'failed', error: 'View chat startup was interrupted. Check the chat before continuing; it has not been retried.' }, 'starting' ) } }