feat: home and empty ai sessions share one session composer

This commit is contained in:
Guilhem Lemouel
2026-10-15 08:15:33 -07:00
parent 7ba3d2b0e0
commit d32f1ea335
29 changed files with 1135 additions and 680 deletions
+25
View File
@@ -426,3 +426,28 @@ input[type='time']::-webkit-calendar-picker-indicator {
.svelte-flow__edges {
z-index: -10;
}
/* The composer's glide, defined once: the Home ↔ AI Sessions view transition below and the
in-page move on a session's first message (composerGlide.svelte.ts) both read it. */
:root {
--composer-glide-duration: 200ms;
--composer-glide-easing: cubic-bezier(0.2, 0, 0, 1);
}
/* Home ↔ AI Sessions (homeSessionsTransition.svelte.ts). The session heading and composer
glide from where they were to where they land; everything else, Home's list included, is
the page cross-fading, kept short. The pseudo-elements hang off :root itself, so no space
before `::view-transition-*`: with one, the selector looks for a descendant and never
matches. */
:root[data-home-sessions-transition]::view-transition-group(session-heading),
:root[data-home-sessions-transition]::view-transition-group(session-composer) {
animation-duration: var(--composer-glide-duration);
animation-timing-function: var(--composer-glide-easing);
}
:root[data-home-sessions-transition]::view-transition-old(root),
:root[data-home-sessions-transition]::view-transition-new(root) {
animation-duration: 150ms;
}
:root[data-home-sessions-transition='fade'] * {
view-transition-name: none !important;
}
@@ -18,7 +18,9 @@
forceDisabledMessage = '',
wideLayout = false,
emptyHint,
starterPrompts = undefined,
starter = undefined,
viewTransitionNames = false,
onSent = undefined,
inputPreface,
initialInstructions = undefined,
onDraftChange = undefined
@@ -36,7 +38,9 @@
// in; the narrow global-chat panel leaves it off.
wideLayout?: boolean
emptyHint?: import('svelte').Snippet
starterPrompts?: import('$lib/onboardingProfile').StarterPrompt[]
starter?: import('./starter/starterPrompts.svelte').ChatStarter
viewTransitionNames?: boolean
onSent?: () => void
inputPreface?: import('svelte').Snippet
// Seed / observe the composer's draft text (forwarded to AIChatDisplay).
initialInstructions?: string
@@ -200,7 +204,9 @@
{hideModeSelector}
{wideLayout}
{emptyHint}
{starterPrompts}
{starter}
{viewTransitionNames}
{onSent}
{inputPreface}
{initialInstructions}
{onDraftChange}
@@ -68,9 +68,10 @@
import { sendUserToast } from '$lib/toast'
import Alert from '$lib/components/common/alert/Alert.svelte'
import { copilotInfo } from '$lib/aiStore'
import type { StarterPrompt } from '$lib/onboardingProfile'
import BuildWithAIHeading from './starter/BuildWithAIHeading.svelte'
import { RotatingPlaceholder } from './starter/starterPrompts.svelte'
import SessionGreeting from './starter/SessionGreeting.svelte'
import StarterPromptChips from './starter/StarterPromptChips.svelte'
import { RotatingPlaceholder, type ChatStarter } from './starter/starterPrompts.svelte'
import { glideOnLayoutChange } from './composerGlide.svelte'
const MAX_YOLO_TOOLTIP_TOOLS = 8
const chatHost = getChatViewHost()
@@ -109,7 +110,9 @@
hideModeSelector = false,
wideLayout = false,
emptyHint,
starterPrompts = undefined,
starter = undefined,
viewTransitionNames = false,
onSent = undefined,
inputPreface,
footerSettings,
initialInstructions = undefined,
@@ -142,10 +145,17 @@
// off there.
wideLayout?: boolean
emptyHint?: Snippet
/** Open an empty chat the way Home's composer looks: the "Build with AI" heading, a
* taller box cycling through these prompts as its placeholder. Sessions
* set it so the two read as the same entry point. Replaces `emptyHint`. */
starterPrompts?: StarterPrompt[]
/** Open an empty chat as the block that starts a session: Home and an empty session
* both mount it, so the two are one entry point rather than look-alikes. Replaces
* `emptyHint`. */
starter?: ChatStarter
/** Names the block for the view transition between Home and AI Sessions. Only one
* chat on the page may carry the names: a duplicate makes the browser skip the
* transition. Named only while the chat is empty: the glide carries Home's draft to
* the same draft's page and back, and a session already under way just cross-fades. */
viewTransitionNames?: boolean
/** After the composer hands a new turn to the host. */
onSent?: () => void
inputPreface?: Snippet
/** The settings control at the footer's right edge, where the copilot puts its
* model picker. A host that configures its turn elsewhere replaces it here. */
@@ -293,13 +303,10 @@
}
$effect(() => {
if (aiChatInput) {
chatHost.setAiChatInput(aiChatInput)
}
return () => {
chatHost.setAiChatInput(null)
}
const input = aiChatInput
if (!input) return
chatHost.setAiChatInput(input)
return () => chatHost.releaseAiChatInput(input)
})
// Also shown for a run held by another tab, labeled with where it is: the
@@ -560,11 +567,21 @@
// A step name hangs its icon in the column's left padding (see AssistantMessage), so a
// transcript carrying one widens the padding, on both sides to keep the column centred.
const agentGutter = $derived(messages.some((m) => m.role === 'assistant' && m.stepName))
const starterHero = $derived(!!starterPrompts && messages.length === 0 && !disabled)
// The block's layout holds while the chat is empty, usable or not; only the rotating
// placeholder, the taller box and the prompts need a composer that can send.
const starterLayout = $derived(!!starter && messages.length === 0)
const starterHero = $derived(starterLayout && !disabled)
// Home is a page, not a pane: nothing there to centre in.
const centreComposer = $derived(starterLayout && starter?.where === 'session')
const starterPlaceholder = new RotatingPlaceholder(
() => (starterPrompts ?? []).map((p) => p.prompt),
() => (starter?.prompts ?? []).map((p) => p.prompt),
() => starterHero
)
let composerEl: HTMLDivElement | undefined = $state()
glideOnLayoutChange(
() => composerEl,
() => starterLayout
)
const columnClass = $derived(
wideLayout
@@ -673,9 +690,7 @@
<!-- tabindex="-1": clicks on non-focusable chat content must move focus into
the panel, or the Escape-to-stop focus check would wrongly reject them. -->
<div
class="flex flex-col h-full relative outline-none {starterPrompts && messages.length === 0
? 'justify-center'
: ''}"
class="flex flex-col h-full relative outline-none {starterLayout ? 'justify-center' : ''}"
tabindex="-1"
bind:this={panelEl}
ondragenter={onPanelDragEnter}
@@ -784,9 +799,17 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
{#if messages.length === 0}
{#if starterPrompts}
<div class={columnClass}>
<BuildWithAIHeading />
{#if starter}
<!-- In a session the greeting rides on top of the centred composer instead of being
centred with it: it takes the space above, the spacer after the composer the
same below. -->
<div class={centreComposer ? 'flex-1 min-h-0 flex flex-col justify-end' : ''}>
<div
class={columnClass}
style:view-transition-name={viewTransitionNames ? 'session-heading' : undefined}
>
<SessionGreeting />
</div>
</div>
{:else if emptyHint}
{@render emptyHint()}
@@ -909,8 +932,14 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
<!-- Same horizontal padding as the transcript above: the composer's edges line up with
the messages rather than sitting closer to the panel edge. -->
<!-- The bottom margin offsets the heading's weight above, so the centred box sits mid-pane. -->
<div class="relative {columnClass} pb-2 {starterPrompts && messages.length === 0 ? 'mb-24' : ''}">
<div
bind:this={composerEl}
data-session-composer
class="relative {columnClass} pb-2"
style:view-transition-name={viewTransitionNames && starterLayout
? 'session-composer'
: undefined}
>
{#if showFlowPendingActionControls}
<div class="absolute -top-10 w-full flex flex-row justify-center gap-2">
<Button
@@ -956,7 +985,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{#if inputPreface}
{@render inputPreface()}
{/if}
{#if showFreeTierUsage}
{#if showFreeTierUsage && !starterLayout}
{@render freeTierUsageBanner()}
{/if}
<AIChatInput
@@ -970,322 +999,351 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{disabled}
{pendingQuestionToolCallId}
isFirstMessage={messages.length === 0}
hero={starterHero}
hero={starterLayout}
fadingPlaceholder={starterHero ? starterPlaceholder : undefined}
/>
<div
class="mt-1 flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1"
class:justify-between={showFooterLeftControls}
class:justify-end={!showFooterLeftControls}
{onSent}
>
{#if showFooterLeftControls}
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
{#if showContextPicker && !disabled}
<Popover placement="bottom-start">
{#snippet trigger()}
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="default"
title="Add context"
iconOnly
startIcon={{ icon: AtSign }}
/>
{/snippet}
{#snippet content({ close })}
{#if chatHost.mode === AIMode.APP}
<AppAvailableContextList
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
close()
}}
/>
{:else}
<ChatContextPicker
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
onSelectWorkspaceItem={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
setShowing={(showing) => {
if (!showing) close()
}}
onSelectFile={(name) => {
aiChatInput?.insertFileMention(name)
close()
}}
/>
{/if}
{/snippet}
</Popover>
{/if}
{#if attachmentsOffReason}
<Tooltip small placement="top">
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="default"
iconOnly
disabled
startIcon={{ icon: Plus }}
/>
{#snippet text()}
<div class="max-w-64 text-xs">{attachmentsOffReason}</div>
{/snippet}
</Tooltip>
{:else if canAttachFiles}
<DropdownV2
items={() => {
const closeMenu = () => (plusMenuOpen = false)
const inGlobal = chatHost.mode === AIMode.GLOBAL
if (inGlobal) {
skillsMenu.refresh()
mcpMenu.refresh()
}
return [
{
displayName: 'Attach file or image',
icon: FileText,
action: () => {
plusMenuOpen = false
linkFiles()
}
},
...(canLinkFolders
? [
{
// A real (live) link needs the File System Access API; without it the
// folder is only snapshotted, so call it "Add folder", not "Link folder".
displayName: canUseFsAccess ? 'Link folder' : 'Add folder',
icon: Folder,
tooltip: canUseFsAccess
? 'Linked live — the assistant reads the folder’s current files from disk and refreshes each turn.'
: 'Loaded as a snapshot — the folder’s files are copied into your browser (they won’t auto-update). For a live link that refreshes from disk, use a Chromium-based browser (Chrome, Edge).',
action: () => {
plusMenuOpen = false
linkFolder()
}
}
]
: []),
...(inGlobal
? [
{
displayName: 'Mention file',
icon: AtSign,
customSubmenu: WorkspaceMentionPicker,
customSubmenuProps: {
onSelect: mentionWorkspaceItem,
onAfterClose: () => aiChatInput?.focusInput()
}
}
]
: []),
...(inGlobal
? [
{
displayName: 'Skills',
icon: BookOpen,
separatorTop: true,
// Getters so the submenus fill in when their fetch lands
// rather than the whole menu waiting on it.
get submenuItems() {
return skillsMenu.items(closeMenu)
}
},
{
displayName: 'MCP connections',
icon: Plug,
get submenuItems() {
return mcpMenu.items(closeMenu)
}
}
]
: [])
]
}}
placement="bottom-start"
fixedHeight={false}
closeOnItemClick={false}
bind:open={plusMenuOpen}
>
{#snippet buttonReplacement()}
{#snippet toolbar()}
<div
class="flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1"
class:justify-between={showFooterLeftControls}
class:justify-end={!showFooterLeftControls}
>
{#if showFooterLeftControls}
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
{#if showContextPicker && !disabled}
<Popover placement="bottom-start">
{#snippet trigger()}
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="default"
title="Add context"
iconOnly
startIcon={{ icon: AtSign }}
/>
{/snippet}
{#snippet content({ close })}
{#if chatHost.mode === AIMode.APP}
<AppAvailableContextList
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
close()
}}
/>
{:else}
<ChatContextPicker
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
onSelectWorkspaceItem={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
setShowing={(showing) => {
if (!showing) close()
}}
onSelectFile={(name) => {
aiChatInput?.insertFileMention(name)
close()
}}
/>
{/if}
{/snippet}
</Popover>
{/if}
{#if attachmentsOffReason}
<Tooltip small placement="top">
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="default"
variant="subtle"
iconOnly
disabled
startIcon={{ icon: Plus }}
/>
{#snippet text()}
<div class="max-w-64 text-xs">{attachmentsOffReason}</div>
{/snippet}
</Tooltip>
{:else if canAttachFiles}
<DropdownV2
items={() => {
const closeMenu = () => (plusMenuOpen = false)
const inGlobal = chatHost.mode === AIMode.GLOBAL
if (inGlobal) {
skillsMenu.refresh()
mcpMenu.refresh()
}
return [
{
displayName: 'Attach file or image',
icon: FileText,
action: () => {
plusMenuOpen = false
linkFiles()
}
},
...(canLinkFolders
? [
{
// A real (live) link needs the File System Access API; without it the
// folder is only snapshotted, so call it "Add folder", not "Link folder".
displayName: canUseFsAccess ? 'Link folder' : 'Add folder',
icon: Folder,
tooltip: canUseFsAccess
? 'Linked live — the assistant reads the folder’s current files from disk and refreshes each turn.'
: 'Loaded as a snapshot — the folder’s files are copied into your browser (they won’t auto-update). For a live link that refreshes from disk, use a Chromium-based browser (Chrome, Edge).',
action: () => {
plusMenuOpen = false
linkFolder()
}
}
]
: []),
...(inGlobal
? [
{
displayName: 'Mention file',
icon: AtSign,
customSubmenu: WorkspaceMentionPicker,
customSubmenuProps: {
onSelect: mentionWorkspaceItem,
onAfterClose: () => aiChatInput?.focusInput()
}
}
]
: []),
...(inGlobal
? [
{
displayName: 'Skills',
icon: BookOpen,
separatorTop: true,
// Getters so the submenus fill in when their fetch lands
// rather than the whole menu waiting on it.
get submenuItems() {
return skillsMenu.items(closeMenu)
}
},
{
displayName: 'MCP connections',
icon: Plug,
get submenuItems() {
return mcpMenu.items(closeMenu)
}
}
]
: [])
]
}}
placement="bottom-start"
fixedHeight={false}
closeOnItemClick={false}
bind:open={plusMenuOpen}
>
{#snippet buttonReplacement()}
<Tooltip small placement="top">
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="subtle"
iconOnly
startIcon={{ icon: Plus }}
/>
{#snippet text()}
<div class="max-w-64 text-xs">
<p class="font-semibold">Attach files or link a folder</p>
<p class="mt-1">
Files and images attach to your next message. Images are seen
directly; file contents stay in your browser and are read on demand.
</p>
<p class="mt-1">
A linked folder is a session-wide resource: the assistant lists,
searches, and reads its files whenever it needs them.
</p>
</div>
{/snippet}
</Tooltip>
{/snippet}
</DropdownV2>
<!-- Fallback file picker (used when the File System Access API is unavailable).
`accept` only steers the picker; the content sniff at attach is authoritative. -->
<input
bind:this={fileInputEl}
type="file"
multiple
accept={chatHost.attachmentAccept}
class="hidden no-default-style"
onchange={onFileInputChange}
/>
<!-- Fallback folder picker (no File System Access API): webkitdirectory selects a
whole folder; its files carry webkitRelativePath and are snapshotted. -->
<input
bind:this={folderInputEl}
type="file"
multiple
webkitdirectory
class="hidden no-default-style"
onchange={onFolderInputChange}
/>
{/if}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
availability={autonomyAvailability}
onChange={chatHost.setAutonomyMode}
/>
{/if}
{#if effectiveAutonomyMode === AIAutonomyMode.PLAN}
<span class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.modeNote}</span>
{/if}
{#if effectiveAutonomyMode === AIAutonomyMode.YOLO && chatHost.autoAcceptToolConfirmationsAvailable}
<Tooltip small placement="top">
<AlertTriangle class="w-3 h-3 text-red-500" />
{#snippet text()}
<div class="max-w-64 text-xs">
<p class="font-semibold">Attach files or link a folder</p>
<p class="mt-1">
Files and images attach to your next message. Images are seen directly;
file contents stay in your browser and are read on demand.
<p class="font-semibold">
{chatHost.autoAcceptEditsAvailable
? 'Bypass permissions auto-accepts edits and tool usage.'
: 'Bypass permissions auto-accepts tool usage.'}
</p>
<p class="mt-1">
A linked folder is a session-wide resource: the assistant lists, searches,
and reads its files whenever it needs them.
{chatHost.autoAcceptEditsAvailable
? 'This can result in edits being applied or tools being called without user confirmation.'
: 'This can result in tools being called without user confirmation.'}
</p>
{#if yoloBypassedTools.length > 0}
<p class="mt-2 font-semibold">Bypassed in current mode:</p>
<ul class="mt-1 list-disc pl-4 space-y-0.5">
{#each visibleYoloBypassedTools as tool (tool.name)}
<li class="break-words">{tool.label}</li>
{/each}
</ul>
{#if hiddenYoloBypassedToolCount > 0}
<p class="mt-1">+ {hiddenYoloBypassedToolCount} more</p>
{/if}
{:else}
<p class="mt-2">No tools in the current mode require confirmation.</p>
{/if}
</div>
{/snippet}
</Tooltip>
{/snippet}
</DropdownV2>
<!-- Fallback file picker (used when the File System Access API is unavailable).
`accept` only steers the picker; the content sniff at attach is authoritative. -->
<input
bind:this={fileInputEl}
type="file"
multiple
accept={chatHost.attachmentAccept}
class="hidden no-default-style"
onchange={onFileInputChange}
/>
<!-- Fallback folder picker (no File System Access API): webkitdirectory selects a
whole folder; its files carry webkitRelativePath and are snapshotted. -->
<input
bind:this={folderInputEl}
type="file"
multiple
webkitdirectory
class="hidden no-default-style"
onchange={onFolderInputChange}
/>
{/if}
{#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled}
<ChatQuickActions {askAi} {diffMode} />
{/if}
</div>
{/if}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
availability={autonomyAvailability}
onChange={chatHost.setAutonomyMode}
/>
{/if}
{#if effectiveAutonomyMode === AIAutonomyMode.PLAN}
<span class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.modeNote}</span>
{/if}
{#if effectiveAutonomyMode === AIAutonomyMode.YOLO && chatHost.autoAcceptToolConfirmationsAvailable}
<Tooltip small placement="top">
<AlertTriangle class="w-3 h-3 text-red-500" />
{#snippet text()}
<div class="max-w-64 text-xs">
<p class="font-semibold">
{chatHost.autoAcceptEditsAvailable
? 'Bypass permissions auto-accepts edits and tool usage.'
: 'Bypass permissions auto-accepts tool usage.'}
</p>
<p class="mt-1">
{chatHost.autoAcceptEditsAvailable
? 'This can result in edits being applied or tools being called without user confirmation.'
: 'This can result in tools being called without user confirmation.'}
</p>
{#if yoloBypassedTools.length > 0}
<p class="mt-2 font-semibold">Bypassed in current mode:</p>
<ul class="mt-1 list-disc pl-4 space-y-0.5">
{#each visibleYoloBypassedTools as tool (tool.name)}
<li class="break-words">{tool.label}</li>
{/each}
</ul>
{#if hiddenYoloBypassedToolCount > 0}
<p class="mt-1">+ {hiddenYoloBypassedToolCount} more</p>
{/if}
{:else}
<p class="mt-2">No tools in the current mode require confirmation.</p>
{/if}
</div>
{/snippet}
</Tooltip>
{/if}
{#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled}
<ChatQuickActions {askAi} {diffMode} />
{/if}
</div>
{/if}
{#if footerMessageShown}
<div class="text-primary text-xs my-2 px-2">
<Markdown md={disabledMessage} />
</div>
{:else}
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center">
{#if chatHost.mode === AIMode.GLOBAL}
<AttachedFilesBar />
{/if}
{#if !hideModeSelector}
<ChatMode />
{/if}
{#if chatHost.mode === AIMode.APP}
<DatatableCreationPolicy />
{/if}
<ContextUsageIndicator />
{#if chatHost.supportsModelSettings}
<!-- `promptSettings={false}`: in a session, GLOBAL, the settings modal's
{#if footerMessageShown}
<div class="text-primary text-xs my-2 px-2">
<Markdown md={disabledMessage} />
</div>
{:else}
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center">
{#if chatHost.mode === AIMode.GLOBAL}
<AttachedFilesBar />
{/if}
{#if !hideModeSelector}
<ChatMode />
{/if}
{#if chatHost.mode === AIMode.APP}
<DatatableCreationPolicy />
{/if}
<ContextUsageIndicator />
{#if chatHost.supportsModelSettings}
<!-- `promptSettings={false}`: in a session, GLOBAL, the settings modal's
Instructions section owns the prompt entries. -->
<AIChatModelSettings promptSettings={false} />
{/if}
{@render footerSettings?.()}
{#if chatHost.mode === AIMode.GLOBAL}
<AssistantSettingsModal bind:this={assistantSettings} />
{/if}
<AIChatModelSettings promptSettings={false} />
{/if}
{@render footerSettings?.()}
{#if chatHost.mode === AIMode.GLOBAL}
<AssistantSettingsModal bind:this={assistantSettings} />
{/if}
{#if chatHost.mode === AIMode.APP && appContext && (appContext.inspectorElement || appContext.codeSelection)}
{#if appContext.inspectorElement}
<div
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-2xs"
title={appContext.inspectorElement.path}
>
<MousePointer2 class="w-3 h-3" />
<span class="truncate max-w-[60px]">
{appContext.inspectorElement.tagName.toLowerCase()}{appContext.inspectorElement
.id
? `#${appContext.inspectorElement.id}`
: ''}{appContext.inspectorElement.className
? `.${appContext.inspectorElement.className.split(' ')[0]}`
: ''}
</span>
<button
class="hover:bg-purple-200 dark:hover:bg-purple-800/50 rounded p-0.5 -mr-0.5"
onclick={() => appContext.clearInspector?.()}
title="Clear element selection"
>
<X class="w-2.5 h-2.5" />
</button>
</div>
{/if}
{#if appContext.codeSelection}
<div
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-2xs"
title={`${appContext.codeSelection.source}: lines ${appContext.codeSelection.startLine}-${appContext.codeSelection.endLine}`}
>
<TextSelect class="w-3 h-3" />
<span class="truncate max-w-[80px]">
L{appContext.codeSelection.startLine}-{appContext.codeSelection.endLine}
</span>
<button
class="hover:bg-amber-200 dark:hover:bg-amber-800/50 rounded p-0.5 -mr-0.5"
onclick={() => appContext.clearCodeSelection?.()}
title="Clear code selection"
>
<X class="w-2.5 h-2.5" />
</button>
</div>
{/if}
{#if chatHost.mode === AIMode.APP && appContext && (appContext.inspectorElement || appContext.codeSelection)}
{#if appContext.inspectorElement}
<div
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-2xs"
title={appContext.inspectorElement.path}
>
<MousePointer2 class="w-3 h-3" />
<span class="truncate max-w-[60px]">
{appContext.inspectorElement.tagName.toLowerCase()}{appContext
.inspectorElement.id
? `#${appContext.inspectorElement.id}`
: ''}{appContext.inspectorElement.className
? `.${appContext.inspectorElement.className.split(' ')[0]}`
: ''}
</span>
<button
class="hover:bg-purple-200 dark:hover:bg-purple-800/50 rounded p-0.5 -mr-0.5"
onclick={() => appContext.clearInspector?.()}
title="Clear element selection"
>
<X class="w-2.5 h-2.5" />
</button>
</div>
{/if}
{#if appContext.codeSelection}
<div
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-2xs"
title={`${appContext.codeSelection.source}: lines ${appContext.codeSelection.startLine}-${appContext.codeSelection.endLine}`}
>
<TextSelect class="w-3 h-3" />
<span class="truncate max-w-[80px]">
L{appContext.codeSelection.startLine}-{appContext.codeSelection.endLine}
</span>
<button
class="hover:bg-amber-200 dark:hover:bg-amber-800/50 rounded p-0.5 -mr-0.5"
onclick={() => appContext.clearCodeSelection?.()}
title="Clear code selection"
>
<X class="w-2.5 h-2.5" />
</button>
</div>
{/if}
{/if}
</div>
{/if}
</div>
{/if}
</div>
{/snippet}
</AIChatInput>
</div>
{#if starterLayout && starter}
{#if showFreeTierUsage}
<div
class="mt-2 flex flex-row items-center justify-end gap-1 text-2xs text-hint tabular-nums"
>
{freeTierUsedPct}% of free AI used ·
<Button
variant="subtle"
unifiedSize="2xs"
btnClasses="!text-2xs !text-hint !px-0 underline"
href="/workspace_settings?tab=ai"
>
Configure API key
</Button>
</div>
{/if}
{#if starter.chips && !disabled}
<div class="mt-3">
<StarterPromptChips
prompts={starter.prompts}
onPick={(prompt) => aiChatInput?.setText(prompt)}
/>
</div>
{/if}
{/if}
{#if (chatHost.mode === AIMode.NAVIGATOR || chatHost.mode === AIMode.ASK) && suggestions.length > 0 && messages.filter((m) => m.role === 'user').length === 0 && !disabled}
<div class="px-2 mt-4">
<div class="flex flex-col gap-2">
@@ -1303,4 +1361,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
</div>
{#if centreComposer}
<div class="flex-1 min-h-0"></div>
{/if}
</div>
@@ -14,6 +14,11 @@
import { CHAT_INPUT_PADDING, getAiChatManager } from './aiChatManagerContext'
import { getChatViewHost } from './chatViewHost'
import { composerBoxClass, COMPOSER_FIELD_RESET } from './composerBox'
// The send button sits in the toolbar row, not over the field, so the text needs no
// room reserved on its right, and the row right below it stands in for most of its
// bottom padding.
const FIELD_PADDING_WITH_TOOLBAR = '!pr-3 !pb-1'
import { formatMention, hasMention, removeMentionFromText } from './mention'
import { twMerge } from 'tailwind-merge'
import { tick, untrack, type Snippet } from 'svelte'
@@ -93,9 +98,16 @@
// plain-text draft sent from here answers it instead of queueing behind a
// turn that only the answer can resume.
pendingQuestionToolCallId?: string
/** Forwarded to ContextTextarea: the composer that opens a session. */
/** The composer that opens a session (Home, an empty session): `toolbar` is drawn in the
* box's bottom row with the send button at its end, and a usable box is taller. Otherwise
* the controls sit under the box and the send button floats over the field's corner, as a
* chat under way reads more clearly. */
hero?: boolean
fadingPlaceholder?: { text: string; visible: boolean }
/** After a new turn is handed to the host — not an edit, a queued message or an answer. */
onSent?: () => void
/** The composer's controls. */
toolbar?: Snippet
}
let {
@@ -120,10 +132,14 @@
onCancel,
onDraftChange = undefined,
pendingQuestionToolCallId = undefined,
onSent = undefined,
toolbar = undefined,
hero = false,
fadingPlaceholder = undefined
}: Props = $props()
const toolbarInBox = $derived(!!toolbar && hero)
// GLOBAL-mode suggestion pool. We pick one at mount-time so each new
// session lands on a different prompt; the choice stays stable for
// the lifetime of this input so the placeholder doesn't shuffle as
@@ -641,6 +657,13 @@
draft.text = removeMentionFromText(draft.text, title)
}
/** Replace the draft's text, keeping its attachments: a starter prompt fills the box, it
* never sends. */
export function setText(text: string) {
draft.text = text
focusInput()
}
export function focusInput() {
if (isContextEnabledMode) {
contextTextareaComponent?.focus()
@@ -982,6 +1005,7 @@
// textarea still rely on the draft reset alone (no `@`-mention state to
// coordinate).
contextTextareaComponent?.clearForSend()
onSent?.()
}
}
@@ -1212,7 +1236,18 @@
}
</script>
{#snippet sendStopButton()}
{#snippet toolbarRow()}
{#if toolbarInBox}
<!-- The send button sets the row's height and the smaller controls centre on it, which
already puts them a few pixels further from the box's bottom edge than the padding. -->
<div class="flex flex-row items-center gap-1.5 px-1.5 pb-1">
<div class="flex-1 min-w-0">{@render toolbar?.()}</div>
{@render sendStopButton('sm')}
</div>
{/if}
{/snippet}
{#snippet sendStopButton(size: 'sm' | 'md' = 'md')}
<!-- The turn stays `loading` while parked on a question, but a drafted answer
is what the button should ship then — otherwise the only pointer action on
a typed answer would be Stop. Anything else keeps Stop. -->
@@ -1237,9 +1272,11 @@
(onSendRequest !== undefined ||
chatHost.mode !== AIMode.GLOBAL ||
selectedContext.length === 0))}
<!-- Accent only once there is something to send, so the button lights up as the draft
becomes sendable; idle and Stop stay quiet. -->
<Button
variant="subtle"
unifiedSize="md"
variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'}
unifiedSize={size}
iconOnly
title={isLoading
? 'Stop'
@@ -1407,7 +1444,7 @@
{availableContext}
{selectedContext}
placeholder={modePlaceholder}
{hero}
hero={hero && !disabled}
fadingPlaceholder={isFirstMessage && !chatHost.runHeldElsewhere
? fadingPlaceholder
: undefined}
@@ -1423,13 +1460,17 @@
}}
{disabled}
{onKeyDown}
className={toolbarInBox ? FIELD_PADDING_WITH_TOOLBAR : ''}
>
{#snippet leading()}
{@render badgeRow()}
{@render imageChipsRow()}
{/snippet}
{#snippet trailing()}
{@render toolbarRow()}
{/snippet}
</ContextTextarea>
{#if !bottomRightSnippet}
{#if !bottomRightSnippet && !toolbarInBox}
<div class="absolute bottom-1 right-1">
{@render sendStopButton()}
</div>
@@ -1527,17 +1568,26 @@
}}
rows={1}
placeholder={modePlaceholder}
class={twMerge('resize-none', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING)}
class={twMerge(
'resize-none',
COMPOSER_FIELD_RESET,
CHAT_INPUT_PADDING,
toolbarInBox && FIELD_PADDING_WITH_TOOLBAR
)}
{disabled}
></textarea>
{#if !bottomRightSnippet}
{#if !bottomRightSnippet && !toolbarInBox}
<div class="absolute bottom-1 right-1">
{@render sendStopButton()}
</div>
{/if}
</div>
{@render toolbarRow()}
</div>
{/if}
{#if toolbar && !toolbarInBox}
<div class="mt-1">{@render toolbar()}</div>
{/if}
{#if bottomRightSnippet}
<div class="absolute bottom-1 right-1">
{@render bottomRightSnippet()}
@@ -332,7 +332,7 @@ function isWorkspacePath(path: string | undefined): path is string {
// Returns the safe ACCEPT_EDIT default when no user is known yet — the
// module-level singleton (constructed at import, before the email resolves)
// re-reads via onUserChange once it does.
export function getPersistedAutonomyMode(): AIAutonomyMode {
function getPersistedAutonomyMode(): AIAutonomyMode {
const key = scopedKey(AI_AUTONOMY_MODE_STORAGE_KEY)
if (!BROWSER || !key) {
return AIAutonomyMode.ACCEPT_EDIT
@@ -2260,6 +2260,10 @@ export class AIChatManager implements ChatViewHost {
this.aiChatInput = aiChatInput
}
releaseAiChatInput(aiChatInput: AIChatInput) {
if (this.aiChatInput === aiChatInput) this.aiChatInput = null
}
/** Queue the message typed while a turn is streaming. There is only ever
* one queued message; pressing Enter again appends the new text as another
* line so it all goes out as a single message, and its images accumulate
@@ -39,7 +39,7 @@
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="default"
variant="subtle"
title={option.tooltip(availability)}
btnClasses={option.triggerClass ?? ''}
startIcon={{ icon: option.icon, classes: option.iconColor }}
@@ -51,6 +51,8 @@
onKeyDown?: (e: KeyboardEvent) => void
/** Rendered inside the input box, above the textarea (e.g. context chips). */
leading?: Snippet
/** Rendered inside the input box, below the textarea (the composer's controls). */
trailing?: Snippet
/** The taller box that opens a session, matching Home's composer. */
hero?: boolean
/** Replaces `placeholder` with one drawn over the field, so it can fade between prompts. */
@@ -72,6 +74,7 @@
className = '',
onKeyDown = undefined,
leading,
trailing,
hero = false,
fadingPlaceholder
}: Props = $props()
@@ -828,7 +831,7 @@
bind:this={textarea}
onkeydown={handleKeyDown}
bind:value
use:autosize={{ maxHeight: '40vh', minHeight: hero ? 96 : undefined }}
use:autosize={{ maxHeight: '40vh', minHeight: hero ? 56 : undefined }}
rows={1}
oninput={handleInput}
onpaste={handlePaste}
@@ -853,7 +856,7 @@
}, 200)
}}
placeholder={fadingPlaceholder ? '' : placeholder}
aria-label={fadingPlaceholder ? 'Describe what you want to build' : undefined}
aria-label={fadingPlaceholder ? 'Describe what you want to do' : undefined}
class={twMerge(
'textarea-input resize-none caret-black dark:caret-white overflow-clip',
COMPOSER_FIELD_RESET,
@@ -864,6 +867,7 @@
{disabled}
></textarea>
</div>
{@render trailing?.()}
</div>
{#if showContextTooltip || showCommandTooltip}
@@ -73,6 +73,10 @@ export interface ChatViewHost {
sendRequest: (options?: ChatSendRequestOptions) => Promise<boolean | undefined>
cancel: (reason?: string) => void
setAiChatInput: (aiChatInput: AIChatInput | null) => void
/** Unregisters `aiChatInput` if it is still the registered one. A host's chat can remount
* elsewhere (Home hands its session to /sessions), and the new composer may register before
* the old one's teardown runs. */
releaseAiChatInput: (aiChatInput: AIChatInput) => void
readonly queuedMessage: string
queuedContext: ContextElement[] | undefined
readonly queuedImages: AttachedImage[]
@@ -0,0 +1,46 @@
import { untrack } from 'svelte'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
/** The glide's timing, read from the tokens app.css defines once for this move and for
* the Home ↔ AI Sessions view transition, so the two read as the same motion. */
function glideTiming(): { duration: number; easing: string } {
const style = getComputedStyle(document.documentElement)
const duration = parseFloat(style.getPropertyValue('--composer-glide-duration'))
const easing = style.getPropertyValue('--composer-glide-easing').trim()
return { duration: Number.isFinite(duration) ? duration : 200, easing: easing || 'ease-out' }
}
/**
* Slides `el` from where it sat to where it lands whenever `layout()` changes (an empty
* session's composer dropping to the bottom on its first message). Measured before the DOM
* updates, again after, and the difference animated away; an element that did not move does
* not animate. Under reduced motion it fades in where it landed.
*/
export function glideOnLayoutChange(el: () => HTMLElement | undefined, layout: () => unknown) {
const reducedMotion = useReducedMotion()
let from: DOMRect | undefined
$effect.pre(() => {
layout()
from = untrack(el)?.getBoundingClientRect()
})
$effect(() => {
layout()
const node = untrack(el)
const start = from
from = undefined
if (!node || !start) return
const { duration, easing } = glideTiming()
if (reducedMotion.val) {
node.animate([{ opacity: 0 }, { opacity: 1 }], { duration })
return
}
const end = node.getBoundingClientRect()
const dx = start.left - end.left
const dy = start.top - end.top
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return
node.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
duration,
easing
})
})
}
@@ -1,10 +0,0 @@
<script lang="ts">
import { Badge } from '$lib/components/common'
</script>
<!-- The title over every composer that starts a session — on Home and in an empty session
alike — so both read as the same entry point. -->
<div class="flex items-center justify-center gap-2 mb-4">
<p class="text-center font-regular text-3xl">Build with AI</p>
<Badge color="blue" small>Beta</Badge>
</div>
@@ -0,0 +1,30 @@
<script lang="ts">
import { Badge } from '$lib/components/common'
import { userStore, userWorkspaces, workspaceStore } from '$lib/stores'
import { takeFirstVisit, timeOfDayGreeting } from './greeting'
// `name` is the full name when the account has one; the greeting uses the first word.
const userName = $derived($userStore?.name?.trim().split(/\s+/)[0] || $userStore?.username)
const workspaceName = $derived(
$userWorkspaces.find((w) => w.id === $workspaceStore)?.name ?? $workspaceStore
)
// Read once the membership for this workspace has loaded: `userStore` still describes the
// previous workspace for a moment after a switch.
const firstVisit = $derived(
!!$workspaceStore &&
$userStore?.workspace_id === $workspaceStore &&
takeFirstVisit($workspaceStore, $userStore.created_at)
)
const greeting = timeOfDayGreeting()
</script>
<div class="flex items-center justify-center gap-2 mb-4">
<p class="text-center font-regular text-3xl">
{#if firstVisit}
Welcome to {workspaceName}{userName ? `, ${userName}` : ''}
{:else}
{greeting}{userName ? `, ${userName}` : ''}
{/if}
</p>
<Badge color="blue" small>Beta</Badge>
</div>
@@ -0,0 +1,41 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const scoped = vi.hoisted(() => ({ key: 'welcomed::ada@example.com' as string | undefined }))
vi.mock('$lib/userScopedStorage', () => ({ scopedKey: () => scoped.key }))
import { takeFirstVisit } from './greeting'
const DAY = 24 * 60 * 60 * 1000
const daysAgo = (n: number) => new Date(Date.now() - n * DAY).toISOString()
const store = new Map<string, string>()
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, v)
})
beforeEach(() => {
store.clear()
scoped.key = 'welcomed::ada@example.com'
})
describe('takeFirstVisit', () => {
it('welcomes a new member once per workspace, for the whole page load', () => {
expect(takeFirstVisit('acme', daysAgo(2))).toBe(true)
// Back on Home or the empty session in the same load: still the welcome.
expect(takeFirstVisit('acme', daysAgo(2))).toBe(true)
expect(JSON.parse(store.get('welcomed::ada@example.com')!)).toEqual(['acme'])
})
it('greets by time of day for an older member, or a workspace already welcomed', () => {
expect(takeFirstVisit('old-team', daysAgo(45))).toBe(false)
store.set('welcomed::ada@example.com', JSON.stringify(['seen-before']))
expect(takeFirstVisit('seen-before', daysAgo(1))).toBe(false)
})
it('records nothing before the user is known', () => {
scoped.key = undefined
expect(takeFirstVisit('fresh', daysAgo(1))).toBe(false)
expect(store.size).toBe(0)
})
})
@@ -0,0 +1,37 @@
import { scopedKey } from '$lib/userScopedStorage'
const WELCOMED_KEY = 'session-block-welcomed-workspaces'
/** A membership older than this is not a first visit, whatever this browser remembers: without
* it, everyone already in a workspace would be welcomed to it once on their next visit. */
const NEW_MEMBER_MS = 30 * 24 * 60 * 60 * 1000
// Workspaces welcomed during this page load: the welcome holds for the whole visit (Home, the
// empty session, back), and only a later load greets by time of day.
const welcomedThisLoad = new Set<string>()
/** Whether this is the user's first visit to `workspace`: a recent member this browser has not
* welcomed there yet. Answering yes records the welcome. */
export function takeFirstVisit(workspace: string, memberSince: string | undefined): boolean {
if (welcomedThisLoad.has(workspace)) return true
const key = scopedKey(WELCOMED_KEY)
if (!key) return false
let welcomed: string[] = []
try {
welcomed = JSON.parse(localStorage.getItem(key) ?? '[]')
} catch {}
if (welcomed.includes(workspace)) return false
const joined = memberSince ? Date.parse(memberSince) : NaN
if (!(Date.now() - joined < NEW_MEMBER_MS)) return false
welcomedThisLoad.add(workspace)
try {
localStorage.setItem(key, JSON.stringify([...welcomed, workspace]))
} catch {}
return true
}
export function timeOfDayGreeting(now = new Date()): string {
const hour = now.getHours()
if (hour >= 5 && hour < 12) return 'Good morning'
if (hour >= 12 && hour < 18) return 'Good afternoon'
return 'Good evening'
}
@@ -2,6 +2,8 @@ import { onboardingProfile, type StarterPrompt } from '$lib/onboardingProfile'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
import { userStore } from '$lib/stores'
import { fromStore } from 'svelte/store'
import { resource } from 'runed'
import { ScriptService } from '$lib/gen'
/** Example prompts: the short `label` is shown as a clickable tag under the composer,
* the `prompt` is what rotates through the placeholder / gets dropped into the input. */
@@ -48,12 +50,57 @@ export class StarterPrompts {
readonly list = $derived(
this.#invite ?? (this.#user.current?.operator ? operatorStarterPrompts : defaultStarterPrompts)
)
#hasItems: { readonly current: boolean | undefined }
constructor() {
/** `workspace`: where the session acts, which decides whether the chips are offered. */
constructor(workspace: () => string | undefined) {
void onboardingProfile().then((p) => {
if (p?.starter_prompts?.length) this.#invite = p.starter_prompts
})
this.#hasItems = resource(workspace, async (ws) => (ws ? workspaceHasItems(ws) : undefined))
}
/** The example chips are for a workspace with nothing in it yet: next to someone's own
* scripts and flows, "Ban Discord users" is noise. Withheld until the workspace is known
* to be empty, so they never show and then vanish. The examples still rotate through the
* placeholder either way. */
get chipsOffered(): boolean {
return this.#hasItems.current === false
}
}
// Workspaces known to hold something, for the page load. An empty answer is not kept: the
// next mount asks again, so the chips go once the user has created their first item.
const workspacesWithItems = new Set<string>()
async function workspaceHasItems(workspace: string): Promise<boolean> {
if (workspacesWithItems.has(workspace)) return true
try {
// What Home's list counts: library scripts and the user's own drafts included.
const res = await ScriptService.listRunnables({
workspace,
includeWithoutMain: true,
includeDraftOnly: true,
perPage: 1
})
const has = (res.items?.length ?? 0) > 0
if (has) workspacesWithItems.add(workspace)
return has
} catch (e) {
// Unknown reads as "has items": no chips is the quieter mistake.
console.error(`Could not check whether workspace ${workspace} has items:`, e)
return true
}
}
/** What turns an empty chat into the block that starts a session. */
export type ChatStarter = {
/** The page the block is on: an empty session centres it in the pane, Home does not. */
where: 'home' | 'session'
/** Rotated through the placeholder. */
prompts: StarterPrompt[]
/** Also offered as chips under the box. */
chips: boolean
}
const CYCLE_MS = 7_000
@@ -578,6 +578,9 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac
this.#aiChatInput = aiChatInput
this.#takeReturned()
})
releaseAiChatInput: ChatViewHost['releaseAiChatInput'] = (aiChatInput) => {
if (this.#aiChatInput === aiChatInput) this.#aiChatInput = null
}
/** Whether a composer showing this conversation holds something not sent — text, an
* attachment, a file still being read. Its panel stays mounted for as long as one does:
@@ -1,56 +1,25 @@
<script lang="ts">
import TextInput from '$lib/components/text_input/TextInput.svelte'
import {
ArrowUp,
ExternalLink,
Globe2,
KeyRound,
PlugZap,
Settings,
WandSparkles
} from 'lucide-svelte'
import { ExternalLink, Globe2, PlugZap, WandSparkles } from 'lucide-svelte'
import Button from '../common/button/Button.svelte'
import CloseButton from '../common/CloseButton.svelte'
import { startSessionWithPrompt } from '../sessions/sessionSwitch.svelte'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
import { copilotWorkspace } from '$lib/aiStore'
import { WorkspaceService } from '$lib/gen'
import { resource } from 'runed'
import { loadCopilot } from '$lib/components/copilot/loadCopilot'
import {
aiUserDisabled,
hubBaseUrlStore,
userStore,
userWorkspaces,
workspaceStore
} from '$lib/stores'
import ActingOnPicker from '../sessions/ActingOnPicker.svelte'
import { defaultSessionWorkspace, type PendingFork } from '../sessions/sessionState.svelte'
import AutonomyModePicker from '../copilot/chat/AutonomyModePicker.svelte'
import {
AIAutonomyMode,
getPersistedAutonomyMode,
AIMode,
supportsAutoAcceptEdits,
supportsAutoAcceptToolConfirmations,
supportsPlanMode
} from '../copilot/chat/AIChatManager.svelte'
import { hubBaseUrlStore, userStore, workspaceStore } from '$lib/stores'
import { sessionState } from '../sessions/sessionState.svelte'
import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte'
import HomeSessionStarter from '../sessions/HomeSessionStarter.svelte'
import { HOME_SHOW_HUB } from '$lib/consts'
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
import { isRuleActive } from '$lib/workspaceProtectionRules.svelte'
import { isRuleActive, protectionRulesState } from '$lib/workspaceProtectionRules.svelte'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
import { BROWSER } from 'esm-env'
import AIChatModelSettings from '../copilot/chat/AIChatModelSettings.svelte'
import HomeConnectDrawer from './HomeConnectDrawer.svelte'
import { USER_SETTINGS_HASH } from '../sidebar/settings'
import { prefersSessionHandoff } from '../copilot/chat/global/gate'
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
import BuildWithAIHeading from '../copilot/chat/starter/BuildWithAIHeading.svelte'
import StarterPromptChips from '../copilot/chat/starter/StarterPromptChips.svelte'
import {
PLACEHOLDER_FADE_CLASS,
RotatingPlaceholder,
StarterPrompts
} from '../copilot/chat/starter/starterPrompts.svelte'
const COLLAPSED_SETTING = 'home-ai-composer-collapsed'
@@ -61,8 +30,6 @@
const sideTripsInBar = $derived(pageHeader.barWidth >= BAR_FITS_SIDE_TRIPS)
const hubOffered = $derived(!$userStore?.operator && HOME_SHOW_HUB)
let value = $state('')
const starterPrompts = new StarterPrompts()
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
// How much of the home page this reader wants the composer to take, so it lives per browser
@@ -94,33 +61,6 @@
pulseEndTimer = setTimeout(() => (pulsing = false), PULSE_MS)
}
// In global-AI mode the layout's chat panel is disabled and never loads the copilot
// config, so the home chat loads it for the current workspace itself.
$effect(() => {
if ($workspaceStore) {
loadCopilot($workspaceStore)
}
})
// Whether the copilot config has actually loaded for the current workspace.
let configLoaded = $derived($copilotWorkspace === $workspaceStore)
// No usable model (no provider configured, or AI disabled): the input is blurred and an overlay
// explains why and links to the fix. Gate on `configLoaded` so the initial (unloaded) state
// doesn't flash the overlay while a provider is in fact configured.
let disabled = $derived(configLoaded && !$copilotInfo.enabled)
// Submission is stricter than the overlay: block it until the config is loaded AND
// enabled. Submitting during the unknown-config window hands the prompt to a session
// that only sends once `copilotInfo.enabled` flips true — on an unconfigured/disabled
// workspace that never happens and the prompt is silently lost.
let canSend = $derived(configLoaded && $copilotInfo.enabled)
// The input alone: what the overlay covers and the one part a missing provider makes unusable.
let blurClass = $derived(disabled ? 'blur-sm pointer-events-none select-none' : '')
// Disabled because the user spent their free Windmill AI grant, not because AI was never
// set up — the two look identical otherwise, and the "configure AI" copy would be a lie.
let freeTierExhausted = $derived($copilotInfo.freeTier?.exhausted === true)
// A workspace locked against direct deployment is run, not authored in, so its home page drops
// the composer and the button to reopen it. This is about the workspace, not the caller:
// `createSession` would steer a prompt into the paired dev workspace and an admin bypasses the
@@ -128,13 +68,48 @@
// unlocked, so the far commoner unlocked workspace never pops the composer in mid-load.
let runOnlyWorkspace = $derived(isRuleActive('DisableDirectDeployment'))
// The draft is created when the block mounts, and a new draft steers to the dev workspace
// while the rules are unknown (a locked prod could not be edited), so the block waits for
// them: mounted earlier, an unlocked prod's draft would act on its dev. Once shown for a
// family it stays: switching to a fork resets the rules, and remounting would flash it.
let rulesReady = $derived(
protectionRulesState.rulesets !== undefined &&
protectionRulesState.workspace === $workspaceStore
)
let shownForRoot = $state<string>()
// In global-AI mode the layout's chat panel is disabled and never loads the copilot config,
// so Home loads it for its workspace until the block shows; from then on the block loads the
// config of the workspace its draft acts on, and loading Home's over it would show the
// draft another workspace's models.
$effect(() => {
if ($workspaceStore && shownForRoot !== $currentWorkspaceRootId) {
loadCopilot($workspaceStore)
}
})
// Whether Home's own workspace hides the assistant, read for that workspace directly: the
// shared copilot config follows whichever workspace loaded last, and once the block shows
// that is the draft's, so a draft acting on a workspace that hides AI would otherwise take
// the whole block, and the picker that could undo it, off Home.
const homeAiHidden = resource(
() => $workspaceStore ?? undefined,
async (workspace) => {
if (!workspace) return false
try {
return (await WorkspaceService.getCopilotInfo({ workspace })).copilot_disabled === true
} catch (e) {
console.error(`Failed to read the AI config of workspace ${workspace}:`, e)
return false
}
}
)
// The composer hands off to /sessions, which refuses operators and users opted out of the
// sessions beta — so hide it from them (the prompt would be silently dropped) while the
// AI-independent CLI/MCP row below stays.
let showComposer = $derived(
prefersSessionHandoff($userStore?.operator) &&
!runOnlyWorkspace &&
!$copilotInfo.workspaceDisabled
prefersSessionHandoff($userStore?.operator) && !runOnlyWorkspace && !homeAiHidden.current
)
// The hero's margins and centered column are for the full block. The lone button row left
@@ -143,179 +118,26 @@
// hugs the right edge instead of floating centered in empty space.
let hero = $derived(showComposer && !collapsed)
let outerSpacing = $derived(hero ? 'mt-20 mb-16' : 'mt-0 mb-1')
// The session's own pre-send controls, held here until the hand-off creates the session.
// A pick is kept with the workspace it was made in, so switching workspace drops it
// rather than carrying a workspace from another family into the new session.
let actingOnPick = $state<{ in: string; workspaceId: string; fork?: PendingFork }>()
const pickHere = $derived(actingOnPick?.in === $workspaceStore ? actingOnPick : undefined)
// defaultSessionWorkspace reads these stores with `get`, so name them to re-run on change.
const actingOnId = $derived.by(() => {
void $userWorkspaces
void $workspaceStore
return pickHere?.workspaceId ?? defaultSessionWorkspace()
})
function pickActingOn(workspaceId: string, fork?: PendingFork) {
if ($workspaceStore) actingOnPick = { in: $workspaceStore, workspaceId, fork }
}
// Only a mode picked here is handed off: the persisted one is what the session would
// start with anyway, and it can read stale before the user's email resolves.
let pickedAutonomyMode = $state<AIAutonomyMode>()
// The persisted mode is keyed by the user's email, so re-read it once that resolves.
const autonomyMode = $derived.by(() => {
void $userStore?.email
return pickedAutonomyMode ?? getPersistedAutonomyMode()
})
const sessionAutonomyAvailability = {
autoAcceptEditsAvailable: supportsAutoAcceptEdits(AIMode.GLOBAL),
autoAcceptToolConfirmationsAvailable: supportsAutoAcceptToolConfirmations(AIMode.GLOBAL),
planModeAvailable: supportsPlanMode(AIMode.GLOBAL)
}
let starting = $state(false)
async function start() {
if (!canSend || starting || !value.trim()) return
starting = true
try {
await startSessionWithPrompt(value, {
autoSend: true,
// Always the displayed workspace, picked or not: createSession may reuse an
// untouched draft parked elsewhere, and the session must act where Home said.
actingOn: actingOnId ? { workspaceId: actingOnId, fork: pickHere?.fork } : undefined,
autonomyMode: pickedAutonomyMode
})
} finally {
starting = false
}
}
// Enter starts the session; Shift+Enter keeps inserting a newline.
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
start()
}
}
const placeholder = new RotatingPlaceholder(
() => starterPrompts.list.map((e) => e.prompt),
() => showComposer && !collapsed
)
</script>
<div class="w-full flex justify-center {outerSpacing}">
<div class="{hero ? 'max-w-[40rem]' : ''} grow relative group">
{#if showComposer && !collapsed}
{#if !disabled}
<!-- The one dismiss control while the composer is usable; the overlay below carries its
own once it takes over, so the two never show at the same time. -->
<div class="absolute right-0 top-0 z-20">
<CloseButton small noBg title="Remove session chat" onClick={removeComposer} />
</div>
{/if}
<BuildWithAIHeading />
<ActingOnPicker
selectedId={actingOnId}
pendingFork={pickHere?.fork}
onPick={(id) => pickActingOn(id)}
onCreateFork={(fork) => pickActingOn(fork.parent_workspace_id, fork)}
/>
<!-- Anchors the send button / model settings to the input, not to the whole block — the row
below would otherwise push them down. The inner wrapper stays `relative` in both
states: `blur-sm` is a filter, which makes an element the containing block for its
absolutely positioned children, so those two would shift when the blur turns on. -->
<div class="relative">
<div class="relative {blurClass}" inert={disabled}>
<TextInput
bind:value
class="resize-none px-4 py-3 pb-9 shadow-sm border-accent"
underlyingInputEl="textarea"
inputProps={{
rows: 4,
'aria-label': 'Describe what you want to build',
onkeydown: onKeydown
}}
/>
{#if !value}
<!-- The 1px margin is the textarea's border, so the text sits where typing starts. -->
<span
aria-hidden="true"
class="pointer-events-none absolute inset-x-4 top-3 m-px text-xs text-hint {PLACEHOLDER_FADE_CLASS} {placeholder.visible
? 'opacity-100'
: 'opacity-0'}"
>
{placeholder.text}
</span>
{/if}
<Button
endIcon={starting ? {} : { icon: ArrowUp }}
wrapperClasses="absolute right-2 bottom-3.5"
variant={value.trim() ? 'accent' : 'subtle'}
iconOnly
loading={starting}
disabled={!value.trim() || starting || !canSend}
onclick={start}
></Button>
<div class="absolute left-3 bottom-4 flex items-center gap-1.5 px-0.5">
<AutonomyModePicker
mode={autonomyMode}
availability={sessionAutonomyAvailability}
onChange={(mode) => (pickedAutonomyMode = mode)}
/>
<AIChatModelSettings />
</div>
</div>
{#if disabled}
<!-- Covers the input alone: the title, the example prompts and the CLI/MCP row are all
still legible and usable without a provider. Static, not hover-gated, so keyboard
and touch users see it too. -->
<div
class="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 rounded-md bg-surface/70"
>
<p class="text-sm text-secondary">
{#if $aiUserDisabled}
Windmill AI is disabled in your account settings
{:else if freeTierExhausted}
You have used all of your free Windmill AI tokens
{:else}
No AI provider is configured
{/if}
</p>
<div class="flex items-center gap-2">
{#if $aiUserDisabled}
<!-- The fix lives in account settings (a hash-opened drawer, not a route), so link
the hash the sidebar's Account menu uses rather than the workspace AI settings. -->
<Button
unifiedSize="sm"
variant="accent"
startIcon={{ icon: Settings }}
href={USER_SETTINGS_HASH}
>
Open account settings
</Button>
{:else}
<Button
unifiedSize="sm"
variant="accent"
startIcon={{ icon: freeTierExhausted ? KeyRound : Settings }}
href="/workspace_settings?tab=ai"
>
{freeTierExhausted ? 'Add your own API key' : 'Configure AI'}
</Button>
{/if}
<Button unifiedSize="sm" variant="default" onClick={removeComposer}>Remove</Button>
</div>
</div>
{/if}
<div class="{hero ? 'max-w-3xl' : ''} grow relative group">
{#if hero}
<div class="absolute right-0 top-0 z-20">
<CloseButton small noBg title="Remove session chat" onClick={removeComposer} />
</div>
{/if}
<div class="flex items-center justify-between gap-2 pt-2">
{#if showComposer && !collapsed}
<StarterPromptChips prompts={starterPrompts.list} onPick={(p) => (value = p)} />
<!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on
the workspace family, not the workspace: another family needs its own draft, but a
fork shares its parent's, and remounting for it only flashes the block. -->
<!-- It also waits for the first AI config to load: the chat reads "AI not configured"
until then and would flash its disabled state. Any loaded config will do, so a
later switch to a fork does not unmount it while the fork's config loads. -->
{#if sessionState.hydrated && $copilotWorkspace !== undefined && (rulesReady || shownForRoot === $currentWorkspaceRootId)}
{#key $currentWorkspaceRootId}
<HomeSessionStarter onShown={() => (shownForRoot = $currentWorkspaceRootId)} />
{/key}
{/if}
</div>
{/if}
</div>
</div>
@@ -1,34 +0,0 @@
<script lang="ts">
import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte'
import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte'
import type { PendingFork } from './sessionState.svelte'
let {
selectedId,
pendingFork,
onPick,
onCreateFork
}: {
selectedId: string | undefined
pendingFork: PendingFork | undefined
onPick: (workspaceId: string) => void
onCreateFork: (fork: PendingFork) => void
} = $props()
</script>
<!-- Where a session's first message will act. A fork picked here is only staged: it is
created when that message is sent. -->
<div class="flex flex-row items-center gap-1 py-0.5 px-1 text-2xs text-secondary">
<span class="shrink-0">Acting on</span>
<WorkspaceFamilyPicker
{selectedId}
{pendingFork}
{onPick}
{onCreateFork}
createForkCaption="Created when you send your first message."
>
{#snippet trigger()}
<WorkspaceScopeTrigger workspaceId={selectedId} {pendingFork} class="max-w-[16rem]" />
{/snippet}
</WorkspaceFamilyPicker>
</div>
@@ -0,0 +1,84 @@
<script lang="ts">
import { onMount, setContext } from 'svelte'
import AIChat from '$lib/components/copilot/chat/AIChat.svelte'
import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte'
import { goto } from '$lib/navigation'
import { getOrCreateRuntime } from './sessionRuntime.svelte'
import { workspaceStore } from '$lib/stores'
import { loadCopilot } from '$lib/components/copilot/loadCopilot'
import {
getEffectiveWorkspaceId,
getSessionDraftPrompt,
homeStarterSession,
selectSession,
sessionPageHref,
sessionState,
setSessionDraftPrompt
} from './sessionState.svelte'
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
import { takeComposerFocus } from './homeSessionsTransition.svelte'
// Home's block is the empty session's own chat, run by that session's manager: the
// composer, its controls and what a send does are the session's, not a copy of them.
// Picked once; the parent remounts this on a workspace switch, which changes the family.
let { onShown }: { onShown?: () => void } = $props()
const initialSession = homeStarterSession()
const sessionId = initialSession.id
const runtime = getOrCreateRuntime(initialSession)
setContext<AIChatManager>('aiChatManager', runtime.manager)
const session = $derived(sessionState.sessions.find((s) => s.id === sessionId))
const actingWorkspaceId = $derived(
(session ? getEffectiveWorkspaceId(session) : undefined) ?? $workspaceStore ?? undefined
)
const starterPrompts = new StarterPrompts(() => actingWorkspaceId)
// The AI config (models, whether AI is hidden) of the workspace the draft acts on, as the
// session page loads it, so a fork picked here shows its own models and the session page
// can judge it at once on arrival instead of covering it while it asks.
$effect(() => {
if (actingWorkspaceId) loadCopilot(actingWorkspaceId)
})
// The turn is already running on the session's manager; the page it belongs to takes over.
function onSent() {
selectSession(sessionId)
void goto(sessionPageHref(sessionId))
}
function onDraftChange(text: string) {
setSessionDraftPrompt(sessionId, text)
// A prompt typed here is what the AI Sessions switch should open; an empty box leaves
// the switch resuming whatever session the user was last in.
if (text.trim()) selectSession(sessionId)
}
let aiChat: AIChat | undefined = $state(undefined)
onMount(() => {
onShown?.()
if (takeComposerFocus()) setTimeout(() => aiChat?.focusInput(), 0)
})
</script>
{#snippet inputPreface()}
{#if session}
<SessionWorkspaceBar {session} />
{/if}
{/snippet}
{#if session}
<AIChat
bind:this={aiChat}
hideHeader
hideModeSelector
wideLayout
initialInstructions={getSessionDraftPrompt(sessionId)}
{onDraftChange}
starter={{ where: 'home', prompts: starterPrompts.list, chips: starterPrompts.chipsOffered }}
viewTransitionNames
{onSent}
{inputPreface}
/>
{/if}
@@ -6,7 +6,8 @@
setSessionPendingWorkspace,
type Session
} from './sessionState.svelte'
import ActingOnPicker from './ActingOnPicker.svelte'
import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte'
import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte'
let { session }: { session: Session } = $props()
@@ -27,4 +28,17 @@
}
</script>
<ActingOnPicker selectedId={effectiveId} {pendingFork} onPick={pick} onCreateFork={stageFork} />
<div class="flex flex-row items-center gap-1 py-0.5 px-1 text-2xs text-secondary">
<span class="shrink-0">Acting on</span>
<WorkspaceFamilyPicker
selectedId={effectiveId}
{pendingFork}
onPick={pick}
onCreateFork={stageFork}
createForkCaption="Created when you send your first message."
>
{#snippet trigger()}
<WorkspaceScopeTrigger workspaceId={effectiveId} {pendingFork} class="max-w-[16rem]" />
{/snippet}
</WorkspaceFamilyPicker>
</div>
@@ -73,7 +73,14 @@
// Reactive session reference (mutations to summary/target propagate via the $state proxy)
const session = $derived(sessionState.sessions.find((s) => s.id === sessionId))
const starterPrompts = new StarterPrompts()
// Only a session that has never sent opens as the starter block. Read off the record, not
// the transcript: a cold session's history is still loading from storage when it mounts,
// and an empty transcript would show the greeting and then glide the composer away.
// The first send commits the workspace, so this flips only after the transcript has.
const opensSession = $derived(!session?.workspace_id)
const starterPrompts = new StarterPrompts(() =>
opensSession ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined
)
// Seed the composer with the unsent prompt a reload preserved on the session
// record (script-init: AIChatInput reads it once at mount).
@@ -309,6 +316,10 @@
{#if !session || !runtime}
<div class="p-8 text-secondary text-sm">Session not found</div>
{:else}
<!-- A sent session whose transcript is still loading (or came back empty) shows nothing
rather than the docked copilot's keyboard-shortcut hint, which means nothing here. -->
{#snippet sessionEmptyHint()}{/snippet}
{#snippet inputPreface()}
{#if showRecoveryNotice}
<!-- mb-6, not the banner column's mb-1: at that gap it reads as one more
@@ -464,7 +475,15 @@
: session.archived
? 'This session is archived. Unarchive it from the banner above to keep working.'
: ''}
starterPrompts={starterPrompts.list}
starter={opensSession
? {
where: 'session',
prompts: starterPrompts.list,
chips: starterPrompts.chipsOffered
}
: undefined}
viewTransitionNames={headerInPage}
emptyHint={sessionEmptyHint}
{inputPreface}
/>
</div>
@@ -0,0 +1,68 @@
import type { OnNavigate } from '@sveltejs/kit'
// Moving between Home and AI Sessions keeps the session block in sight: the browser
// snapshots the page before and after the navigation and glides each element that
// carries the same `view-transition-name` on both sides (AIChatDisplay names the
// heading and the composer); the rest of the page cross-fades. The timing lives in
// app.css, keyed on the `data-home-sessions-transition` attribute set here for the
// length of the move.
const HOME = '/'
const SESSIONS = '/sessions'
/** Whether the composer had focus when the user left AI Sessions for Home. */
let composerFocused = false
/** The focus flag to keep after a navigation from `from` to `to`. Only the return to Home
* hands focus on — the sessions page focuses its composer on its own — and every other
* navigation clears the flag, so a later arrival on Home never acts on a stale one. */
export function composerFocusAfter(
from: string | undefined,
to: string | undefined,
composerHadFocus: boolean
): boolean {
return from === SESSIONS && to === HOME && composerHadFocus
}
/** Whether Home should give its composer the focus the sessions page's had. Read once:
* a later visit starts unfocused. */
export function takeComposerFocus(): boolean {
const focused = composerFocused
composerFocused = false
return focused
}
/** For SvelteKit's `onNavigate`: runs a move between Home and AI Sessions as a view
* transition. Any other navigation, or a browser without the API, is left alone. */
export function homeSessionsTransition(navigation: OnNavigate): Promise<void> | undefined {
const from = navigation.from?.url.pathname
const to = navigation.to?.url.pathname
composerFocused = composerFocusAfter(
from,
to,
document.activeElement?.closest('[data-session-composer]') != null
)
const direction =
from === HOME && to === SESSIONS
? 'enter'
: from === SESSIONS && to === HOME
? 'leave'
: undefined
if (!direction || navigation.willUnload || !document.startViewTransition) return
const root = document.documentElement
// Reduced motion keeps the transition but drops every name, so the two pages simply
// cross-fade as one.
root.dataset.homeSessionsTransition = window.matchMedia('(prefers-reduced-motion: reduce)')
.matches
? 'fade'
: direction
return new Promise((resolve) => {
const transition = document.startViewTransition(async () => {
resolve()
await navigation.complete
})
// Rejects when the navigation is cancelled or fails; the attribute goes either way.
const done = () => delete root.dataset.homeSessionsTransition
void transition.finished.then(done, done)
})
}
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest'
import { composerFocusAfter } from './homeSessionsTransition.svelte'
describe('composerFocusAfter', () => {
it('hands focus on only for the return from AI Sessions to Home', () => {
expect(composerFocusAfter('/sessions', '/', true)).toBe(true)
expect(composerFocusAfter('/sessions', '/', false)).toBe(false)
// Going to AI Sessions: that page focuses its own composer, so nothing is kept for Home.
expect(composerFocusAfter('/', '/sessions', true)).toBe(false)
// Any other navigation clears it, so a later arrival on Home never reads a stale flag.
expect(composerFocusAfter('/sessions', '/runs', true)).toBe(false)
expect(composerFocusAfter('/runs', '/', true)).toBe(false)
})
})
@@ -58,6 +58,7 @@ import {
setSessionPreviewCollapsed,
setSessionPreviewSize,
setSessionTabs,
setDraftsDiscardedHandler,
type Session
} from './sessionState.svelte'
import {
@@ -306,6 +307,7 @@ export interface SessionRuntime {
}
const runtimes = new SvelteMap<string, SessionRuntime>()
const runtimeRoots = new Map<string, () => void>()
function emptyFlow(): Flow {
return {
@@ -1329,7 +1331,18 @@ async function initRuntime(runtime: SessionRuntime, session: Session) {
export function getOrCreateRuntime(session: Session): SessionRuntime {
let runtime = runtimes.get(session.id)
if (!runtime) {
runtime = createRuntime(session)
// The manager's `$derived` fields belong to whatever effect is running when they are
// built. A runtime outlives the component that first asked for it (Home hands its
// session to /sessions and unmounts), so give it a root of its own; built inside the
// component, its deriveds turn inert once that component is gone.
let created: SessionRuntime | undefined
runtimeRoots.set(
session.id,
$effect.root(() => {
created = createRuntime(session)
})
)
runtime = created!
runtimes.set(session.id, runtime)
// The gate opens even when the restore fails: a session that cannot read its
// history is still usable, and a send that waits forever is not.
@@ -1346,6 +1359,8 @@ export function disposeRuntime(sessionId: string) {
runtime.manager.cancel('runtime disposed')
runtime.manager.historyManager.close()
runtimes.delete(sessionId)
runtimeRoots.get(sessionId)?.()
runtimeRoots.delete(sessionId)
// The sidebar reads the stored chat again rather than trust a read that
// predates everything this runtime saw.
peeks.delete(sessionId)
@@ -1474,6 +1489,8 @@ export function removeSession(sessionId: string): void {
deleteSessionState(sessionId)
}
setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime))
// The chat calls a new item by its chosen name while its draft is stored at
// `draft_<uuid>`; resolve the name the way the chat's write tools do.
function draftStoragePath(
@@ -1051,29 +1051,6 @@ export function findEmptyLandingSession(): Session | undefined {
)
}
/** The workspace a new session starts on, before the user picks another. */
export function defaultSessionWorkspace(): string | undefined {
// Start in the workspace you're in. The one exception: a root you can't
// deploy to (locked, no bypass) steers to its dev, since a session there
// couldn't edit anything. The picker lets you switch.
const currentWs = get(workspaceStore)
const devOfCurrent = currentWs
? findCanonicalDevWorkspace(currentWs, get(userWorkspaces))?.id
: undefined
// Only trust the deploy check once the active workspace's rules have actually loaded: until then
// `isRuleActive` reads an empty ruleset and fails open, which would default a new session onto a
// locked prod. Treat "not yet loaded for currentWs" as not-deployable so we steer to the dev (always
// editable) when one exists; the picker still lets the user switch back once rules resolve.
const rulesLoadedForCurrent =
protectionRulesState.rulesets !== undefined && protectionRulesState.workspace === currentWs
const canDeployHere =
rulesLoadedForCurrent &&
(!isRuleActive('DisableDirectDeployment') ||
canUserBypassRuleKind('DisableDirectDeployment', get(userStore)))
const pending = devOfCurrent && !canDeployHere ? devOfCurrent : currentWs
return pending && pending.length > 0 ? pending : undefined
}
export function createSession(): Session {
// Reuse an existing untouched draft from the active family rather than pile a
// blank entry on every `+`, so several pending sessions can still be built up
@@ -1093,8 +1070,42 @@ export function createSession(): Session {
requestComposerFocus()
return reusable
}
const session = newTransientSession()
sessionState.currentSessionId = session.id
return session
}
// Told which never-touched drafts were dropped, so their runtimes go with them. Set by
// sessionRuntime, which imports this module and so cannot be imported back. Home builds a
// runtime for its draft on every mount, so a dropped draft would otherwise leave its
// manager and its history database handle open.
let onDraftsDiscarded: ((ids: string[]) => void) | undefined
export function setDraftsDiscardedHandler(handler: (ids: string[]) => void): void {
onDraftsDiscarded = handler
}
function newTransientSession(): Session {
const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id)
sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s))
const pending = defaultSessionWorkspace()
if (discarded.length > 0) onDraftsDiscarded?.(discarded)
// Start in the workspace you're in. The one exception: a root you can't
// deploy to (locked, no bypass) steers to its dev, since a session there
// couldn't edit anything. The picker lets you switch.
const currentWs = get(workspaceStore)
const devOfCurrent = currentWs
? findCanonicalDevWorkspace(currentWs, get(userWorkspaces))?.id
: undefined
// Only trust the deploy check once the active workspace's rules have actually loaded: until then
// `isRuleActive` reads an empty ruleset and fails open, which would default a new session onto a
// locked prod. Treat "not yet loaded for currentWs" as not-deployable so we steer to the dev (always
// editable) when one exists; the picker still lets the user switch back once rules resolve.
const rulesLoadedForCurrent =
protectionRulesState.rulesets !== undefined && protectionRulesState.workspace === currentWs
const canDeployHere =
rulesLoadedForCurrent &&
(!isRuleActive('DisableDirectDeployment') ||
canUserBypassRuleKind('DisableDirectDeployment', get(userStore)))
const pending = devOfCurrent && !canDeployHere ? devOfCurrent : currentWs
// Friendly default summary so the header reads like "Zippy session"
// rather than "Untitled session" — assigned at create time, the user
// can still rename it (or it gets overwritten by an editor target).
@@ -1104,17 +1115,37 @@ export function createSession(): Session {
id: createLongHash(),
summary,
summarySource: 'placeholder',
pending_workspace_id: pending,
pending_workspace_id: pending && pending.length > 0 ? pending : undefined,
createdAt: Date.now(),
transient: true
}
sessionState.sessions = [session, ...sessionState.sessions]
sessionState.currentSessionId = session.id
// Transient until first touch: no DB record yet. Persisting is deferred to the
// first user edit (the mutation helpers below route through persistTouched).
return session
}
/** The unsent session Home's composer writes into, so a prompt half-typed on Home is the
* one the empty session page shows, and the reverse. Never selects it: merely opening Home
* must not change which session the AI Sessions switch resumes. A session opened on an
* item (it carries preview tabs) is about that item, so Home starts its own instead. */
export function homeStarterSession(): Session {
const unsent = (s: Session) =>
!s.archived && !s.workspace_id && !s.previewTabs?.length && sessionInCurrentFamily(s)
const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId)
if (current && unsent(current)) return current
// Stored but never sent: a draft the user touched, by typing or by picking where it acts.
// Either is theirs to come back to, and leaving it would strand it in the sidebar.
const touched = sessionState.sessions
.filter((s) => unsent(s) && !s.transient)
.sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0]
return (
touched ??
sessionState.sessions.find((s) => isDiscardableDraft(s) && sessionInCurrentFamily(s)) ??
newTransientSession()
)
}
// Promote an in-memory transient session to a persisted IndexedDB record.
// No-op when the session isn't transient (already persisted by a prior touch).
// Called on the first genuine user touch (via persistTouched) and, idempotently,
@@ -5,9 +5,11 @@ import {
createSession,
decideSessionLifecycle,
findEmptyLandingSession,
homeStarterSession,
isForkSession,
isTearingDownOpenSession,
renameSession,
setDraftsDiscardedHandler,
sessionInCurrentFamily,
setGeneratedSessionSummary,
setSessionDraftPrompt,
@@ -674,3 +676,64 @@ describe('withOpenSessionTeardown — the gate that holds recovery off during a
expect(isTearingDownOpenSession()).toBe(false)
})
})
describe('homeStarterSession', () => {
it("shows the family's stored draft, not the conversation in view, and selects nothing", () => {
const restore = withTwoFamilies('rootA')
const prevCurrent = sessionState.currentSessionId
const conversation = session({ id: 'conversation', workspace_id: 'rootA' })
// Touched only by picking where it acts: no text, but stored, so it is the user's draft.
const picked = session({ id: 'picked-draft', pending_workspace_id: 'forkA', lastActivityAt: 2 })
const otherFamily = session({
id: 'other-family-draft',
pending_workspace_id: 'rootB',
draftPrompt: 'elsewhere',
lastActivityAt: 3
})
sessionState.sessions.push(conversation, picked, otherFamily)
sessionState.currentSessionId = 'conversation'
try {
expect(homeStarterSession().id).toBe('picked-draft')
// Opening Home must leave the AI Sessions switch resuming the conversation.
expect(sessionState.currentSessionId).toBe('conversation')
} finally {
sessionState.sessions = sessionState.sessions.filter(
(s) => !['conversation', 'picked-draft', 'other-family-draft'].includes(s.id)
)
sessionState.currentSessionId = prevCurrent
restore()
}
})
it('reports the never-touched drafts it drops, so their runtimes can be disposed', () => {
const restore = withTwoFamilies('rootB')
const prevCurrent = sessionState.currentSessionId
const blank = session({
id: 'blank-other-family',
pending_workspace_id: 'forkA',
transient: true
})
const typed = session({
id: 'typed-other-family',
pending_workspace_id: 'rootA',
draftPrompt: 'kept'
})
sessionState.sessions.push(blank, typed)
const discarded: string[][] = []
setDraftsDiscardedHandler((ids) => discarded.push(ids))
let createdId: string | undefined
try {
// No draft of family B exists, so Home starts one, dropping family A's blank draft.
createdId = homeStarterSession().id
expect(discarded).toEqual([['blank-other-family']])
expect(sessionState.sessions.some((s) => s.id === 'typed-other-family')).toBe(true)
} finally {
setDraftsDiscardedHandler(() => {})
sessionState.sessions = sessionState.sessions.filter(
(s) => !['blank-other-family', 'typed-other-family', createdId].includes(s.id)
)
sessionState.currentSessionId = prevCurrent
restore()
}
})
})
@@ -10,16 +10,13 @@ import {
sessionState,
setSessionAutoSend,
setSessionDraftPrompt,
setSessionPendingFork,
setSessionPendingWorkspace,
type PendingFork,
type Session,
type SessionTarget
} from './sessionState.svelte'
import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte'
import { parsePipelineRoute, parsePreviewItemRoute } from './previewPaths'
import { findMountedOpenInSessionSource } from './openInSessionContext'
import type { AIAutonomyMode } from '../copilot/chat/AIChatManager.svelte'
// Type-only: erased at compile time, so the component graph stays out of this
// navigation seam (see the dynamic import in openEditorInSession).
import type { OpenInSessionSource } from './OpenInSessionButton.svelte'
@@ -271,33 +268,14 @@ export async function openSourceInSession(
// global search's "Ask AI"). Always a new session rather than the most recent
// one (`enterSessionMode`), so the seed cannot overwrite a prompt the user has
// already typed into a session they are mid-way through.
//
// `actingOn` and `autonomyMode` carry what the entry point's own controls picked
// (Home's composer); without them the session keeps createSession's workspace and
// the user's persisted autonomy mode.
export async function startSessionWithPrompt(
prompt: string,
opts?: {
autoSend?: boolean
actingOn?: { workspaceId: string; fork?: PendingFork }
autonomyMode?: AIAutonomyMode
}
opts?: { autoSend?: boolean }
): Promise<void> {
// Without `actingOn`, no setSessionPendingWorkspace: createSession already picked
// the workspace, steering off a root the user cannot deploy to onto its dev.
// Overwriting it with the raw current workspace would land the session where it
// cannot edit.
// No setSessionPendingWorkspace: createSession already picked the workspace,
// steering off a root the user cannot deploy to onto its dev. Overwriting it
// with the raw current workspace would land the session where it cannot edit.
const session = createSession()
const actingOn = opts?.actingOn
if (actingOn?.fork) setSessionPendingFork(session.id, actingOn.fork)
else if (actingOn && actingOn.workspaceId !== session.pending_workspace_id)
setSessionPendingWorkspace(session.id, actingOn.workspaceId)
if (opts?.autonomyMode) {
// Set on the session's own manager before the page mounts it: plan mode is
// never persisted, so it cannot ride the stored preference across the hand-off.
const { getOrCreateRuntime } = await import('./sessionRuntime.svelte')
getOrCreateRuntime(session).manager.setAutonomyMode(opts.autonomyMode)
}
setSessionDraftPrompt(session.id, prompt)
// An empty prompt has nothing to send; leave the composer focused instead.
if (opts?.autoSend && prompt.trim()) setSessionAutoSend(session.id)
@@ -57,7 +57,8 @@
type UserWorkspace
} from '$lib/stores'
import CenteredModal from '$lib/components/CenteredModal.svelte'
import { afterNavigate, beforeNavigate } from '$app/navigation'
import { afterNavigate, beforeNavigate, onNavigate } from '$app/navigation'
import { homeSessionsTransition } from '$lib/components/sessions/homeSessionsTransition.svelte'
import { goto } from '$lib/navigation'
import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte'
import type UserSettings from '$lib/components/UserSettings.svelte'
@@ -444,6 +445,8 @@
return kind ? { kind, path: route.itemPath } : undefined
}
onNavigate(homeSessionsTransition)
beforeNavigate((navigation) => {
if (preserveMenuOnNextNav) {
preserveMenuOnNextNav = false
@@ -97,6 +97,12 @@
// the mount animation below never covers. Replay it by hand instead of keying the page on the
// workspace: a remount would drop the list's own state and refetch what it is already loading.
let pageEl: HTMLDivElement | undefined = $state(undefined)
// Back from AI Sessions the view transition (homeSessionsTransition.svelte.ts) carries the arrival, so
// the page skips its own fade-in. Decided once at mount: gating the class on the attribute
// instead would start the fade from transparent the moment the transition removes it.
const fadeIn =
typeof document === 'undefined' || !document.documentElement.dataset.homeSessionsTransition
const reducedMotion = useReducedMotion()
let animatedWorkspace = $workspaceStore
$effect(() => {
@@ -285,7 +291,7 @@
<div
bind:this={pageEl}
class="wm-page-in flex flex-col w-full h-full overflow-y-auto items-center"
class="{fadeIn ? 'wm-page-in' : ''} flex flex-col w-full h-full overflow-y-auto items-center"
style="scrollbar-gutter: stable both-edges;"
>
<!-- Where edits to this workspace are made is a fact about the workspace, so it sits in the
@@ -1,3 +1,13 @@
<script lang="ts" module>
import { SvelteMap } from 'svelte/reactivity'
// AI-hidden verdicts already read, by workspace, for the whole page load: arriving from Home
// or switching back to a workspace is judged at once, while a fresh read still runs and
// replaces the verdict when it lands. Kept outside the page, which remounts on every
// arrival, so the switch from Home does not land on the full-page loader.
const knownAiHidden = new SvelteMap<string, boolean>()
</script>
<script lang="ts">
import { onDestroy, onMount, tick, untrack } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
@@ -45,6 +55,7 @@
import { enterSessionMode } from '$lib/components/sessions/sessionSwitch.svelte'
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
import {
getOrCreateRuntime,
getRuntime,
@@ -344,6 +355,7 @@
}
// The generated client can't take an abort signal, so drop a superseded response here.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
knownAiHidden.set(workspace, hidden)
return { workspace, hidden }
}
)
@@ -351,8 +363,18 @@
// landed yet.
const aiHiddenVerdict = $derived.by(() => {
const current = workspaceAiHidden.current
return current && current.workspace === previewWorkspace ? current.hidden : undefined
if (current && current.workspace === previewWorkspace) return current.hidden
if (!previewWorkspace) return undefined
const known = knownAiHidden.get(previewWorkspace)
if (known !== undefined) return known
// The AI config already loaded for this very workspace (by Home, on the way here) carries
// the same flag. Tagged with its workspace, so it is never another workspace's verdict.
return $copilotWorkspace === previewWorkspace ? $copilotInfo.workspaceDisabled : undefined
})
// The full loader is for the page load's first verdict only. Later, picking another workspace
// in "Acting on" leaves the session on screen, inert until its verdict lands: covering
// it for the length of a request reads as the whole page reloading.
const firstVerdictPending = $derived(aiHiddenVerdict === undefined && knownAiHidden.size === 0)
// Lazy-mount gate: a tab's content only renders once its key lands here (on
// first activation) — so restoring a session with N saved tabs boots just
@@ -1269,7 +1291,7 @@
</Pane>
</Splitpanes>
</div>
{#if aiHiddenVerdict === undefined}
{#if firstVerdictPending}
<div class="absolute inset-0 z-20 flex items-center justify-center bg-surface">
<Loader2 class="animate-spin" />
</div>