feat: one home for the workspace and AI sessions

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-22 05:07:07 -07:00
co-authored by Claude Opus 5.5
parent 34de8bc06d
commit 1ba8d1f294
33 changed files with 722 additions and 1505 deletions
+5 -31
View File
@@ -427,45 +427,19 @@ input[type='time']::-webkit-calendar-picker-indicator {
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 (the spacer under AIChatDisplay's composer) both
read it. */
:root {
--composer-glide-duration: 380ms;
--composer-glide-easing: cubic-bezier(0.2, 0.8, 0.2, 1);
}
/* Home ↔ AI Sessions (homeSessionsTransition.svelte.ts). The composer glides from where it
was to where it lands; everything else, Home's list and the session's greeting included, is
the page cross-fading, kept short. The pseudo-elements hang off :root itself, so no space
/* Home → AI Sessions on a send from Home (homeSessionsTransition.svelte.ts). The composer
glides from where it was to where it lands; 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(composer) {
animation-duration: var(--composer-glide-duration);
animation-timing-function: var(--composer-glide-easing);
animation-duration: 380ms;
animation-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1);
}
:root[data-home-sessions-transition]::view-transition-old(root),
:root[data-home-sessions-transition]::view-transition-new(root) {
animation-duration: 150ms;
}
/* The session's greeting sits above where the composer lands, so it waits for the composer:
shown while the composer is still gliding, it reads as text placed in mid-air. It starts as
the composer settles and rises into place on the same easing, so the two read as one motion.
Leaving, it goes with the page. */
:root[data-home-sessions-transition='enter']::view-transition-new(greeting) {
animation: greeting-in 260ms var(--composer-glide-easing)
calc(var(--composer-glide-duration) * 0.6) both;
}
:root[data-home-sessions-transition]::view-transition-old(greeting) {
animation-duration: 150ms;
}
@keyframes greeting-in {
from {
opacity: 0;
transform: translateY(4px);
filter: blur(2px);
}
}
:root[data-home-sessions-transition='fade'] * {
view-transition-name: none !important;
}
@@ -23,7 +23,6 @@
viewTransitionNames = false,
onSent = undefined,
inputPreface,
actingOn,
initialInstructions = undefined,
onDraftChange = undefined,
initialAttachments = undefined,
@@ -47,8 +46,6 @@
viewTransitionNames?: boolean
onSent?: () => void
inputPreface?: import('svelte').Snippet
/** Forwarded to AIChatDisplay: where the session acts, first among the controls. */
actingOn?: import('svelte').Snippet
// Seed / observe the composer's draft (forwarded to AIChatDisplay).
initialInstructions?: string
onDraftChange?: (text: string) => void
@@ -223,7 +220,6 @@
{viewTransitionNames}
{onSent}
{inputPreface}
{actingOn}
{initialInstructions}
{onDraftChange}
{initialAttachments}
@@ -69,7 +69,6 @@
import { sendUserToast } from '$lib/toast'
import Alert from '$lib/components/common/alert/Alert.svelte'
import { copilotInfo } from '$lib/aiStore'
import SessionGreeting from './starter/SessionGreeting.svelte'
import ComposerSuggestions from './starter/ComposerSuggestions.svelte'
import type { DraftAttachments } from './messageDraft.svelte'
import type { ChatStarter } from './starter/starterPrompts.svelte'
@@ -117,7 +116,6 @@
viewTransitionNames = false,
onSent = undefined,
inputPreface,
actingOn,
footerSettings,
initialInstructions = undefined,
onDraftChange = undefined,
@@ -151,20 +149,16 @@
// off there.
wideLayout?: boolean
emptyHint?: Snippet
/** 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`. */
/** Open an empty chat as the block that starts a session: Home's composer, collapsed
* to one line at rest. Replaces `emptyHint`. */
starter?: ChatStarter
/** Names the composer for the view transition between Home and AI Sessions, so it
* glides between its two places, a send from Home included: that lands it under the
* session's first message. Only one chat on the page may carry the name: a duplicate
* makes the browser skip the transition. */
/** Names the composer for the view transition of a send from Home, so it glides from
* Home to its place under the session's first message. Only one chat on the page may
* carry the name: a duplicate makes the browser skip the transition. */
viewTransitionNames?: boolean
/** After the composer hands a new turn to the host. */
onSent?: () => void
inputPreface?: Snippet
/** Where the session acts: first among the controls after the attach button. */
actingOn?: 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. */
footerSettings?: Snippet
@@ -587,8 +581,6 @@
// The block's layout holds while the chat is empty, usable or not; only the taller box
// and the suggestions need a composer that can send.
const starterLayout = $derived(!!starter && messages.length === 0)
// Home is a page, not a pane: nothing there to centre in.
const centreComposer = $derived(starterLayout && starter?.where === 'session')
// Home's composer at rest is one line. Focusing the field opens it; a press outside it or
// Escape puts it back, but only with nothing in the draft: leaving it open then means
@@ -597,7 +589,6 @@
// menu it is opening.
let composerEl: HTMLDivElement | undefined = $state()
let composerOpened = $state(false)
const homeComposer = $derived(starterLayout && starter?.where === 'home')
// Anything the user has started (text, an attachment) or is in the middle of (they opened it
// and have not left) keeps it open, and so does a workspace small enough that the composer is
// the page's main way in.
@@ -612,9 +603,9 @@
!initialAttachments?.blobs.length
)
const composerCollapsed = $derived(
homeComposer &&
starterLayout &&
!disabled &&
!(starter?.where === 'home' && starter.fewItems) &&
!starter?.fewItems &&
!composerOpened &&
(aiChatInput ? aiChatInput.isDraftEmpty() : seededDraftEmpty)
)
@@ -622,13 +613,13 @@
if (aiChatInput?.isDraftEmpty() ?? true) composerOpened = false
}
function onComposerPointerDown(e: PointerEvent) {
if (!homeComposer || !composerOpened || composerEl?.contains(e.target as Node)) return
if (!starterLayout || !composerOpened || composerEl?.contains(e.target as Node)) return
if (!isComposerOverlay(e.target)) closeComposer()
}
// Home's composer is one block of the page and takes the page's column as it is.
const columnClass = $derived(
starter?.where === 'home'
starter
? 'w-full'
: wideLayout
? `w-full max-w-3xl mx-auto ${agentGutter ? 'px-8' : 'px-7'}`
@@ -688,7 +679,6 @@
const showFooterLeftControls = $derived(
!footerMessageShown &&
(canAttachFiles ||
!!actingOn ||
attachmentsOffReason !== undefined ||
showContextPicker ||
showAutonomyModeSelector ||
@@ -739,7 +729,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 {starterLayout ? 'justify-center' : ''}"
class="flex flex-col h-full relative outline-none"
tabindex="-1"
bind:this={panelEl}
ondragenter={onPanelDragEnter}
@@ -849,19 +839,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/if}
{#if messages.length === 0}
{#if starter}
<!-- 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. Home
has none: there the composer is one control among the page's. -->
{#if centreComposer}
<div class="flex-1 min-h-0 flex flex-col justify-end">
<div
class={columnClass}
style:view-transition-name={viewTransitionNames ? 'greeting' : undefined}
>
<SessionGreeting />
</div>
</div>
{/if}
<!-- Home's composer is one control among the page's: nothing above it. -->
{:else if emptyHint}
{@render emptyHint()}
{:else}
@@ -994,12 +972,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
class="relative {columnClass} pb-2"
style:view-transition-name={viewTransitionNames ? 'composer' : undefined}
onfocusin={(e) => {
if (homeComposer && e.target instanceof HTMLTextAreaElement) composerOpened = true
if (starterLayout && e.target instanceof HTMLTextAreaElement) composerOpened = true
}}
onkeydown={(e) => {
// A prevented Escape closed something inside first, such as the @-mention picker.
if (e.key !== 'Escape' || e.defaultPrevented) return
if (!homeComposer || !composerOpened) return
if (!starterLayout || !composerOpened) return
closeComposer()
if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur()
}}
@@ -1067,7 +1045,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
isFirstMessage={messages.length === 0}
hero={starterLayout}
collapsed={composerCollapsed}
chatIcon={homeComposer}
chatIcon={starterLayout}
{onSent}
>
{#snippet collapsedControls()}
@@ -1267,7 +1245,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
onchange={onFolderInputChange}
/>
{/if}
{@render actingOn?.()}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
@@ -1316,13 +1293,8 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
{#if footerMessageShown}
<!-- The workspace picker stays: picking another workspace is how a chat that
cannot run here becomes usable again. -->
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
{@render actingOn?.()}
<div class="text-primary text-xs my-2 px-2">
<Markdown md={disabledMessage} />
</div>
<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">
@@ -1402,7 +1374,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
<div class="pt-2">
<ComposerSuggestions
suggestions={starter.suggestions}
wrap={starter.where === 'session'}
onPick={(prompt) => aiChatInput?.setText(prompt)}
/>
</div>
@@ -1426,12 +1397,4 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
</div>
<!-- Equal to the space above while the session is empty, so the composer sits centred.
Always mounted and shrunk on the first message rather than removed: flex-grow
transitions, so the composer slides down to the bottom instead of jumping. -->
<div
class="min-h-0 basis-0 transition-[flex-grow] duration-[var(--composer-glide-duration)] ease-[var(--composer-glide-easing)] motion-reduce:transition-none {centreComposer
? 'grow'
: 'grow-0'}"
></div>
</div>
@@ -5,22 +5,17 @@
let {
suggestions,
onPick,
wrap = false
onPick
}: {
suggestions: ComposerSuggestion[]
onPick: (prompt: string) => void
/** Wrap onto more lines instead of one row that scrolls sideways. */
wrap?: boolean
} = $props()
</script>
<!-- Unwrapped, one row whatever the width: it scrolls sideways and fades out at its end, so the
page under the composer does not move with the window width. -->
<!-- One row whatever the width: it scrolls sideways and fades out at its end, so the page under
the composer does not move with the window width. -->
<div
class="flex flex-row items-center gap-1.5 {wrap
? 'flex-wrap'
: 'overflow-x-auto no-scrollbar [mask-image:linear-gradient(90deg,#000_calc(100%-24px),transparent)]'}"
class="flex flex-row items-center gap-1.5 overflow-x-auto no-scrollbar [mask-image:linear-gradient(90deg,#000_calc(100%-24px),transparent)]"
>
{#each suggestions.slice(0, 4) as suggestion (suggestion.label)}
<Button
@@ -1,28 +0,0 @@
<script lang="ts">
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>
</div>
@@ -1,41 +0,0 @@
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)
})
})
@@ -1,37 +0,0 @@
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'
}
@@ -144,9 +144,6 @@ async function fetchItemCount(workspace: string): Promise<number> {
return count
}
/** What turns an empty chat into the block that starts a session. */
export type ChatStarter = { suggestions: ComposerSuggestion[] } & (
| /** An empty session centres the block in the pane under a greeting. */
{ where: 'session' } /** Home shows it alone, collapsed to one line at rest unless `fewItems`. */
| { where: 'home'; fewItems: boolean }
)
/** What turns an empty chat into Home's block that starts a session, collapsed to one line at
* rest unless `fewItems`. */
export type ChatStarter = { suggestions: ComposerSuggestion[]; fewItems: boolean }
@@ -16,10 +16,11 @@
import CloseButton from '../common/CloseButton.svelte'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { hubBaseUrlStore, roleCapabilities, workspaceStore } from '$lib/stores'
import { sessionState } from '../sessions/sessionState.svelte'
import { homeDraft, sessionState } from '../sessions/sessionState.svelte'
import { homeSidebarList } from '../sessions/sidebarList.svelte'
import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte'
import { HOME_SHOW_HUB } from '$lib/consts'
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
import { homeComposerPin, setHomeComposerRemoved } from './homeComposerPin.svelte'
import { isRuleActive, protectionRulesState } from '$lib/workspaceProtectionRules.svelte'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
import { BROWSER } from 'esm-env'
@@ -36,8 +37,6 @@
import { useWorkspaceAiHidden } from '../copilot/workspaceAiHidden.svelte'
import { homeQuickAccessSettings } from './homeQuickAccessSettings.svelte'
const COLLAPSED_SETTING = 'home-ai-composer-collapsed'
/** Bar width from which the two side trips stand in the bar rather than folding into the menu.
* Home's trail is ~250px and the rest of its actions ~400, so this leaves room for both
* labelled buttons without the trail starting to truncate. Below it they fold back. */
@@ -47,14 +46,9 @@
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
// Whether this reader wants the composer on the home page at all, so it lives per browser
// rather than per workspace or account. It has nothing to do with the composer's one-line
// state despite the key's name; renaming the key would reset every reader's choice.
let removed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true')
function setRemoved(next: boolean) {
removed = next
storeLocalSetting(COLLAPSED_SETTING, next ? 'true' : undefined)
}
// Whether this reader wants the composer on the home page at all. Starting a session puts
// it back (see pinHomeComposer).
const removed = $derived(homeComposerPin.removed)
// Removing puts the composer away rather than throwing it out, and the way back is one item in
// the band's menu — so the ellipsis flashes as it appears, in a corner nobody is watching while
@@ -72,7 +66,7 @@
function removeComposer() {
// The `close` key keeps these events in the series they have always been counted in.
logFeatureUsage('home', 'ai_hero_remove', { key: 'close' })
setRemoved(true)
setHomeComposerRemoved(true)
if (reducedMotion.val) return
clearTimeout(pulseEndTimer)
pulsing = true
@@ -80,16 +74,15 @@
}
// 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
// lock outright, yet neither makes prod the place to start one. Unresolved rules read as
// unlocked, so the far commoner unlocked workspace never pops the composer in mid-load.
// the composer and the button to reopen it. This is about the workspace, not the caller: an
// admin bypasses the lock outright, yet that does not make prod the place to start a session.
// Unresolved rules read as 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.
// So the block waits for the rules before it mounts: mounted before them, a locked workspace
// would show its composer until they arrived. 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
@@ -102,16 +95,20 @@
// rather than once the code has loaded, it is no extra wait.
if ($workspaceStore) prefetchItemCount($workspaceStore)
// Whether Home's own workspace hides the assistant, read for that workspace: once the block
// shows, the shared copilot config 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.
// Whether Home's own workspace hides the assistant, read for that workspace rather than from
// the shared copilot config, which still describes the last session's workspace for a moment
// after leaving its page.
const homeAiHidden = useWorkspaceAiHidden(() => $workspaceStore ?? undefined)
// The composer hands off to /sessions, which refuses roles that cannot code 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.
// The composer hands off to /sessions, which refuses roles that cannot code, users opted out
// of the sessions beta and a session's own preview frame — so hide it there (the prompt would
// be silently dropped) while the AI-independent CLI/MCP row below stays.
const inPreviewFrame = BROWSER && window.self !== window.top
let showComposer = $derived(
prefersSessionHandoff(!$roleCapabilities.code) && !runOnlyWorkspace && !homeAiHidden.hidden
prefersSessionHandoff(!$roleCapabilities.code) &&
!inPreviewFrame &&
!runOnlyWorkspace &&
!homeAiHidden.hidden
)
let hero = $derived(showComposer && !removed)
@@ -133,15 +130,21 @@
</div>
<!-- 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. -->
fork shares its parent's, and remounting for it only flashes the block. Also keyed
on the asks for another draft (New session, a draft picked in the session list). -->
{#if HomeSessionStarter && sessionState.hydrated && (rulesReady || shownForRoot === $currentWorkspaceRootId)}
{#key $currentWorkspaceRootId}
<HomeSessionStarter
onShown={() => (shownForRoot = $currentWorkspaceRootId)}
{placeholder}
onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)}
/>
{/key}
<!-- Going into the composer is going to the AI side, so the sidebar lists sessions,
where the one sent from here opens. Nothing may focus the composer unasked (Home's
search holds the page's first focus), or every visit would flip the list. -->
<div class="contents" onfocusin={() => (homeSidebarList.val = 'sessions')}>
{#key `${$currentWorkspaceRootId}:${homeDraft.requests}`}
<HomeSessionStarter
onShown={() => (shownForRoot = $currentWorkspaceRootId)}
{placeholder}
onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)}
/>
{/key}
</div>
{:else}
{@render placeholder()}
{/if}
@@ -237,7 +240,7 @@
displayName: 'Pin session hero to homepage',
action: () => {
logFeatureUsage('home', 'ai_hero_pin')
setRemoved(false)
setHomeComposerRemoved(false)
}
}
]
@@ -0,0 +1,21 @@
import { BROWSER } from 'esm-env'
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
// Whether this reader put the composer away from the home page, so it lives per browser
// rather than per workspace or account. It has nothing to do with the composer's one-line
// state despite the key's name; renaming the key would reset every reader's choice.
const REMOVED_SETTING = 'home-ai-composer-collapsed'
export const homeComposerPin = $state({
removed: BROWSER && getLocalSetting(REMOVED_SETTING) === 'true'
})
export function setHomeComposerRemoved(removed: boolean): void {
homeComposerPin.removed = removed
storeLocalSetting(REMOVED_SETTING, removed ? 'true' : undefined)
}
/** Starting a session asks for the composer: it is the only place one is typed. */
export function pinHomeComposer(): void {
if (homeComposerPin.removed) setHomeComposerRemoved(false)
}
@@ -1,32 +1,31 @@
<script lang="ts">
import { onMount, setContext, type Snippet } from 'svelte'
import AIChat from '$lib/components/copilot/chat/AIChat.svelte'
import type { DraftAttachments } from '$lib/components/copilot/chat/messageDraft.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 { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot'
import { copilotWorkspace } from '$lib/aiStore'
import {
getEffectiveWorkspaceId,
getSessionDraftAttachments,
getSessionDraftPrompt,
holdHomeDraft,
homeStarterSession,
setSessionDraftAttachments,
selectSession,
sessionPageHref,
sessionState,
setSessionDraftPrompt
setSessionDraftPrompt,
takeHomeDraftFocus
} from './sessionState.svelte'
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
import { composerSentFromHome, takeComposerFocus } from './homeSessionsTransition.svelte'
import { composerSentFromHome } from './homeSessionsTransition.svelte'
import { homeComposerContext } from './homeComposerContext.svelte'
// Home's block is the empty session's own chat, run by that session's manager: the
// Home's block is the unsent 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.
// Picked once; the parent remounts this on a workspace family switch and whenever
// another draft is asked for (New session, a draft picked in the session list).
// `placeholder` stands in while the chat waits on its config; `onSettled` reports the height
// the chat first took, for the next placeholder to take.
let {
@@ -38,24 +37,13 @@
const initialSession = homeStarterSession()
const sessionId = initialSession.id
holdHomeDraft(sessionId)
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. The layout also
// loads Home's own workspace into the same shared config, and the last request wins, so
// this asks again whenever a later request named another workspace.
$effect(() => {
if (actingWorkspaceId && $copilotWorkspaceRequested !== actingWorkspaceId)
loadCopilot(actingWorkspaceId)
})
// The draft acts on the workspace the page header names: holdHomeDraft keeps it there.
const starterPrompts = new StarterPrompts(() => $workspaceStore ?? undefined)
// The turn is already running on the session's manager; the page it belongs to takes over.
function onSent() {
@@ -64,19 +52,13 @@
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)
}
function onAttachmentsChange(attachments: DraftAttachments) {
setSessionDraftAttachments(sessionId, attachments)
if (Object.values(attachments).some((lane) => lane.length > 0)) selectSession(sessionId)
}
// Asked for with the draft, and taken once the chat is there: it mounts only after a config
// has loaded, and this block can remount meanwhile (a workspace switch reloads both).
let aiChat: AIChat | undefined = $state(undefined)
function bindChat(chat: AIChat | undefined) {
aiChat = chat
if (chat && takeHomeDraftFocus()) setTimeout(() => chat.focusInput(), 0)
}
let chatWrapper: HTMLDivElement | undefined = $state(undefined)
// A seeded draft holds the composer open, which is not the shape it rests in once the
// draft is sent, so only a mount with an empty draft is measured.
@@ -92,7 +74,6 @@
})
onMount(() => {
onShown?.()
if (takeComposerFocus()) setTimeout(() => aiChat?.focusInput(), 0)
// The rows' "Ask AI" lands here. Before the chat has mounted (its config still
// loading) there is nowhere to put the item, and the attach does nothing.
return homeComposerContext.register(async (element) => {
@@ -101,12 +82,6 @@
})
</script>
{#snippet actingOn()}
{#if session}
<SessionWorkspaceBar {session} switchesWorkspace />
{/if}
{/snippet}
<!-- Until a config has loaded the chat reads "AI not configured" and would flash its disabled
state. Any loaded config will do, so a fork switch does not hide it while the fork's loads.
The item count decides whether the composer rests collapsed, so it waits for that too
@@ -114,22 +89,17 @@
{#if session && $copilotWorkspace !== undefined && starterPrompts.fewItems !== undefined}
<div bind:this={chatWrapper}>
<AIChat
bind:this={aiChat}
bind:this={() => aiChat, bindChat}
hideHeader
hideModeSelector
wideLayout
initialInstructions={getSessionDraftPrompt(sessionId)}
{onDraftChange}
onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)}
initialAttachments={getSessionDraftAttachments(sessionId)}
{onAttachmentsChange}
starter={{
where: 'home',
suggestions: starterPrompts.suggestions,
fewItems: starterPrompts.fewItems
}}
onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)}
starter={{ suggestions: starterPrompts.suggestions, fewItems: starterPrompts.fewItems }}
viewTransitionNames
{onSent}
{actingOn}
/>
</div>
{:else}
@@ -66,7 +66,7 @@
)
const isFork = $derived(!!parentWorkspaceId)
// Same gate as the sidebar WorkspaceMenu / SessionWorkspaceBar. On cloud,
// Same gate as the sidebar WorkspaceMenu. On cloud,
// forking is a premium-only feature (backend caps it per paid seat).
const forksAllowed = $derived(
(!isCloudHosted() || $maybePremium) && canCreateFork($userStore, $roleCapabilities) && $workspaceStore !== 'admins'
@@ -387,7 +387,8 @@
onItemDiscarded={(item) => {
void runtime?.manager.removeModifiedItem(item.draftKind, item.path)
const folder = pipelineFolderFromBundlePath(item.path)
if (item.draftKind === PIPELINE_DRAFT_KIND && folder) void runtime?.forgetPipelineDrafts(folder)
if (item.draftKind === PIPELINE_DRAFT_KIND && folder)
void runtime?.forgetPipelineDrafts(folder)
}}
deployPipeline={runtime?.deployPipeline}
/>
@@ -1,53 +1,34 @@
<script lang="ts">
import { Building, MessagesSquare } from 'lucide-svelte'
import { page } from '$app/state'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
import { enterSessionModeFromNav, exitSessionMode } from './sessionSwitch.svelte'
import { goto } from '$lib/navigation'
import { sendUserToast } from '$lib/toast'
import { page } from '$app/state'
import { resumeAiSessions, returnToWorkspace, swapHomeList } from './sessionSwitch.svelte'
import type { SidebarList } from './sidebarList.svelte'
// Which side of the switch is active. `nav` = workspace navigation (the classic
// app), `session` = the sessions sidebar + chat + preview.
let {
mode,
list,
isCollapsed = false,
// Fired right before the toggle navigates. Lets a host (e.g. the mobile menu
// drawer) keep itself open across the mode switch.
// Fired right before the switch navigates. Lets a host (the mobile menu drawer)
// stay open across it, to show the list it switched to.
onToggle
}: { mode: 'nav' | 'session'; isCollapsed?: boolean; onToggle?: () => void } = $props()
}: { list: SidebarList; isCollapsed?: boolean; onToggle?: () => void } = $props()
// The group's highlighted side. Melt moves it on click, before the navigation
// that would change `mode`, so it is derived from the route (which wins once
// a switch navigates) and pushed back when one does not, or the rail would
// read "AI Sessions" on an editor page with the clicked side inert until
// "Workspace" was pressed first.
let selected: string | string[] | null | undefined = $derived(mode)
// The group's highlighted side. Melt moves it on click, before the navigation that
// changes `list`, so it is pushed back to `list` once the click has played out: a
// navigation that did not happen (an editor refusing to be left) must not leave the
// other side lit.
let selected: string | string[] | null | undefined = $derived(list)
function onSelected(next: 'nav' | 'session') {
if (next === mode) return
onToggle?.()
if (next === 'session') {
// An editor whose draft could not be persisted keeps the user on the
// page, as its own "Open in AI session" button does, rather than open a
// session on an older draft than the one on screen.
void enterSessionModeFromNav().catch((e) => {
selected = mode
sendUserToast(e instanceof Error ? e.message : String(e), true)
})
} else void exitSessionMode()
}
// Pressing the already-active "Workspace" side goes home, so the toggle doubles
// as the home button when there is no mode to switch to. `onToggle` is
// deliberately not fired: this is a plain in-mode navigation, so the mobile menu
// drawer should dismiss like it does for any other nav link.
function onNavActivate() {
if (mode !== 'nav') return
// `goto` has no same-URL short-circuit, so navigating from home would push a
// duplicate history entry and make the next Back press look broken.
if (page.url.pathname === '/') return
void goto('/')
async function onSelected(next: SidebarList) {
if (next === list) return
if (page.url.pathname === '/') {
swapHomeList(next, page.url.pathname + page.url.search)
} else {
onToggle?.()
await (next === 'sessions' ? resumeAiSessions() : returnToWorkspace())
}
selected = list
}
</script>
@@ -62,18 +43,17 @@
{#snippet children({ item })}
<ToggleButton
{item}
value="nav"
value="workspace"
icon={isCollapsed ? Building : undefined}
label="Workspace"
iconOnly={isCollapsed}
tooltip={isCollapsed ? 'Workspace' : undefined}
size="sm"
class="w-full justify-center whitespace-nowrap"
onActivate={onNavActivate}
/>
<ToggleButton
{item}
value="session"
value="sessions"
icon={isCollapsed ? MessagesSquare : undefined}
label="AI Sessions"
iconOnly={isCollapsed}
@@ -1,6 +1,5 @@
<script lang="ts">
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import Modal from '$lib/components/common/modal/Modal.svelte'
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
import { Button } from '$lib/components/common'
import {
@@ -23,20 +22,20 @@
import { twMerge } from 'tailwind-merge'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import { goto } from '$lib/navigation'
import { takeNewSessionSeed, type NewSessionSeed } from './sessionSwitch.svelte'
import { leaveForHome, openDraftOnHome, openNewSession } from './sessionSwitch.svelte'
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
import { slide } from 'svelte/transition'
import {
createSession,
deleteSessionsForWorkspace,
homeDraft,
isForkSession,
opensOnHome,
reconcileAfterWorkspaceChange,
renameSession,
selectSession,
sessionPageHref,
sessionLastActivityAt,
sessionState,
setNewSessionWorkspace,
setSessionArchived,
syncWorkspaceTo,
withOpenSessionTeardown,
@@ -49,8 +48,7 @@
getRuntime,
getSessionChatPeek,
getSessionChatStatus,
removeSession,
resetSessionPreviewTabs
removeSession
} from './sessionRuntime.svelte'
import SessionStatusDot from './SessionStatusDot.svelte'
import UnreadCountBadge from '$lib/components/common/badge/UnreadCountBadge.svelte'
@@ -116,10 +114,15 @@
return () => clearInterval(handle)
})
// Only highlight the active session while the sessions page is open — elsewhere
// `currentSessionId` lingers but no row should appear selected.
const onSessionsPage = $derived(page.url.pathname.startsWith('/sessions'))
const sessionActive = $derived(onSessionsPage)
// The row the page is showing: the open session on its page, the draft in Home's
// composer on Home. Elsewhere `currentSessionId` lingers but no row is selected.
const activeRowId = $derived(
page.url.pathname.startsWith('/sessions')
? sessionState.currentSessionId
: page.url.pathname === '/'
? homeDraft.id
: undefined
)
interface Props {
isCollapsed?: boolean
@@ -176,10 +179,12 @@
// total, and keyboard navigation.
const visibleSessions = $derived(
sessionState.sessions.filter((s) => {
// A blank nobody has typed in is Home's composer at rest, not a session yet.
if (s.transient) return false
// Pending (unsent) sessions show like any other, so several drafts can be
// set up in parallel; they group by pending_workspace_id via sessionRootOf.
// The open session always stays in the list, ignoring every filter.
if (s.id === sessionState.currentSessionId) return true
// The row on screen always stays in the list, ignoring every filter.
if (s.id === activeRowId) return true
if (s.archived && !showArchived.val) return false
if (lastActivityDays.val > 0) {
const cutoff = clock - lastActivityDays.val * 24 * 60 * 60 * 1000
@@ -352,7 +357,7 @@
const archivedCount = $derived(
sessionState.sessions.filter((s) => {
if (!s.archived || s.transient) return false
if (s.id === sessionState.currentSessionId) return true
if (s.id === activeRowId) return true
if (lastActivityDays.val > 0) {
const cutoff = clock - lastActivityDays.val * 24 * 60 * 60 * 1000
if (sessionLastActivityAt(s) < cutoff) return false
@@ -396,6 +401,10 @@
async function activate(session: Session, restoreFocus: boolean = false) {
// Picking a session leaves browse mode so the chat comes back.
onSelectSession?.()
if (opensOnHome(session)) {
await openDraftOnHome(session.id)
return
}
selectSession(session.id)
// The global workspaceStore is intentionally NOT switched here: a session
// runs against its own workspace via the chat manager's workspace resolver,
@@ -415,59 +424,16 @@
}
}
// Whatever page is on screen, a new session starts on Home: a session about an item
// is started from that item, by its Open in AI session button.
async function createAndOpen() {
// A new session opened from a Windmill page adopts that page as its first
// preview tab.
if (!onSessionsPage) {
await createAndOpenWith(page.url.pathname + page.url.search)
return
}
// On the sessions page there is nothing meaningful on screen to capture,
// except the item the user just left to get here: that one is offered (once)
// before the session is created, and answerSeedOffer picks up from there.
const seed = takeNewSessionSeed()
if (seed) {
seedOffer = seed
seedOfferOpen = true
return
}
await createAndOpenWith(undefined)
await openNewSession()
}
// `previewUrl` undefined leaves the preview empty until the chat opens something.
async function createAndOpenWith(previewUrl: string | undefined) {
const fresh = createSession()
if (previewUrl) resetSessionPreviewTabs(fresh.id, previewUrl)
await activate(fresh)
}
// The item createAndOpen is asking about. Closing the dialog any other way than
// answering (Escape, the corner X, the backdrop) creates nothing: the click was
// met with a question, not a session. Kept after the dialog closes, since the
// title reads it through the close fade; `seedOfferOpen` alone gates rendering.
let seedOffer = $state<NewSessionSeed | undefined>(undefined)
let seedOfferOpen = $state(false)
// Focus moves onto the primary answer as the dialog opens. Enter is left to
// the focused button (the dialog does not bind it), and the "New session"
// button that opened the dialog would otherwise keep focus and answer Enter
// with a second, unasked session underneath.
let keepButton: Button | undefined = $state(undefined)
$effect(() => {
if (seedOfferOpen) keepButton?.focus()
})
async function answerSeedOffer(keep: boolean) {
const offer = seedOffer
seedOfferOpen = false
if (!offer) return
await createAndOpenWith(keep ? offer.url : undefined)
}
// The `+` on a workspace group header: a new session parked on that group's
// workspace rather than the one currently open.
// The `+` on a workspace group header: a new session in that group's workspace,
// which the header switches to, since Home's draft acts on the header's workspace.
async function createAndOpenIn(workspaceId: string) {
const fresh = createSession()
setNewSessionWorkspace(fresh.id, workspaceId)
await activate(fresh)
await openNewSession(workspaceId)
}
let editingId: string | undefined = $state(undefined)
@@ -584,6 +550,13 @@
selectedIds = allSelected ? [] : [...selectableIds]
}
// Home shows no archived draft, so archiving the one its composer holds moves Home on.
function leaveArchivedHomeDraft(ids: string[]) {
if (page.url.pathname === '/' && homeDraft.id && ids.includes(homeDraft.id)) {
void leaveForHome()
}
}
function handleBatchArchive() {
const archive = !allSelectedArchived
let skipped = 0
@@ -599,6 +572,7 @@
}
setSessionArchived(id, archive)
}
if (archive) leaveArchivedHomeDraft(selectedIds)
exitSelectionMode()
if (skipped > 0) {
sendUserToast(
@@ -607,31 +581,18 @@
}
}
// After deleting the open session, land somewhere usable: the newest remaining
// session, else a fresh one. The page derives the visible session from the
// `session` query, so leaving the URL on a deleted session would fall
// through to recovery and open a blank one rather than their recent work.
async function openReplacementSession() {
const next = sessionState.sessions[0]
if (next) await activate(next)
else {
const fresh = createSession()
await goto(sessionPageHref(fresh.id))
}
}
// Batch delete never touches fork workspaces — same default as the single
// delete, where the user has to tick the fork box explicitly.
async function handleConfirmedBatchDelete() {
const ids = selectedIds
batchDeleteOpen = false
if (ids.length === 0) return
const current = sessionState.currentSessionId
const wasActive = !!current && ids.includes(current)
const active = activeRowId
const wasActive = !!active && ids.includes(active)
await withOpenSessionTeardown(async () => {
for (const id of ids) removeSession(id)
exitSelectionMode()
if (wasActive) await openReplacementSession()
if (wasActive) await leaveForHome()
})
}
@@ -647,7 +608,7 @@
pendingDelete = undefined
deleteAlsoFork = false
if (!session) return
const wasActive = sessionState.currentSessionId === session.id
const wasActive = activeRowId === session.id
await withOpenSessionTeardown(async () => {
removeSession(session.id)
if (forkToDelete) {
@@ -665,7 +626,7 @@
if (forkToDelete && forkParentId && $workspaceStore === forkToDelete) {
syncWorkspaceTo(forkParentId)
}
if (wasActive) await openReplacementSession()
if (wasActive) await leaveForHome()
})
}
@@ -771,8 +732,7 @@
{@const status = runtime
? getSessionChatStatus(runtime)
: (getSessionChatPeek(session.id)?.status ?? 'idle')}
{@const isSelected =
sessionActive && session.id === sessionState.currentSessionId}
{@const isSelected = session.id === activeRowId}
{@const unread = unreadFor(session)}
{@const draft = hasDraft(session)}
<MenuItem
@@ -984,7 +944,7 @@
{@const status = runtime
? getSessionChatStatus(runtime)
: (getSessionChatPeek(session.id)?.status ?? 'idle')}
{@const isSelected = sessionActive && session.id === sessionState.currentSessionId}
{@const isSelected = session.id === activeRowId}
{@const isEditing = editingId === session.id}
{@const unread = unreadFor(session)}
{@const draft = hasDraft(session)}
@@ -1112,7 +1072,10 @@
{
displayName: 'Archive',
icon: Archive,
action: () => setSessionArchived(session.id, true)
action: () => {
setSessionArchived(session.id, true)
leaveArchivedHomeDraft([session.id])
}
}
]),
{
@@ -1330,30 +1293,3 @@
{/if}
</div>
</ConfirmationModal>
<!-- Two answers of equal standing, so Enter is left to whichever button has
focus rather than bound to one of them by the dialog. -->
<Modal
bind:open={seedOfferOpen}
kind="X"
enterConfirms={false}
title="Keep this {seedOffer?.kind ?? 'item'} in the new session?"
description="You came here from {seedOffer?.path ?? ''}."
>
<p class="text-sm text-secondary">
Keeping it opens it in the preview, so the chat starts with it as context.
</p>
<div class="flex justify-end gap-2 mt-4">
<Button variant="default" unifiedSize="sm" onClick={() => answerSeedOffer(false)}>
Start empty
</Button>
<Button
bind:this={keepButton}
variant="accent"
unifiedSize="sm"
onClick={() => answerSeedOffer(true)}
>
Keep in preview
</Button>
</div>
</Modal>
@@ -1,60 +0,0 @@
<script lang="ts">
import { workspaceStore } from '$lib/stores'
import {
getEffectiveWorkspaceId,
setSessionPendingFork,
setSessionPendingWorkspace,
type Session
} from './sessionState.svelte'
import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte'
import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte'
import { switchWorkspace } from '$lib/storeUtils'
import { workspaceAIClients } from '$lib/components/copilot/lib'
import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl'
// `switchesWorkspace`: a pick also moves the navigation workspace. For a host whose page
// shows the navigation workspace around the composer (Home), where a pick that left it
// behind would read as ignored; the session page follows the session's own workspace instead.
let { session, switchesWorkspace = false }: { session: Session; switchesWorkspace?: boolean } =
$props()
function followPick(id: string) {
if (!switchesWorkspace || $workspaceStore === id) return
workspaceAIClients.init(id)
switchWorkspace(id)
void fixupUrlAfterWorkspaceSwitch(id)
}
// Effective workspace for display: committed → pending pick → active store.
const effectiveId = $derived(getEffectiveWorkspaceId(session) ?? $workspaceStore ?? undefined)
const pendingFork = $derived(session.pending_fork)
function pick(id: string) {
// Pre-send only: writes the pending pick. workspace_id stays undefined until
// the user sends their first message. The chat targets this pending workspace
// via the manager's workspace resolver, not the global workspaceStore.
setSessionPendingWorkspace(session.id, id)
followPick(id)
}
function stageFork(req: { parent_workspace_id: string; id: string; name: string }) {
setSessionPendingFork(session.id, req)
followPick(req.parent_workspace_id)
}
</script>
<!-- A control of the composer's toolbar; on a narrow window it gives up its label first. -->
<div class="flex flex-row items-center gap-1 min-w-0 text-2xs text-secondary">
<span class="shrink-0 hidden lg:inline">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>
@@ -9,15 +9,12 @@
</script>
<script lang="ts">
import { onDestroy, setContext, untrack } from 'svelte'
import { setContext, untrack } from 'svelte'
import { Pane, Splitpanes } from 'svelte-splitpanes'
import type AIChat from '$lib/components/copilot/chat/AIChat.svelte'
import ComposerPlaceholder from '$lib/components/copilot/chat/ComposerPlaceholder.svelte'
import SessionGreeting from '$lib/components/copilot/chat/starter/SessionGreeting.svelte'
import ComposerSuggestions from '$lib/components/copilot/chat/starter/ComposerSuggestions.svelte'
import {
globalComposerSuggestion,
STARTER_PLACEHOLDER,
type ComposerSelection
} from '$lib/components/copilot/chat/composerBox'
import { useSessionPermissions } from './sessionPermissions.svelte'
@@ -34,24 +31,11 @@
import Toggle from '$lib/components/Toggle.svelte'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
import { loadCopilot } from '$lib/components/copilot/loadCopilot'
import {
Archive,
ArchiveRestore,
EllipsisVertical,
MessageSquareDashed,
Pencil,
Plus,
Trash2,
X
} from 'lucide-svelte'
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
import { Archive, ArchiveRestore, EllipsisVertical, Pencil, Trash2 } from 'lucide-svelte'
import { arrivingFromHomeSend } from './homeSessionsTransition.svelte'
import SessionChangesBar from './SessionChangesBar.svelte'
import SessionShareButton from './SessionShareButton.svelte'
import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte'
import {
composerFocusRequest,
createSession,
deleteSessionsForWorkspace,
getEffectiveWorkspaceId,
moveSessionToNewFork,
@@ -64,17 +48,15 @@
takeSessionAutoSend,
reconcileAfterWorkspaceChange,
renameSession,
selectSession,
sessionPageHref,
sessionState,
setSessionArchived,
syncWorkspaceTo,
withOpenSessionTeardown
withOpenSessionTeardown,
type Session
} from './sessionState.svelte'
import { leaveForHome } from './sessionSwitch.svelte'
import { getOrCreateRuntime, removeSession } from './sessionRuntime.svelte'
import { goto } from '$lib/navigation'
import { splitterPointerCapture } from '$lib/utils/splitterPointerCapture'
import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte'
let {
sessionId,
@@ -100,15 +82,6 @@
// Reactive session reference (mutations to summary/target propagate via the $state proxy)
const session = $derived(sessionState.sessions.find((s) => s.id === sessionId))
// 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).
const restoredDraftPrompt = getSessionDraftPrompt(sessionId)
@@ -189,16 +162,11 @@
let summaryInput: EditableInput | undefined = $state(undefined)
// Drop the user on a fresh new-session page. Used after archiving or
// deleting the open session: the session they were on is no longer
// usable, and routing to a sibling would feel arbitrary.
async function resetToNewSession() {
const fresh = createSession()
selectSession(fresh.id)
// The page derives the visible session from the `session` query, not
// currentSessionId: navigate so the URL leaves the deleted/archived session,
// which would otherwise fall through to recovery or stay on the archived one.
await goto(sessionPageHref(fresh.id))
// After archiving or deleting the open session, Home: the session the user was on
// is no longer usable, and routing to a sibling would feel arbitrary. The URL has to
// leave it, or the page would fall through to recovery or stay on the archived one.
async function leaveRemovedSession() {
await leaveForHome()
}
// If the session targets a forked workspace that's still accessible,
@@ -249,7 +217,7 @@
if (forkToDelete && forkParentId && $workspaceStore === forkToDelete) {
syncWorkspaceTo(forkParentId)
}
await resetToNewSession()
await leaveRemovedSession()
})
}
@@ -268,7 +236,7 @@
sendUserToast(`Failed to archive fork ${forkToArchive}: ${e?.body ?? e}`, true)
}
}
await resetToNewSession()
await leaveRemovedSession()
}
// Kept for the "Archive" entry that doesn't go through the confirmation
@@ -283,54 +251,16 @@
return
}
setSessionArchived(session.id, true)
await resetToNewSession()
await leaveRemovedSession()
}
// Workspace bar is shown only before the session sends its first user
// message — after that the session's workspace is immutable. The
// commit itself happens in `AIChatManager.beforeSend` (wired in
// `createRuntime`) so it fires exactly once at send-time. A reactive
// commit here would retry forever on backend failures (e.g. fork-id
// collision after a previously-successful create whose response was
// dropped) — restoration self-heal lives in `initRuntime` instead.
const hasFirstUserMessage = $derived(
runtime?.manager.displayMessages.some((m) => m.role === 'user') ?? false
)
// Gated on the first message, not on typing: the notice sits directly above a
// vertically centred composer, so dropping it mid-sentence would jump the
// field out from under the user's cursor.
const showRecoveryNotice = $derived(isSessionRecovered(sessionId) && !hasFirstUserMessage)
// The notice explains one arrival, and the arrival is exactly "this page is
// open, on this session, nothing sent yet". Spend the marker the moment any of
// those three breaks, so a later return can never replay it — masking it behind
// the gate above instead leaves it to resurface. Dismiss is the user's own exit.
$effect(() => {
if (hasFirstUserMessage || sessionState.currentSessionId !== sessionId) {
clearSessionRecovered(sessionId)
}
})
onDestroy(() => clearSessionRecovered(sessionId))
// Focus the chat input whenever this session is the active one.
// The textarea is disabled until copilotInfo loads (otherwise focus is
// a silent no-op), so we wait for that too. Triggers on initial mount,
// warm-session switch via the picker, and the moment copilot finishes
// loading.
let aiChat: AIChat | undefined = $state(undefined)
let seenFocusNonce = untrack(() => composerFocusRequest.nonce)
$effect(() => {
// Focus the composer when this session becomes active, or on an explicit
// focus request — the latter covers `+` reusing the untouched draft you're
// already viewing, where currentSessionId doesn't change so activation alone
// wouldn't re-run this.
const focusNonce = composerFocusRequest.nonce
if (focusNonce !== seenFocusNonce) {
// An explicit request overrides the user having left the placeholder before it.
seenFocusNonce = focusNonce
handoff = undefined
}
if (sessionState.currentSessionId !== sessionId) {
// The user left for another session: coming back is an activation, which focuses.
handoff = undefined
@@ -394,37 +324,12 @@
{#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}
<!-- A session with no message yet, or whose transcript is still loading, keeps its composer
at the bottom, where it stays once the transcript shows, rather than the docked
copilot's keyboard-shortcut hint, which means nothing here. -->
{#snippet sessionEmptyHint()}<div class="flex-1 min-h-0"></div>{/snippet}
{#snippet inputPreface()}
{#if showRecoveryNotice}
<!-- mb-6, not the banner column's mb-1: at that gap it reads as one more
row of composer chrome rather than as a message about the session. -->
<!-- Tinted, where the other banners are white: this one has to be spotted
without being looked for, above a composer the user is already typing in. -->
<!-- Announced: the composer takes focus the moment this appears, so without
it a screen reader lands in an empty field with no account of the swap. -->
<div role="status" class="{bannerClass} bg-surface-accent-selected mb-6">
<div class="flex flex-row items-center gap-2 min-w-0">
<MessageSquareDashed class="w-4 h-4 shrink-0 text-accent" />
<!-- Names no cause: deleted, another browser, cleared site data and a
damaged link are indistinguishable from here. The empty session it
landed on is on screen, so the notice doesn't describe it. -->
<span class="text-emphasis font-semibold">We couldn't find that session</span>
</div>
<Button
variant="subtle"
unifiedSize="2xs"
iconOnly
startIcon={{ icon: X }}
title="Dismiss"
aria-label="Dismiss"
onclick={() => clearSessionRecovered(sessionId)}
/>
</div>
{/if}
<!-- gap-1 (4px) spaces the archived banner and the changes bar when both
are visible. Each renders a single in-flow root (or nothing); the diff
drawer is position:fixed, so it doesn't count as a flex item — no stray
@@ -461,19 +366,14 @@
</div>
{/snippet}
{#snippet actingOn()}
<SessionWorkspaceBar {session} />
{/snippet}
<!-- The left of AIChatDisplay's controls row: the rest arrives with the chat. -->
{#snippet placeholderToolbar()}
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
<Button unifiedSize="2xs" variant="subtle" iconOnly startIcon={{ icon: Plus }} disabled />
{@render actingOn()}
</div>
{/snippet}
<!-- Read by the page header bar, outside this branch, so `session` can be gone here: a delete
removes the session while the bar still shows it, on the way to the next page. The
section's label below reads it the same way. -->
{#snippet sessionHeader()}
{#if session}{@render sessionHeaderControls(session)}{/if}
{/snippet}
{#snippet sessionHeaderControls(session: Session)}
<EditableInput
bind:this={summaryInput}
value={session.summary ?? ''}
@@ -545,7 +445,7 @@
fork reads like anything else in that fork. -->
<PageHeaderContent
section={{
label: session.summary ?? 'Untitled session',
label: session?.summary ?? 'Untitled session',
content: sessionHeader,
noNavPicker: true
}}
@@ -577,62 +477,33 @@
: session.archived
? 'This session is archived. Unarchive it from the banner above to keep working.'
: ''}
starter={opensSession
? { where: 'session', suggestions: starterPrompts.suggestions }
: undefined}
viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())}
viewTransitionNames={headerInPage && arrivingFromHomeSend()}
emptyHint={sessionEmptyHint}
{inputPreface}
actingOn={hasFirstUserMessage ? undefined : actingOn}
/>
{:else}
<!-- AIChatDisplay's layout, so the composer stays put when the chat replaces it:
its transcript area, its column, and its footer row's height; for a session
that has never sent, the greeting above the centred composer. -->
its transcript area, its column, and its footer row's height. -->
<div
class="flex flex-col h-full {opensSession ? 'justify-center' : ''}"
class="flex flex-col h-full"
{@attach () => () =>
runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, false)}
>
{#if opensSession}
<div class="flex-1 min-h-0 flex flex-col justify-end">
<div class="w-full max-w-3xl mx-auto px-7">
<SessionGreeting />
</div>
</div>
{:else if runtime.manager.displayMessages.length > 0}
<div class="flex-1 min-h-0"></div>
{/if}
<div class="flex-1 min-h-0"></div>
<div class="w-full max-w-3xl mx-auto px-7 pb-2">
{@render inputPreface()}
<ComposerPlaceholder
bind:value={() => draftText, setPlaceholderText}
toolbar={opensSession ? placeholderToolbar : undefined}
placeholder={opensSession
? STARTER_PLACEHOLDER
: runtime.manager.displayMessages.length > 0
? 'Ask followup'
: composerPlaceholder}
placeholder={runtime.manager.displayMessages.length > 0
? 'Ask followup'
: composerPlaceholder}
disabled={isUnavailable || !!session.archived}
autofocus={sessionState.currentSessionId === sessionId && !covered}
onSelectionChange={(selection) => (handoff = selection ?? null)}
onCompositionChange={(composing) => (placeholderComposing = composing)}
/>
{#if !opensSession}
<div class="mt-1 h-5"></div>
{:else if !isUnavailable && !session.archived && starterPrompts.suggestions.length > 0}
<div class="pt-2">
<ComposerSuggestions
suggestions={starterPrompts.suggestions}
wrap
onPick={setPlaceholderText}
/>
</div>
{/if}
<div class="mt-1 h-5"></div>
</div>
{#if opensSession}
<div class="flex-1 min-h-0"></div>
{/if}
</div>
{/if}
</div>
@@ -1,7 +1,7 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import { classes as alertClasses, icons as alertIcons } from '$lib/components/common/alert/model'
import { clearSessionsBetaOptOut } from '$lib/components/copilot/chat/global/gate'
import { activateAiSessions } from './sidebarList.svelte'
const InfoIcon = alertIcons.info
</script>
@@ -18,12 +18,6 @@
<InfoIcon size={14} class="shrink-0 {alertClasses.info.iconClass}" />
<span class="font-medium">Try AI Sessions (beta)</span>
<span>·</span>
<Button
variant="subtle"
unifiedSize="xs"
onclick={() => clearSessionsBetaOptOut('/sessions')}
>
Activate
</Button>
<Button variant="subtle" unifiedSize="xs" onclick={activateAiSessions}>Activate</Button>
</div>
</div>
@@ -47,8 +47,7 @@
// drives the family-root resolution and the "selected" highlight).
// Defaults to the active workspace store when not set.
selectedId,
// A staged-but-not-yet-created fork (e.g. SessionWorkspaceBar's
// pre-send draft). Highlighted as the active row when set.
// A staged-but-not-yet-created fork. Highlighted as the active row when set.
pendingFork,
onPick,
onCreateFork,
@@ -1,40 +1,16 @@
import type { OnNavigate } from '@sveltejs/kit'
import { sessionState } from './sessionState.svelte'
// Moving between Home and AI Sessions keeps the composer in sight: the browser
// snapshots the page before and after the navigation and glides the element that
// carries the `composer` view-transition-name on both sides (AIChatDisplay names it);
// 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.
// A send from Home keeps the composer in sight: the browser snapshots the page before and
// after the navigation to the session the send started, and glides the element that carries
// the `composer` view-transition-name (AIChatDisplay names it) from Home to its place under the
// session's first message; the rest of the page cross-fades. Any other move between Home and
// a session is one cross-fade: a session under way has a composer of its own, not Home's. 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
}
// A session that has sent its first message has a composer of its own, not Home's draft, so
// a move between it and Home is not one composer moving: its page names no composer. The one
// exception is the send from Home itself, which lands on that session already under way.
let sentFromHome = $state(false)
/** Called by Home's composer as its send hands over to the session page. */
@@ -53,34 +29,14 @@ export function arrivingFromHomeSend(): boolean {
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
const glides = sentFromHome && from === HOME && to === SESSIONS
// Good for the navigation the send started, and only that one.
if (direction !== 'enter') sentFromHome = false
if (!direction || navigation.willUnload || !document.startViewTransition) return
if (!glides) sentFromHome = false
const between = (from === HOME && to === SESSIONS) || (from === SESSIONS && to === HOME)
if (!between || navigation.willUnload || !document.startViewTransition) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return
const root = document.documentElement
// To or from a session under way there is no composer to carry over: Home's would only
// fade out or in on its own, so the move drops every name and the page cross-fades as
// one. Leaving, the page says so; arriving, the session's record does (it has sent once
// it has a workspace), short of the send from Home that just started it.
const composerOnScreen = Array.from(document.querySelectorAll('[data-session-composer]')).some(
(el) => getComputedStyle(el).viewTransitionName === 'composer'
)
const arrivingId = navigation.to?.url.searchParams.get('session') ?? sessionState.currentSessionId
const arrivingUnderWay =
!sentFromHome && !!sessionState.sessions.find((s) => s.id === arrivingId)?.workspace_id
const plain = direction === 'leave' ? !composerOnScreen : arrivingUnderWay
root.dataset.homeSessionsTransition = plain ? 'fade' : direction
root.dataset.homeSessionsTransition = glides ? 'glide' : 'fade'
return new Promise((resolve) => {
const transition = document.startViewTransition(async () => {
resolve()
@@ -1,14 +0,0 @@
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)
})
})
@@ -1,6 +1,5 @@
import { getContext, onDestroy, setContext } from 'svelte'
import { getContext, setContext } from 'svelte'
import type { OpenInSessionSource } from './OpenInSessionButton.svelte'
import type { SessionTarget } from './sessionState.svelte'
// The "Open in AI session" hand-off, published by the component that owns the
// item being edited (FlowBuilder, RawAppEditor) for AI entry points too deep in
@@ -15,40 +14,10 @@ export type OpenInSessionHandoff = {
source: (opts?: { moduleId?: string }) => OpenInSessionSource | undefined
}
// The hand-offs of every editor currently mounted. The navigation rail's "AI
// Sessions" switch sits above every page, out of reach of the context, and
// looks the editor of the item it is leaving up here instead.
const mounted = new Set<OpenInSessionHandoff>()
export function setOpenInSessionHandoff(handoff: OpenInSessionHandoff): void {
setContext(KEY, handoff)
onDestroy(registerMountedOpenInSessionHandoff(handoff))
}
/** Count `handoff` as mounted until the returned unregister runs. Split from
* setOpenInSessionHandoff so the registry can be driven outside a component. */
export function registerMountedOpenInSessionHandoff(handoff: OpenInSessionHandoff): () => void {
mounted.add(handoff)
return () => {
mounted.delete(handoff)
}
}
export function getOpenInSessionHandoff(): OpenInSessionHandoff | undefined {
return getContext<OpenInSessionHandoff | undefined>(KEY)
}
/** The mounted editor's hand-off for `target`, or undefined when no editor on
* screen publishes one for it (a detail page). Matched on the item rather than
* taken as "the latest registered": a script editor mounted in a flow's drawer
* registers too, and the rail wants the page's own item. */
export function findMountedOpenInSessionSource(
target: SessionTarget
): OpenInSessionSource | undefined {
for (const handoff of mounted) {
const source = handoff.source()
const t = source?.target
if (t && t.kind === target.kind && t.path === target.path) return source
}
return undefined
}
@@ -1,18 +0,0 @@
import { SvelteSet } from 'svelte/reactivity'
// Session ids opened as a stand-in for a `session` URL this browser doesn't
// hold. Kept in memory rather than on the Session record: persisted, the notice
// would replay on every reload of a session the user has since made their own.
const recovered = new SvelteSet<string>()
export function markSessionRecovered(id: string): void {
recovered.add(id)
}
export function isSessionRecovered(id: string): boolean {
return recovered.has(id)
}
export function clearSessionRecovered(id: string): void {
recovered.delete(id)
}
@@ -21,7 +21,6 @@ import {
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { workspaceRootId } from './sessionScope.svelte'
import { clearSessionRecovered } from './sessionRecoveryNotice.svelte'
import { type DBSchema, type IDBPDatabase } from 'idb'
import { userScopedDb } from '$lib/userScopedDb'
import { emailOfScopedKey, scopedKeyFor } from '$lib/userScopedStorage'
@@ -94,13 +93,14 @@ export type Session = {
// that have never been sent — those scope by `pending_workspace_id`
// instead and don't show the fork bar.
workspace_id?: string
// Pre-send draft workspace, picked via SessionWorkspaceBar. Drives
// scope/editor/display while workspace_id is undefined; gets copied
// Where an unsent session will act: the workspace a hand-off named, or, for the
// draft on Home, the workspace the page header names (see followHomeDraft).
// Drives scope/editor/display while workspace_id is undefined; gets copied
// into workspace_id at first send and then becomes irrelevant.
pending_workspace_id?: string
// Pre-send intent to create a new fork. The actual API call is
// deferred to first send (via commitSessionWorkspace) so cancelling
// the draft doesn't leave an orphan fork behind.
// Intent to create a new fork at first send (via commitSessionWorkspace), so
// cancelling the draft doesn't leave an orphan fork behind. Found only on records
// older clients wrote: no control stages one.
pending_fork?: PendingFork
// Stable root workspace id used only for sidebar grouping. Lifecycle follows
// workspace_id, not this field. Root sessions store the same id in both fields.
@@ -1022,9 +1022,19 @@ onUserChange(async (email, prevEmail) => {
void reconcileSessionsLifecycle()
})
// The unsent session Home's composer holds. Kept apart from currentSessionId, the
// session open on the sessions page: which draft Home shows says nothing about which
// session the user last opened. `requests` counts asks to show another one, which
// remount Home's composer when Home is already on screen.
export const homeDraft = $state<{ id: string | undefined; requests: number; focus: boolean }>({
id: undefined,
requests: 0,
focus: false
})
// Workspace switches do not reload or clear the active session. The sidebar
// filters the single loaded session list by workspace_root_id, while the current
// chat survives workspace switches.
// chat survives workspace switches. Home's draft follows the switch instead.
if (BROWSER) {
let lastWorkspace: string | undefined
let initialized = false
@@ -1032,76 +1042,99 @@ if (BROWSER) {
const isSwitch = initialized && ws !== lastWorkspace
initialized = true
lastWorkspace = ws
if (isSwitch) followHomeDraft()
if (isSwitch && Date.now() - lastReconcileAt > RECONCILE_THROTTLE_MS) {
void reconcileSessionsLifecycle()
}
})
}
// Home's draft acts on the workspace the page header names, so a switch to another
// workspace of its family takes the draft along. A switch to another family leaves
// it where it was: Home shows that family's own draft. Not a touch, so the draft's
// last activity stays when the user last worked on it.
function followHomeDraft(): void {
const s = homeDraft.id ? sessionState.sessions.find((x) => x.id === homeDraft.id) : undefined
const ws = get(workspaceStore)
if (!s || !ws || s.workspace_id) return
if (s.pending_workspace_id === ws && !s.pending_fork) return
if (s.pending_workspace_id && workspaceRootId(ws, get(userWorkspaces)) !== sessionRootId(s)) {
return
}
s.pending_workspace_id = ws
s.pending_fork = undefined
void putSession(s)
}
/** Called by Home's composer for the draft it shows, which then acts on the header's workspace. */
export function holdHomeDraft(id: string): void {
homeDraft.id = id
followHomeDraft()
}
/** Ask Home to show `id`, and whether its composer takes focus as it mounts. */
export function showOnHome(id: string, opts?: { focus?: boolean }): void {
homeDraft.id = id
homeDraft.focus = opts?.focus ?? false
homeDraft.requests++
}
/** Whether Home's composer should take focus now that it is on screen. Read once. */
export function takeHomeDraftFocus(): boolean {
const focus = homeDraft.focus
homeDraft.focus = false
return focus
}
export function sessionPageHref(id: string): string {
return `/sessions?session=${encodeURIComponent(id)}`
}
// Bumped to ask the active session's composer to re-focus even when
// `currentSessionId` doesn't change — the `+` reuse path lands you back on the
// untouched draft you're already viewing, so nothing navigates, but the click
// should still drop the cursor in the composer. SessionWrapper's focus effect
// depends on `nonce`.
export const composerFocusRequest = $state<{ nonce: number }>({ nonce: 0 })
export function requestComposerFocus(): void {
composerFocusRequest.nonce++
}
// An untouched in-memory blank that `+` may reuse and createSession may silently
// drop. `draftPrompt === undefined` (never edited), not falsiness: a draft typed
// then erased to '' still has a pending flush and is a real session. Every other
// touch clears `transient` synchronously, so only the draft prompt needs checking.
// An untouched in-memory blank that a new session may reuse and newTransientSession
// may silently drop. `draftPrompt === undefined` (never edited), not falsiness: a
// draft typed then erased to '' still has a pending flush and is a real session.
// Every other touch clears `transient` synchronously, so only the draft prompt
// needs checking.
function isDiscardableDraft(s: Session): boolean {
return !!s.transient && s.draftPrompt === undefined
}
// Somewhere empty to put the user, for a URL naming a session this browser
// doesn't hold. Only `transient` makes "empty" trustworthy: a persisted session
// can hold a conversation while every field below stays untouched — its chat and
// attached files key off `!transient`, not off these.
export function findEmptyLandingSession(): Session | undefined {
return sessionState.sessions.find(
(s) =>
!!s.transient &&
!s.archived &&
!s.workspace_id &&
// Falsiness, not `=== undefined`: we only navigate into the session, so a
// draft erased back to '' is still an empty composer to land on.
!s.draftPrompt?.trim() &&
!s.pending_fork &&
sessionInCurrentFamily(s)
)
// The family's untouched blank, reused rather than piling a blank entry on every
// new session, so several pending sessions can still be built up in parallel, one
// touch at a time. A cross-family leftover blank is dropped instead of reused
// (reusing it would act on that family).
function reusableBlank(): Session | undefined {
return sessionState.sessions.find((s) => isDiscardableDraft(s) && sessionInCurrentFamily(s))
}
/** A session for a hand-off to open on the sessions page, selected. */
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
// in parallel, one touch at a time. A cross-family leftover blank is dropped
// instead of reused (reusing it would act on that family).
const reusable = sessionState.sessions.find(
(s) => isDiscardableDraft(s) && sessionInCurrentFamily(s)
)
if (reusable) {
sessionState.currentSessionId = reusable.id
// The blank recovery just landed on is exactly what this reuses, so `+`
// would otherwise hand back a session still carrying the recovery notice:
// asking for a new session must not be answered with "we couldn't find it".
clearSessionRecovered(reusable.id)
// Reusing an already-active draft doesn't change currentSessionId, so ask
// the composer to focus explicitly — the caller still navigates/redirects.
requestComposerFocus()
return reusable
}
const session = newTransientSession()
const session = reusableBlank() ?? newTransientSession(defaultSessionWorkspace())
sessionState.currentSessionId = session.id
return session
}
// Where a session started away from Home acts when its caller names no workspace:
// the one you're in, except a root you can't deploy to (locked, no bypass), which
// steers to its dev since a session there couldn't edit anything.
function defaultSessionWorkspace(): string | undefined {
const currentWs = get(workspaceStore) ?? undefined
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.
const rulesLoadedForCurrent =
protectionRulesState.rulesets !== undefined && protectionRulesState.workspace === currentWs
const canDeployHere =
rulesLoadedForCurrent &&
(!isRuleActive('DisableDirectDeployment') ||
canUserBypassRuleKind('DisableDirectDeployment', get(userStore)))
return devOfCurrent && !canDeployHere ? devOfCurrent : currentWs
}
// 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
@@ -1111,28 +1144,10 @@ export function setDraftsDiscardedHandler(handler: (ids: string[]) => void): voi
onDraftsDiscarded = handler
}
function newTransientSession(): Session {
function newTransientSession(pending: string | undefined): Session {
const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id)
sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s))
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).
@@ -1152,25 +1167,30 @@ function newTransientSession(): Session {
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. */
/** Whether a session opens in Home's composer rather than on a page of its own: unsent, and
* neither about an item (it carries preview tabs, which need the session page's panel) nor
* armed to send itself on arrival. */
export function opensOnHome(s: Session): boolean {
return !s.workspace_id && !s.previewTabs?.length && !autoSendIsFresh(s)
}
/** The unsent session Home's composer shows: the one Home last held, else the family's
* most recent stored draft, else a blank. */
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 unsent = (s: Session) => !s.archived && opensOnHome(s) && sessionInCurrentFamily(s)
const held = sessionState.sessions.find((s) => s.id === homeDraft.id)
if (held && unsent(held)) return held
// Stored but never sent: a draft the user typed or attached something in. Leaving it
// would strand it in the session list.
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()
)
return touched ?? blankHomeDraft()
}
/** A blank for Home's composer: the family's untouched one if any, else a new one. */
export function blankHomeDraft(): Session {
return reusableBlank() ?? newTransientSession(get(workspaceStore) ?? undefined)
}
// Promote an in-memory transient session to a persisted IndexedDB record.
@@ -1194,27 +1214,6 @@ export function setSessionPendingWorkspace(id: string, workspace_id: string) {
if (changed) persistTouched(s)
}
// Park a just-created session on a workspace. Deliberately does not persist a
// still-transient draft: picking where it will live is part of creating it, not a
// user touch, so an unused draft still vanishes on reload (see `transient`).
export function setNewSessionWorkspace(id: string, workspace_id: string) {
const s = sessionState.sessions.find((x) => x.id === id)
if (!s) return
s.pending_workspace_id = workspace_id
s.pending_fork = undefined
if (!s.transient) persistTouched(s)
}
// Records the user's intent to create a new fork without firing the API
// call yet. Routing/scope stay on the parent workspace until commit.
export function setSessionPendingFork(id: string, fork: PendingFork) {
const s = sessionState.sessions.find((x) => x.id === id)
if (!s) return
s.pending_fork = { ...fork }
s.pending_workspace_id = fork.parent_workspace_id
persistTouched(s)
}
// One-shot commit: locks in workspace_id at first user-message send.
// If a pending fork is set, materialises it via the API first, then
// switches the global workspace to the freshly created fork. Falls back
@@ -4,8 +4,9 @@ import {
commitSessionWorkspace,
createSession,
decideSessionLifecycle,
findEmptyLandingSession,
getSessionDraftAttachments,
holdHomeDraft,
homeDraft,
homeStarterSession,
isForkSession,
isTearingDownOpenSession,
@@ -19,11 +20,6 @@ import {
withOpenSessionTeardown,
type Session
} from './sessionState.svelte'
import {
clearSessionRecovered,
isSessionRecovered,
markSessionRecovered
} from './sessionRecoveryNotice.svelte'
import {
enterpriseLicense,
usersWorkspaceStore,
@@ -488,28 +484,6 @@ describe('createSession — reuses an untouched draft, family-scoped', () => {
}
})
it('clears the recovery notice off the draft it reuses, so `+` is not answered with "not found"', () => {
const restore = withTwoFamilies('rootA')
const prevCurrent = sessionState.currentSessionId
const landed = session({
id: 'recovered-blank',
name: 'session-903',
pending_workspace_id: 'forkA',
transient: true
})
sessionState.sessions.push(landed)
markSessionRecovered(landed.id)
try {
expect(createSession().id).toBe('recovered-blank')
expect(isSessionRecovered('recovered-blank')).toBe(false)
} finally {
clearSessionRecovered('recovered-blank')
sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'recovered-blank')
sessionState.currentSessionId = prevCurrent
restore()
}
})
it('drops an untouched draft left over from another family and starts in the active workspace', () => {
const restore = withTwoFamilies('rootB')
const prevCurrent = sessionState.currentSessionId
@@ -637,59 +611,6 @@ describe('createSession — reuses an untouched draft, family-scoped', () => {
})
})
describe('findEmptyLandingSession — where an unresolvable session link lands', () => {
it('takes an untouched draft', () => {
const restore = withTwoFamilies('forkA')
const blank = session({
id: 'landing-blank',
name: 'session-910',
pending_workspace_id: 'forkA',
transient: true
})
sessionState.sessions.push(blank)
try {
expect(findEmptyLandingSession()?.id).toBe('landing-blank')
} finally {
sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'landing-blank')
restore()
}
})
it('passes over a persisted session, which may hold a conversation', () => {
const restore = withTwoFamilies('forkA')
// Persisted means touched: its chat can hold a conversation initRuntime
// reloads, without touching a field checked here.
const abandoned = session({
id: 'landing-abandoned',
name: 'session-910',
pending_workspace_id: 'forkA'
})
const others = sessionState.sessions
sessionState.sessions = [abandoned]
try {
expect(findEmptyLandingSession()).toBeUndefined()
} finally {
sessionState.sessions = others
restore()
}
})
it('passes over a session that has been sent, so recovery never reopens a conversation', () => {
const restore = withTwoFamilies('forkA')
const sent = session({ id: 'landing-sent', name: 'session-911', workspace_id: 'forkA' })
// Sole candidate, so `undefined` pins the exclusion: `not.toBe` would also
// pass on any unrelated session the shared module state happens to hold.
const others = sessionState.sessions
sessionState.sessions = [sent]
try {
expect(findEmptyLandingSession()).toBeUndefined()
} finally {
sessionState.sessions = others
restore()
}
})
})
describe('withOpenSessionTeardown — the gate that holds recovery off during a delete', () => {
it('stays shut until the outermost teardown finishes', async () => {
let innerDone = false
@@ -717,7 +638,7 @@ describe('homeStarterSession', () => {
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.
// Stored, though it holds no text: 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',
@@ -729,7 +650,7 @@ describe('homeStarterSession', () => {
sessionState.currentSessionId = 'conversation'
try {
expect(homeStarterSession().id).toBe('picked-draft')
// Opening Home must leave the AI Sessions switch resuming the conversation.
// Home's draft is not the session open on the sessions page.
expect(sessionState.currentSessionId).toBe('conversation')
} finally {
sessionState.sessions = sessionState.sessions.filter(
@@ -740,6 +661,31 @@ describe('homeStarterSession', () => {
}
})
it('keeps the draft Home holds, acting on the header workspace within its family only', () => {
const restore = withTwoFamilies('forkA')
const recent = session({ id: 'recent-draft', pending_workspace_id: 'rootA', lastActivityAt: 9 })
const held = session({ id: 'held-draft', pending_workspace_id: 'rootA', lastActivityAt: 1 })
sessionState.sessions.push(recent, held)
const heldNow = () => sessionState.sessions.find((s) => s.id === 'held-draft')
try {
holdHomeDraft('held-draft')
// A blank asked for by New session, or a draft picked in the list, beats the
// family's most recent one.
expect(homeStarterSession().id).toBe('held-draft')
expect(heldNow()?.pending_workspace_id).toBe('forkA')
// Another family's header does not take the draft along: Home shows that family's.
workspaceStore.set('rootB')
holdHomeDraft('held-draft')
expect(heldNow()?.pending_workspace_id).toBe('forkA')
} finally {
homeDraft.id = undefined
sessionState.sessions = sessionState.sessions.filter(
(s) => !['recent-draft', 'held-draft'].includes(s.id)
)
restore()
}
})
it('reports the never-touched drafts it drops, so their runtimes can be disposed', () => {
const restore = withTwoFamilies('rootB')
const prevCurrent = sessionState.currentSessionId
@@ -2,166 +2,142 @@ import { get } from 'svelte/store'
import { goto } from '$lib/navigation'
import { workspaceStore } from '$lib/stores'
import {
blankHomeDraft,
createSession,
homeDraft,
opensOnHome,
selectSession,
sessionPageHref,
sessionInCurrentFamily,
sessionLastActivityAt,
sessionPageHref,
sessionState,
setSessionAutoSend,
setSessionDraftPrompt,
setSessionPendingWorkspace,
showOnHome,
syncWorkspaceTo,
type Session,
type SessionTarget
} from './sessionState.svelte'
import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte'
import { parsePipelineRoute, parsePreviewItemRoute } from './previewPaths'
import { findMountedOpenInSessionSource } from './openInSessionContext'
import { homeSidebarList, type SidebarList } from './sidebarList.svelte'
import { hrefAfterWorkspaceSwitch } from '../sidebar/workspaceSwitchUrl'
import { pinHomeComposer } from '../home/homeComposerPin.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'
// The session/navigation switch turns the global rail into either the workspace
// navigation (navigation mode) or the sessions sidebar (session mode). Session
// mode is route-derived — it is exactly "on the /sessions page" — so the switch
// is just navigation in and out of that route.
// The Workspace ⇄ AI Sessions switch moves between two places worked in side by side,
// and comes back to each where it was left. Plain module state: read only in click
// handlers, never rendered. A reload forgets both, and the switch then falls back to
// Home and to the family's most recently used session.
// The last non-session route the user was on, so exiting session mode returns
// them where they were instead of dumping them on the home page. Stored as a
// base-prefixed pathname (+ search); `goto` is base-idempotent so re-prefixing
// is safe. Plain module state: it is read only inside click handlers, never
// rendered, so it needs no reactivity.
let lastNavRoute = '/'
// Whether `lastNavRoute` has been offered as a new session's starting point since
// it was remembered (see takeNewSessionSeed).
let navRouteOffered = false
// The last page shown with the workspace nav beside it, Home included, as a pathname
// with its search, and the workspace it was shown in.
let workspacePage: { href: string; workspace: string | undefined } | undefined
// The session last opened, on its page or in Home's composer.
let lastSessionId: string | undefined
export function rememberNavRoute(pathnameWithSearch: string): void {
lastNavRoute = pathnameWithSearch
navRouteOffered = false
/** The page Workspace returns to. Called on every arrival with the workspace nav shown,
* and by an in-place URL rewrite the router doesn't report as a navigation. */
export function rememberWorkspacePage(href: string): void {
workspacePage = { href, workspace: get(workspaceStore) ?? undefined }
}
/** An item editor the user reached session mode from, as the in-app href a new
* session's preview can open, plus what it edits (for naming it). */
export type NewSessionSeed = { url: string; kind: string; path: string }
/** What an editor route edits: a session target, or an unset target for an item
* with no in-session editor (a legacy app), which is opened by its page instead. */
function editedAt(
url: string
): { target: SessionTarget | undefined; kind: string; path: string } | undefined {
const folder = parsePipelineRoute(url)
if (folder)
return { target: { kind: 'pipeline', path: folder }, kind: 'pipeline', path: `f/${folder}` }
const route = parsePreviewItemRoute(url)
if (!route) return undefined
const kind = route.kind === 'app' ? (route.raw_app ? 'raw_app' : undefined) : route.kind
return {
target: kind ? { kind, path: route.itemPath } : undefined,
kind: route.kind,
path: route.itemPath
/** Where a navigation landed, for the switch to come back to. Landing anywhere but Home
* also sets the list Home will show. */
export function noteArrival(url: URL): void {
if (url.pathname.startsWith('/sessions')) {
homeSidebarList.val = 'sessions'
lastSessionId = url.searchParams.get('session') ?? lastSessionId
return
}
if (url.pathname !== '/') homeSidebarList.val = 'workspace'
if (homeSidebarList.val === 'workspace') rememberWorkspacePage(url.pathname + url.search)
}
// The item (flow, script, app, pipeline) the user came to session mode from, or undefined
// when they came from anywhere else. A "New session" asked for after arriving
// from an item is usually a session about that item, but the arrival route
// (`enterSessionMode`) resumes whatever session was open, so the picker offers
// the item back. Offered once per remembered route: the first "New session" of
// a visit gets the question, however long the visit has run and whatever was
// done in between; later ones start empty without asking, and a dismissed offer
// is not repeated until the user leaves for another page and comes back.
export function takeNewSessionSeed(): NewSessionSeed | undefined {
if (navRouteOffered) return undefined
navRouteOffered = true
const edited = editedAt(lastNavRoute)
return edited ? { url: lastNavRoute, kind: edited.kind, path: edited.path } : undefined
/** The switch on Home, which belongs to both lists: it swaps the list and stays. */
export function swapHomeList(list: SidebarList, homeHref: string): void {
homeSidebarList.val = list
if (list === 'workspace') rememberWorkspacePage(homeHref)
}
// The session entering session mode resumes: the active one if selected, else
// the most recent non-archived one. Scoped to the active workspace family:
// reviving a session from another family would pull that family's scope
// (sidebar list, "Acting on" workspace) into the one the user is actually in.
// The session last opened, else the family's most recently used one. Scoped to the
// family: reviving another family's session would pull its scope into this one.
function resumableSession(): Session | undefined {
const current = sessionState.currentSessionId
? sessionState.sessions.find((s) => s.id === sessionState.currentSessionId)
: undefined
return (
(current && sessionInCurrentFamily(current) ? current : undefined) ??
sessionState.sessions.find((s) => !s.archived && sessionInCurrentFamily(s))
)
const usable = (s: Session) => !s.archived && sessionInCurrentFamily(s)
const last = sessionState.sessions.find((s) => s.id === lastSessionId)
if (last && usable(last)) return last
return sessionState.sessions
.filter((s) => usable(s) && !s.transient)
.sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0]
}
// Enter session mode: resume the session `resumableSession` picks, else spin up
// a fresh one — then route to it.
// `replace` swaps the current history entry instead of pushing — for the
// sessions page's family reconcile, where Back must not return to the
// redirected-away URL just to bounce here again.
export async function enterSessionMode(opts?: { replace?: boolean }): Promise<void> {
const target = resumableSession() ?? createSession()
selectSession(target.id)
await goto(sessionPageHref(target.id), {
replaceState: opts?.replace ?? false
})
}
// How long the resumable session may have sat idle before entering from an item
// editor starts a session on that item instead. Long enough that stepping out to
// the editor in the middle of a conversation comes back to the same chat; short
// enough that a session left since the previous day is not taken for the task
// the user is now on.
const RESUME_IDLE_LIMIT_MS = 60 * 60 * 1000
// Enter session mode from the navigation rail. Coming from an item editor with
// no session to resume, or one idle past RESUME_IDLE_LIMIT_MS, opens a fresh
// session on that item straight away: a session that old is rarely what a visit
// from a flow or app is about, and landing in it would only lead to "New
// session" and the offer takeNewSessionSeed makes. Anything else resumes as
// enterSessionMode does. Rejects when the editor could not persist its draft,
// so the caller can stay on the page and say so.
export async function enterSessionModeFromNav(): Promise<void> {
const edited = editedAt(lastNavRoute)
if (edited) {
const resumable = resumableSession()
if (!resumable || Date.now() - sessionLastActivityAt(resumable) > RESUME_IDLE_LIMIT_MS) {
// The editor's own hand-off is what its "Open in AI session" button uses:
// it persists the draft the preview loads (an edit still inside the
// autosave debounce, the row of a never-saved new item) and names the
// workspace the item lives in. Only an item with no such editor on
// screen (a legacy app, a detail page) is opened by route, as last
// persisted, in the workspace the route was scoped to.
const source = edited.target && findMountedOpenInSessionSource(edited.target)
if (source) await openSourceInSession(source)
else await openPageInSession(lastNavRoute, workspaceParamOf(lastNavRoute))
return
}
/** AI Sessions, from anywhere but Home: the session to resume on its page, or in Home's
* composer for an unsent draft, else a blank draft there. `replace` for the sessions
* page's own redirects, where Back must not return to the URL that bounced here. */
export async function resumeAiSessions(opts?: { replace?: boolean }): Promise<void> {
const session = resumableSession()
if (!session || opensOnHome(session)) {
await toHome((session ?? blankHomeDraft()).id, opts)
return
}
await enterSessionMode()
selectSession(session.id)
await goto(sessionPageHref(session.id), { replaceState: opts?.replace ?? false })
}
function workspaceParamOf(pathnameWithSearch: string): string | undefined {
const query = pathnameWithSearch.split('?')[1]
return query ? (new URLSearchParams(query).get('workspace') ?? undefined) : undefined
/** Workspace, from a session's page: the page it was left on, else Home. One left in
* another workspace than the header's is moved by the workspace picker's rule: restored
* as it was, its item could be missing here or its params switch the workspace back. */
export async function returnToWorkspace(): Promise<void> {
homeSidebarList.val = 'workspace'
const left = workspacePage
const ws = get(workspaceStore) ?? undefined
let href = left?.href ?? '/'
if (left && ws && left.workspace !== ws) href = hrefAfterWorkspaceSwitch(left.href, ws)
await goto(href)
}
// Exit session mode: back to the last navigation route (home as a fallback).
export async function exitSessionMode(): Promise<void> {
let target = lastNavRoute || '/'
// The remembered route can carry a stale `?workspace=` — the layout's
// onQueryChange re-applies that param, so restoring the route would
// silently check the app back out to a workspace the user has since
// left. The rest of the route is scoped to that stale workspace too,
// so fall back to home rather than rewriting the param.
const wsParam = /[?&]workspace=([^&]*)/.exec(target)?.[1]
const ws = get(workspaceStore)
if (ws && wsParam && decodeURIComponent(wsParam) !== ws) {
target = '/'
}
await goto(target)
// A plain session starts on Home, and an unsent draft is shown there rather than on a
// page of its own, with the session list beside it. Asking for one puts the composer
// back on Home if the reader had unpinned it: there is nowhere else to type it.
async function toHome(id: string, opts?: { replace?: boolean }): Promise<void> {
homeSidebarList.val = 'sessions'
lastSessionId = id
showOnHome(id, { focus: true })
pinHomeComposer()
// `goto` has no same-URL short-circuit, so navigating from Home would push a
// duplicate history entry; showOnHome already remounts the composer there.
if (typeof window !== 'undefined' && window.location.pathname === '/') return
await goto('/', { replaceState: opts?.replace ?? false })
}
/** New session: Home's composer, blank and focused. It acts on the header's workspace,
* switched to `workspaceId` first when given. A draft already typed stays in the list. */
export async function openNewSession(workspaceId?: string): Promise<void> {
// Home's current draft stays where it is: the switch below must not take it along.
homeDraft.id = undefined
if (workspaceId) syncWorkspaceTo(workspaceId)
await toHome(blankHomeDraft().id)
}
/** An unsent draft, opened in Home's composer. `replace` for a redirect off the sessions
* page, where Back must not return to the URL that bounced here. */
export async function openDraftOnHome(id: string, opts?: { replace?: boolean }): Promise<void> {
await toHome(id, opts)
}
/** Where to go once the session on screen is gone (archived, deleted, not in this browser):
* Home, showing whichever draft it would pick anyway. */
export async function leaveForHome(opts?: { replace?: boolean }): Promise<void> {
homeDraft.id = undefined
homeDraft.requests++
if (typeof window !== 'undefined' && window.location.pathname === '/') return
await goto('/', { replaceState: opts?.replace ?? false })
}
// Open a fresh AI session showing an editor (flow/script/raw_app) in its preview,
// then route into session mode. The preview loads the item from its live draft,
// then route to its page. The preview loads the item from its live draft,
// so the caller MUST persist any unsaved edits first (e.g. save a draft) for the
// preview to reflect the live state. `workspaceId` scopes the session to the
// editor's workspace (instead of createSession's root default) so it opens the
@@ -229,9 +205,6 @@ async function sessionHrefFor(
// node-run unit tests.
const { resetSessionPreviewTabs } = await import('./sessionRuntime.svelte')
resetSessionPreviewTabs(session.id, url)
// Hand-offs seed the page they leave, so the arrival has opened the item
// itself and "New session" need not offer it again.
navRouteOffered = true
}
selectSession(session.id)
return sessionPageHref(session.id)
@@ -265,9 +238,8 @@ export async function openSourceInSession(
// Open a fresh session on no particular item, with `prompt` pre-filled in the
// composer. For entry points that carry a question rather than a target (the
// 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.
// global search's "Ask AI"). Always a new session, so the seed cannot overwrite
// a prompt the user has already typed into another one.
export async function startSessionWithPrompt(
prompt: string,
opts?: { autoSend?: boolean }
@@ -1,14 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { get } from 'svelte/store'
import {
enterSessionMode,
enterSessionModeFromNav,
noteArrival,
openSourceInSession,
rememberNavRoute,
startSessionWithPrompt,
takeNewSessionSeed
resumeAiSessions,
returnToWorkspace,
startSessionWithPrompt
} from './sessionSwitch.svelte'
import {
homeDraft,
peekSessionAutoSend,
sessionState,
takeSessionAutoSend,
@@ -23,96 +23,101 @@ import { goto } from '$lib/navigation'
// monaco (hence that import being dynamic in the first place) and cannot load
// under node.
vi.mock('./sessionRuntime.svelte', () => ({ resetSessionPreviewTabs: vi.fn() }))
import { resetSessionPreviewTabs } from './sessionRuntime.svelte'
import { registerMountedOpenInSessionHandoff } from './openInSessionContext'
function session(over: Partial<Session> = {}): Session {
return { id: 's1', name: 'sess', createdAt: 0, ...over }
}
function ws(id: string, parent?: string): UserWorkspace {
return { id, name: id, parent_workspace_id: parent } as unknown as UserWorkspace
}
// Two-family fixture: rootA (with forkA) and rootB. Returns a restore fn.
function session(over: Partial<Session> & { id: string }): Session {
return { createdAt: 0, ...over }
}
// Two families: rootA (with forkA) and rootB. Returns a restore fn.
function withTwoFamilies(activeWorkspace: string): () => void {
const prevUsers = get(usersWorkspaceStore)
const prevWs = get(workspaceStore)
const prevCurrent = sessionState.currentSessionId
usersWorkspaceStore.set({
email: 't@t',
workspaces: [ws('rootA'), ws('forkA', 'rootA'), ws('rootB')]
} as never)
workspaceStore.set(activeWorkspace)
return () => {
sessionState.sessions = sessionState.sessions.filter((s) => !s.id.startsWith('sw-'))
sessionState.currentSessionId = prevCurrent
usersWorkspaceStore.set(prevUsers)
workspaceStore.set(prevWs)
}
}
describe('enterSessionMode — restore is scoped to the active family', () => {
describe('the sidebar switch comes back where each side was left', () => {
beforeEach(() => {
vi.mocked(goto).mockClear()
})
it('keeps the current session when it belongs to the active family', async () => {
it('resumes the session last opened, within the active family', async () => {
const restore = withTwoFamilies('forkA')
const prevCurrent = sessionState.currentSessionId
const inFamily = session({ id: 'sw-in-family', name: 'session-911', workspace_id: 'rootA' })
sessionState.sessions.push(inFamily)
sessionState.currentSessionId = 'sw-in-family'
sessionState.sessions.push(
session({ id: 'sw-opened', workspace_id: 'rootA', lastActivityAt: 1 }),
session({ id: 'sw-recent', workspace_id: 'forkA', lastActivityAt: 2 }),
session({ id: 'sw-foreign', workspace_id: 'rootB', lastActivityAt: 3 })
)
try {
await enterSessionMode()
expect(sessionState.currentSessionId).toBe('sw-in-family')
expect(goto).toHaveBeenCalledWith('/sessions?session=sw-in-family', {
noteArrival(new URL('http://localhost/sessions?session=sw-opened'))
await resumeAiSessions()
expect(goto).toHaveBeenLastCalledWith('/sessions?session=sw-opened', {
replaceState: false
})
// Another family's session would pull its scope into this one: the family's most
// recently used session stands in.
noteArrival(new URL('http://localhost/sessions?session=sw-foreign'))
await resumeAiSessions()
expect(goto).toHaveBeenLastCalledWith('/sessions?session=sw-recent', {
replaceState: false
})
} finally {
sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'sw-in-family')
sessionState.currentSessionId = prevCurrent
restore()
}
})
it('skips a cross-family current session in favor of the most recent in-family one', async () => {
const restore = withTwoFamilies('rootB')
const prevCurrent = sessionState.currentSessionId
const foreign = session({ id: 'sw-foreign', name: 'session-912', workspace_id: 'rootA' })
const local = session({ id: 'sw-local', name: 'session-913', workspace_id: 'rootB' })
sessionState.sessions.push(foreign, local)
sessionState.currentSessionId = 'sw-foreign'
it('reopens an unsent draft in Home’s composer', async () => {
const restore = withTwoFamilies('rootA')
sessionState.sessions.push(
session({ id: 'sw-draft', pending_workspace_id: 'rootA', draftPrompt: 'half typed' })
)
// Switched from a workspace page, so Home is not already open.
vi.stubGlobal('window', { location: { pathname: '/runs' } })
try {
await enterSessionMode()
expect(sessionState.currentSessionId).toBe('sw-local')
expect(goto).toHaveBeenCalledWith('/sessions?session=sw-local', {
replaceState: false
})
noteArrival(new URL('http://localhost/sessions?session=sw-draft'))
await resumeAiSessions()
expect(goto).toHaveBeenLastCalledWith('/', { replaceState: false })
expect(homeDraft.id).toBe('sw-draft')
} finally {
sessionState.sessions = sessionState.sessions.filter(
(s) => s.id !== 'sw-foreign' && s.id !== 'sw-local'
)
sessionState.currentSessionId = prevCurrent
vi.unstubAllGlobals()
homeDraft.id = undefined
restore()
}
})
it('creates a fresh session in the active workspace when no in-family session exists', async () => {
const restore = withTwoFamilies('rootB')
const prevCurrent = sessionState.currentSessionId
const foreign = session({ id: 'sw-only-foreign', name: 'session-914', workspace_id: 'rootA' })
sessionState.sessions.push(foreign)
sessionState.currentSessionId = 'sw-only-foreign'
let createdId: string | undefined
it('returns to the workspace page left, moved by the picker’s rule after a switch', async () => {
const restore = withTwoFamilies('rootA')
try {
await enterSessionMode()
createdId = sessionState.currentSessionId
expect(createdId).not.toBe('sw-only-foreign')
const created = sessionState.sessions.find((s) => s.id === createdId)
expect(created?.pending_workspace_id).toBe('rootB')
expect(created?.transient).toBe(true)
noteArrival(new URL('http://localhost/runs?workspace=rootA'))
// Home with the session list beside it is not a workspace page to come back to.
noteArrival(new URL('http://localhost/sessions?session=sw-any'))
noteArrival(new URL('http://localhost/'))
await returnToWorkspace()
expect(goto).toHaveBeenLastCalledWith('/runs?workspace=rootA')
workspaceStore.set('rootB')
await returnToWorkspace()
expect(goto).toHaveBeenLastCalledWith('/runs?workspace=rootB')
noteArrival(new URL('http://localhost/flows/edit/f/foo'))
workspaceStore.set('rootA')
await returnToWorkspace()
expect(goto).toHaveBeenLastCalledWith('/')
} finally {
sessionState.sessions = sessionState.sessions.filter(
(s) => s.id !== 'sw-only-foreign' && s.id !== createdId
)
sessionState.currentSessionId = prevCurrent
restore()
}
})
@@ -253,165 +258,3 @@ describe('startSessionWithPrompt', () => {
}
})
})
describe('takeNewSessionSeed', () => {
it('offers the item editor the user came from, once per arrival', () => {
rememberNavRoute('/flows/edit/u/me/my_flow?workspace=ws')
expect(takeNewSessionSeed()).toEqual({
url: '/flows/edit/u/me/my_flow?workspace=ws',
kind: 'flow',
path: 'u/me/my_flow'
})
// A dismissed or taken offer is not repeated until the user leaves again.
expect(takeNewSessionSeed()).toBeUndefined()
rememberNavRoute('/apps_raw/edit/f/team/dashboard?workspace=ws')
expect(takeNewSessionSeed()).toMatchObject({ kind: 'app', path: 'f/team/dashboard' })
})
it('offers the pipeline the user came from, named by its folder', () => {
rememberNavRoute('/pipeline/crm?workspace=ws')
expect(takeNewSessionSeed()).toEqual({
url: '/pipeline/crm?workspace=ws',
kind: 'pipeline',
path: 'f/crm'
})
})
it('offers nothing for a non-item page', () => {
rememberNavRoute('/runs?workspace=ws')
expect(takeNewSessionSeed()).toBeUndefined()
})
})
describe('enterSessionModeFromNav', () => {
const HOUR = 60 * 60 * 1000
beforeEach(() => {
vi.mocked(goto).mockClear()
vi.mocked(resetSessionPreviewTabs).mockClear()
})
// One session in the active family (rootA), as the one the rail would resume.
// Restores everything the test touched, the module-level nav route included,
// and drops whatever session the call under test created.
function withResumable(over: Partial<Session>): { restore: () => void } {
const restoreFamilies = withTwoFamilies('rootA')
const prevCurrent = sessionState.currentSessionId
const before = new Set(sessionState.sessions.map((s) => s.id))
const s = session({ workspace_id: 'rootA', ...over })
sessionState.sessions.push(s)
sessionState.currentSessionId = s.id
return {
restore: () => {
sessionState.sessions = sessionState.sessions.filter((x) => before.has(x.id))
sessionState.currentSessionId = prevCurrent
rememberNavRoute('/')
restoreFamilies()
}
}
}
it('resumes a recently active session even when coming from an item', async () => {
const { restore } = withResumable({
id: 'nav-recent',
name: 'session-921',
lastActivityAt: Date.now() - HOUR / 2
})
try {
rememberNavRoute('/flows/edit/u/me/f?workspace=rootA')
await enterSessionModeFromNav()
expect(sessionState.currentSessionId).toBe('nav-recent')
expect(resetSessionPreviewTabs).not.toHaveBeenCalled()
} finally {
restore()
}
})
it('starts a session on the item, by route, instead of resuming one idle for hours', async () => {
const { restore } = withResumable({
id: 'nav-stale',
name: 'session-922',
lastActivityAt: Date.now() - 3 * HOUR
})
try {
rememberNavRoute('/flows/edit/u/me/f?workspace=forkA')
await enterSessionModeFromNav()
const createdId = sessionState.currentSessionId
expect(createdId).not.toBe('nav-stale')
expect(resetSessionPreviewTabs).toHaveBeenCalledWith(
createdId,
'/flows/edit/u/me/f?workspace=forkA'
)
// The route's workspace, not createSession's pick for the active one.
const created = sessionState.sessions.find((s) => s.id === createdId)
expect(created?.pending_workspace_id).toBe('forkA')
// The arrival opened the item itself, so "New session" does not offer it.
expect(takeNewSessionSeed()).toBeUndefined()
} finally {
restore()
}
})
// The editor's hand-off is what its own "Open in AI session" button uses: its
// beforeOpen persists the draft the preview loads, and it names the item's
// workspace. The rail must take it over opening the route as last persisted.
it('hands off through the mounted editor of the item, running its beforeOpen first', async () => {
const { restore } = withResumable({
id: 'nav-stale-editor',
name: 'session-924',
lastActivityAt: Date.now() - 3 * HOUR
})
const order: string[] = []
vi.mocked(goto).mockImplementation((async () => {
order.push('goto')
}) as never)
// A script editor mounted alongside (a flow's drawer) must not be taken
// for the page's own item.
const unregisterScript = registerMountedOpenInSessionHandoff({
source: () => ({ target: { kind: 'script', path: 'u/me/s' }, workspaceId: 'rootB' })
})
const unregisterFlow = registerMountedOpenInSessionHandoff({
source: () => ({
target: { kind: 'flow', path: 'u/me/f' },
workspaceId: 'forkA',
beforeOpen: () => {
order.push('beforeOpen')
}
})
})
try {
rememberNavRoute('/flows/edit/u/me/f?workspace=rootA')
await enterSessionModeFromNav()
const createdId = sessionState.currentSessionId
expect(createdId).not.toBe('nav-stale-editor')
expect(order).toEqual(['beforeOpen', 'goto'])
expect(resetSessionPreviewTabs).toHaveBeenCalledWith(
createdId,
expect.stringMatching(/\/flows\/edit\/u\/me\/f$/)
)
const created = sessionState.sessions.find((s) => s.id === createdId)
expect(created?.pending_workspace_id).toBe('forkA')
} finally {
unregisterFlow()
unregisterScript()
vi.mocked(goto).mockReset()
vi.mocked(goto).mockResolvedValue(undefined as never)
restore()
}
})
it('resumes a stale session when coming from a non-item page', async () => {
const { restore } = withResumable({
id: 'nav-stale-runs',
name: 'session-923',
lastActivityAt: Date.now() - 3 * HOUR
})
try {
rememberNavRoute('/runs?workspace=rootA')
await enterSessionModeFromNav()
expect(sessionState.currentSessionId).toBe('nav-stale-runs')
expect(resetSessionPreviewTabs).not.toHaveBeenCalled()
} finally {
restore()
}
})
})
@@ -0,0 +1,27 @@
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
import { clearSessionsBetaOptOut } from '$lib/components/copilot/chat/global/gate'
export type SidebarList = 'workspace' | 'sessions'
/** The list the sidebar shows while Home is open. Every other page decides its own (a
* session's page lists sessions, any other page the workspace nav) and, on arrival, sets
* this to it: Home sits above the switch and belongs to both, so it keeps the list you
* came from, until you go into its composer (HomeAIChat). Per browser, so a reload of Home
* keeps it too. */
export const homeSidebarList = useLocalStorageValue<SidebarList>(
'windmill_sidebar_list',
'workspace',
'string'
)
/** The list the sidebar shows beside `pathname`. */
export function sidebarListFor(pathname: string): SidebarList {
if (pathname.startsWith('/sessions')) return 'sessions'
return pathname === '/' ? homeSidebarList.val : 'workspace'
}
/** Turning AI Sessions back on asks to see them: Home, with the session list beside it. */
export function activateAiSessions(): void {
homeSidebarList.val = 'sessions'
clearSessionsBetaOptOut('/')
}
@@ -1,10 +1,10 @@
// Href for a workspace-switch link in the sidebar WorkspaceMenu: stay on the
// current path and just swap the `workspace` query param, so a modifier/middle
// click (open in new tab, which bypasses the onClick fast-path) lands on the
// same page — session mode included — in the *clicked* workspace. A session
// same page — a session's included — in the *clicked* workspace. A session
// named in the URL is kept only for same-family targets: a cross-family tab
// must not open a foreign family's chat, so it lands on the sessions page with
// nothing selected instead.
// must not open a foreign family's chat, so it drops the session, and the
// sessions page resumes one of the clicked family's own instead.
export function workspaceMenuHref(args: {
pathname: string
searchParams: URLSearchParams
@@ -1,12 +1,13 @@
import { page } from '$app/state'
import { goto } from '$lib/navigation'
// Post-workspace-switch URL fixup shared by the sidebar workspace pickers.
// Post-workspace-switch URL fixup shared by the sidebar workspace pickers, and by the
// Workspace side of the sidebar switch for a page it left before a switch.
// Item-scoped pages would show a wrong-workspace (or missing) item after a
// switch — go home instead. Otherwise, really rewrite the params in the address
// bar that name a workspace (mutating page.url is a no-op there): left stale,
// they get re-applied on reload or when exiting session mode restores the route,
// silently switching the workspace back.
// they get re-applied on reload or when the switch restores the page, silently
// switching the workspace back.
//
// `workspace_id` names the workspace a page acts on (the compare page's pair) and
// `workspace` the one the app is pointed at; a switch moves both. `target`, the
@@ -26,21 +27,13 @@ const EDIT_PAGES = [
'/apps_raw/get/'
]
export async function fixupUrlAfterWorkspaceSwitch(
id: string,
// Decided by the caller so the rule stays with the picker that has the context
// for it — a picker rendered outside the sidebar drives its own page and must
// not be navigated away from.
opts?: { landOnHome?: boolean }
): Promise<void> {
if (EDIT_PAGES.some((p) => page.route.id?.includes(p) ?? false) || opts?.landOnHome) {
await goto('/')
return
}
// `window.location`, never `page.url`: a param written by a previous shallow update
// is in the address bar but not in `page.url`, so rebuilding from it would undo that
// write (see the note on `setQuery` in $lib/navigation).
const url = new URL(window.location.href)
/** Matches a route id or a pathname alike. */
function isItemPage(route: string): boolean {
return EDIT_PAGES.some((p) => route.includes(p))
}
/** Points the params naming a workspace at `id`; whether anything changed. */
function moveWorkspaceParams(url: URL, id: string): boolean {
let changed = false
for (const key of WORKSPACE_PARAMS) {
if (url.searchParams.get(key) === id) continue
@@ -53,7 +46,33 @@ export async function fixupUrlAfterWorkspaceSwitch(
url.searchParams.delete(key)
changed = true
}
if (!changed) return
return changed
}
/** Where `href` (a pathname with its search) leads once the app has switched to `id`. */
export function hrefAfterWorkspaceSwitch(href: string, id: string): string {
const url = new URL(href, 'http://localhost')
if (isItemPage(url.pathname)) return '/'
moveWorkspaceParams(url, id)
return `${url.pathname}${url.search}${url.hash}`
}
export async function fixupUrlAfterWorkspaceSwitch(
id: string,
// Decided by the caller so the rule stays with the picker that has the context
// for it — a picker rendered outside the sidebar drives its own page and must
// not be navigated away from.
opts?: { landOnHome?: boolean }
): Promise<void> {
if (isItemPage(page.route.id ?? '') || opts?.landOnHome) {
await goto('/')
return
}
// `window.location`, never `page.url`: a param written by a previous shallow update
// is in the address bar but not in `page.url`, so rebuilding from it would undo that
// write (see the note on `setQuery` in $lib/navigation).
const url = new URL(window.location.href)
if (!moveWorkspaceParams(url, id)) return
// `goto` rather than `replaceState`: a page reading these params through `page.url`
// (the compare page derives the workspace it compares from them) sees nothing when
// they are written shallowly, since SvelteKit refreshes `page.url` only on a
+8 -8
View File
@@ -18,17 +18,17 @@ vi.mock('./localDraftHints.svelte', () => ({
getLocalDraftHint: () => hints.value
}))
// `stripNewDraftFlag` rewrites the URL through SvelteKit's `replaceState` and
// refreshes the session-switch's remembered nav route. Mock those so the strip
// is observable via `window.location.href` (mirroring jsdom) and the remembered
// route can be asserted.
const rememberNavRoute = vi.hoisted(() => vi.fn())
// refreshes the page the sidebar switch returns to. Mock those so the strip is
// observable via `window.location.href` (mirroring jsdom) and the remembered
// page can be asserted.
const rememberWorkspacePage = vi.hoisted(() => vi.fn())
vi.mock('$app/navigation', () => ({
replaceState: (url: URL | string, _state: unknown) => {
window.location.href = new URL(url, window.location.href).toString()
}
}))
vi.mock('$app/state', () => ({ page: { state: {} } }))
vi.mock('$lib/components/sessions/sessionSwitch.svelte', () => ({ rememberNavRoute }))
vi.mock('$lib/components/sessions/sessionSwitch.svelte', () => ({ rememberWorkspacePage }))
import { UserDraftDbSyncer } from './userDraftDbSyncer.svelte'
import { stripNewDraftFlagOnSave, shouldSeedNewDraft } from './newDraftFlag'
@@ -120,9 +120,9 @@ describe('stripNewDraftFlagOnSave', () => {
expect(window.location.href).not.toContain('new_draft')
// Sibling seeding params are preserved.
expect(window.location.href).toContain('template=foo')
// The remembered nav route is refreshed to the stripped URL so exiting an
// AI session returns here without re-adding ?new_draft.
expect(rememberNavRoute).toHaveBeenCalledWith('/scripts/edit/u/me/draft_d?template=foo')
// The switch's Workspace side returns to the stripped URL, so it does not
// come back with ?new_draft.
expect(rememberWorkspacePage).toHaveBeenCalledWith('/scripts/edit/u/me/draft_d?template=foo')
})
it('does not strip on a delete save', async () => {
+9 -8
View File
@@ -1,6 +1,6 @@
import { page } from '$app/state'
import { replaceState } from '$app/navigation'
import { rememberNavRoute } from '$lib/components/sessions/sessionSwitch.svelte'
import { rememberWorkspacePage } from '$lib/components/sessions/sessionSwitch.svelte'
import { UserDraftDbSyncer, type UserDraftLastSyncQuery } from '$lib/userDraftDbSyncer.svelte'
import { getLocalDraftHint } from '$lib/localDraftHints.svelte'
import type { UserDraftItemKind } from '$lib/gen'
@@ -11,9 +11,9 @@ import type { UserDraftItemKind } from '$lib/gen'
*
* Uses SvelteKit's `replaceState` (not raw `history.replaceState`, which the
* router warns conflicts with it) so the history entry keeps the router's
* bookkeeping and `page.state`. Also refreshes the remembered nav route:
* `afterNavigate` never observes this in-place rewrite, so without it
* `exitSessionMode` would restore the pre-strip URL — still carrying
* bookkeeping and `page.state`. Also refreshes the page the sidebar switch's
* Workspace side returns to: `afterNavigate` never observes this in-place
* rewrite, so the switch would restore the pre-strip URL — still carrying
* `?new_draft=true` — and re-enter the seed-empty branch. */
export function stripNewDraftFlag(): void {
if (typeof window === 'undefined') return
@@ -21,7 +21,7 @@ export function stripNewDraftFlag(): void {
if (url.searchParams.get('new_draft') !== 'true') return
url.searchParams.delete('new_draft')
replaceState(url, page.state)
rememberNavRoute(url.pathname + url.search)
rememberWorkspacePage(url.pathname + url.search)
}
/**
@@ -30,9 +30,10 @@ export function stripNewDraftFlag(): void {
* The `/{scripts,flows,apps,apps_raw}/add` redirect lands the editor on
* `u/<user>/draft_<uuid>?new_draft=true`; the seed branch bootstraps an empty
* (or template/hub/fork-seeded) editor instead of fetching a row that doesn't
* exist yet. But the flag can outlive the seed: exiting an AI session restores
* the remembered nav route (still `?new_draft=true`) even though the draft was
* already materialized — by the first autosave, or by "Open in AI session"'s
* exist yet. But the flag can outlive the seed: a return to the editor's URL
* (Back, the sidebar switch's Workspace side, a link kept from before) still
* carries `?new_draft=true` after the
* draft was materialized — by the first autosave, or by "Open in AI session"'s
* `forcePersist`. Re-running the seed branch then blanks the saved draft.
*
* So gate the seed branch on `new_draft=true` AND no persisted draft this
@@ -120,7 +120,8 @@
parsePreviewItemRoute,
barePath
} from '$lib/components/sessions/previewPaths'
import { rememberNavRoute } from '$lib/components/sessions/sessionSwitch.svelte'
import { sidebarListFor } from '$lib/components/sessions/sidebarList.svelte'
import { noteArrival } from '$lib/components/sessions/sessionSwitch.svelte'
import { sessionState } from '$lib/components/sessions/sessionState.svelte'
import { restoreSessionBackups } from '$lib/components/sessions/sessionMirror.svelte'
import { currentWorkspaceRootId } from '$lib/components/sessions/sessionScope.svelte'
@@ -153,9 +154,9 @@
})
)
let menuOpen = $state(false)
// Set by the workspace⇄session switch before it navigates, so the mobile menu
// drawer stays open across a mode toggle (unlike a normal link navigation,
// which dismisses it). Consumed once in beforeNavigate.
// Set by the Workspace ⇄ AI Sessions switch before it navigates, so the mobile menu
// drawer stays open across it to show the list it switched to (unlike a normal link
// navigation, which dismisses it). Consumed once in beforeNavigate.
let preserveMenuOnNextNav = false
let globalSearchModal: GlobalSearchModal | undefined = $state(undefined)
// Persisted nav-rail collapse preference. A deliberate collapse writes to it —
@@ -302,38 +303,39 @@
let isDarkMode = useIsDarkMode()
let darkMode = $derived(isDarkMode.val)
// Session mode is route-derived: the rail shows the sessions sidebar on the
// /sessions page and the workspace navigation everywhere else. The switch
// (SessionModeSwitch) just navigates in and out of that route.
// An operator without the opt-in (`gate.ts`) is refused by /sessions, so their sidebar is not
// handed over to a session list the page behind it declines, and they keep the docked chat.
const sessionsAllowed = $derived(sessionsAllowedFor(!$roleCapabilities.code))
let sessionMode = $derived(page.url.pathname.startsWith('/sessions') && sessionsAllowed)
// Session mode points the bottom settings entry at the open session's own
// workspace. An unsent draft hasn't committed one yet, so it falls back to
let onSessionsPage = $derived(page.url.pathname.startsWith('/sessions') && sessionsAllowed)
// A session's page points the bottom settings entry at the open session's own
// workspace. An unsent session hasn't committed one yet, so it falls back to
// the family root.
let sessionSettingsWorkspace = $derived.by(() => {
if (!sessionMode) return undefined
if (!onSessionsPage) return undefined
const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId)
return current?.workspace_id ?? $currentWorkspaceRootId ?? $workspaceStore ?? undefined
})
// Inside a preview iframe the rail still renders (navigation mode), but the
// switch must not — entering session mode from within the preview would
// nest the whole experience. Hide it when embedded.
// Inside a preview iframe the rail still renders with the workspace nav, but the
// switch must not: listing sessions from within the preview would nest the
// whole experience. Hide it when embedded.
const embedded = BROWSER && window.self !== window.top
// AI sessions (beta) are on unless this browser opted out earlier (see
// `global/gate.ts`). The Workspace ⇄ Sessions switch is the only entry point,
// so it follows the gate; opted-out users get the legacy Ask-AI pane instead.
// `global/gate.ts`). The Workspace ⇄ AI Sessions switch follows the gate;
// opted-out users get the legacy Ask-AI pane instead.
// The /sessions page has its own gate for direct navigation.
const globalAiEnabled = isGlobalAiEnabled()
// A workspace that hid the assistant (`ai_config.copilot_disabled`) loses both entry
// points: the Workspace ⇄ Sessions switch and the legacy Ask-AI button.
// points: the Workspace ⇄ AI Sessions switch and the legacy Ask-AI button.
const sessionsSwitchShown = $derived(
globalAiEnabled && sessionsAllowed && !$copilotInfo.workspaceDisabled
)
// The rail's top row; the nav below it pads to the page header's height when it is absent.
const switchRowShown = $derived(!embedded && sessionsSwitchShown)
// The page picks the list: a session's page lists sessions and a workspace page shows
// the workspace nav. Home keeps the list you came from. Where the switch is hidden, so
// is the session list.
const sidebarList = $derived(sidebarListFor(page.url.pathname))
const sidebarListsSessions = $derived(switchRowShown && sidebarList === 'sessions')
const askAiShown = $derived(
(!globalAiEnabled || !sessionsAllowed) && !$copilotInfo.workspaceDisabled
)
@@ -794,13 +796,11 @@
$usedTriggerKinds = usedKinds
}
// Where each side of the Workspace ⇄ AI Sessions switch was left, so the switch comes
// back there. Not inside a preview iframe: it has no switch, and Home's list is stored
// per browser, so the frame's own navigation would set the list of the page around it.
afterNavigate((n) => {
// Remember the last navigation-mode route so exiting session mode returns
// the user where they were rather than to the home page.
const to = n.to?.url
if (to && !to.pathname.startsWith('/sessions')) {
rememberNavRoute(to.pathname + to.search)
}
if (!embedded && n.to) noteArrival(n.to.url)
})
// Narrow enough that the rail is in the way: collapse it, transiently (see `collapsedState`).
@@ -1141,19 +1141,10 @@ outside this layout, and their shortcut must reopen the URL that is their creden
<meta name="apple-mobile-web-app-title" content="Windmill" />
</svelte:head>
<!-- Home + Runs lifted to the top of the workspace nav, sitting with Favorites
and Search as the primary quick-access cluster. Excluded from SidebarContent
(via excludeMainLabels) so they aren't rendered twice. -->
<!-- Runs lifted to the top of the workspace nav, sitting with Favorites and Search as the
primary quick-access cluster. Excluded from SidebarContent (via excludeMainLabels), as
Home is, so neither is rendered twice. -->
{#snippet quickLinks(collapsed: boolean)}
<MenuLink
class="!text-xs"
label="Home"
href="/"
icon={Home}
isCollapsed={collapsed}
aiId="sidebar-menu-link-home"
aiDescription="Button to navigate to home which contains all the user's scripts, flows and apps"
/>
<MenuLink
class="!text-xs"
label="Runs"
@@ -1171,7 +1162,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden
/>
{/snippet}
<!-- In the rail's pinned footer, right above the plan usage, in both rails and both modes:
<!-- In the rail's pinned footer, right above the plan usage, in both rails and both lists:
an account with no credentials of its own needs to see this wherever it is on the
page and however far the nav has scrolled, and the footer is where the rail already
keeps what is about the account rather than the workspace. -->
@@ -1218,9 +1209,9 @@ outside this layout, and their shortcut must reopen the URL that is their creden
</div>
{/snippet}
<!-- Settings / instance section. Shared by both sidebar surfaces and both modes
(in nav mode it's the last section inside the unified scroll area; in session
mode it stays pinned under the session list). -->
<!-- Settings / instance section. Shared by both sidebar surfaces and both lists
(under the workspace nav it's the last section inside the unified scroll area;
under the session list it stays pinned below it). -->
{#snippet settingsMenu(collapsed: boolean)}
<div class="px-2 pb-1">
<SettingsMenu
@@ -1263,18 +1254,26 @@ outside this layout, and their shortcut must reopen the URL that is their creden
onpointerdown={startSidebarResize}
></div>
{/if}
<!-- Top row: the workspace ⇄ sessions switch, level with the page header's own
row so the two read as one band. The workspace picker itself lives in that
header, which is why nothing names the workspace here. -->
<!-- Top row: Home, level with the page header's own row so the two read as one band.
It sits above the switch because both lists start from it: Home is one page for
workspace and sessions alike. The workspace picker itself lives in that header,
which is why nothing names the workspace here. -->
<div class="flex-shrink-0 px-2 h-12 flex flex-col justify-center">
<MenuLink
class="!text-xs"
label="Home"
href="/"
icon={Home}
isCollapsed={collapsed}
aiId="sidebar-menu-link-home"
aiDescription="Button to navigate to home which contains all the user's scripts, flows and apps"
/>
</div>
{#if switchRowShown}
<div
class="flex-shrink-0 px-2 gap-1 flex {collapsed
? 'flex-col items-center py-2'
: 'h-12 items-center'}"
>
<div class="flex-shrink-0 px-2 pb-1 flex {collapsed ? 'flex-col items-center' : ''}">
<div class="min-w-0 flex-1">
<SessionModeSwitch
mode={sessionMode ? 'session' : 'nav'}
list={sidebarList}
isCollapsed={collapsed}
onToggle={panel ? () => (preserveMenuOnNextNav = true) : undefined}
/>
@@ -1282,23 +1281,21 @@ outside this layout, and their shortcut must reopen the URL that is their creden
</div>
{/if}
{#if sessionMode}
<!-- Session mode: the session list owns the column. Workspace nav moves
into the preview side panel (the iframe renders its own nav). -->
{#if sidebarListsSessions}
<!-- The session list owns the column. A session's page shows workspace pages in
its preview side panel (the iframe renders its own nav). -->
<div class="px-2 py-2 flex flex-col gap-1 flex-1 min-h-0 overflow-y-auto">
<SessionPicker isCollapsed={collapsed} embedded collapsible={false} />
</div>
{@render settingsMenu(collapsed)}
{:else}
<!-- Navigation mode: Home → Settings scroll as ONE block with an
overflow fade hint. The three sections (Home/Runs + Favorites +
Search / workspace items / instance settings) are spaced by the
scroll area's gap rather than each scrolling on its own. -->
<!-- The workspace nav: Runs → Settings scroll as ONE block with an
overflow fade hint. The three sections (Runs + Favorites + Search /
workspace items / instance settings) are spaced by the scroll area's
gap rather than each scrolling on its own. -->
<SidebarScrollArea color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
<!-- Section 1: Home/Runs + Favorites + Search. Without the switch row above,
Home is the top row and pt-2 centers its h-8 in the page header's h-12
beside the docked rail. -->
<div class="px-2 flex flex-col gap-1 {switchRowShown ? 'pt-1' : 'pt-2'}">
<!-- Section 1: Runs + Favorites + Search. -->
<div class="px-2 flex flex-col gap-1 pt-1">
{@render quickLinks(collapsed)}
<Menubar class="flex flex-col gap-1">
{#snippet children({ createMenu })}
@@ -1578,8 +1575,8 @@ outside this layout, and their shortcut must reopen the URL that is their creden
<AiChatLayout
{children}
noPadding={devOnly || menuHidden}
disableAi={globalAiEnabled && sessionsAllowed ? true : sessionMode}
loadAiConfig={!sessionMode}
disableAi={globalAiEnabled && sessionsAllowed ? true : onSessionsPage}
loadAiConfig={!onSessionsPage}
showSessionsBetaBanner={sessionsAllowed}
sidebarWidth={railWidth}
transitionClass={sidebarTransitionClass}
@@ -9,7 +9,7 @@
</script>
<script lang="ts">
import { onDestroy, onMount, tick, untrack } from 'svelte'
import { onDestroy, onMount, untrack } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
import { page } from '$app/state'
import {
@@ -40,10 +40,9 @@
import type PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte'
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
import {
createSession,
findEmptyLandingSession,
getEffectiveWorkspaceId,
isTearingDownOpenSession,
opensOnHome,
selectSession,
sessionInCurrentFamily,
sessionPageHref,
@@ -51,7 +50,12 @@
type SessionPreviewTab
} from '$lib/components/sessions/sessionState.svelte'
import { withWorkspaceParam } from '$lib/components/sessions/sessionMode.svelte'
import { enterSessionMode } from '$lib/components/sessions/sessionSwitch.svelte'
import {
openDraftOnHome,
resumeAiSessions,
returnToWorkspace
} from '$lib/components/sessions/sessionSwitch.svelte'
import { sendUserToast } from '$lib/toast'
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
import {
roleCapabilities,
@@ -65,12 +69,8 @@
listRuntimes
} from '$lib/components/sessions/sessionRuntime.svelte'
import { markSessionSeen } from '$lib/components/sessions/sessionUnread.svelte'
import { markSessionRecovered } from '$lib/components/sessions/sessionRecoveryNotice.svelte'
import {
isGlobalAiEnabled,
clearSessionsBetaOptOut,
sessionsAllowedFor
} from '$lib/components/copilot/chat/global/gate'
import { isGlobalAiEnabled, sessionsAllowedFor } from '$lib/components/copilot/chat/global/gate'
import { activateAiSessions } from '$lib/components/sessions/sidebarList.svelte'
import { setToolCompletionListener } from '$lib/components/copilot/chat/shared'
import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte'
import { previewTargetForSessionTarget } from '$lib/components/sessions/sessionPreviewTabs.svelte'
@@ -116,14 +116,14 @@
const embedded = typeof window !== 'undefined' && window.self !== window.top
// Warm the lazily-loaded editor views (see PreviewTabHost) once the page is
// idle: entering session mode stays instant, and by the time the user opens
// idle: opening a session stays instant, and by the time the user opens
// an editor tab its chunk is usually already cached. Sequential so the
// prefetch trickles instead of fanning out four heavy graphs at once.
$effect(() => {
if (embedded || !globalEnabled) return
// Once the chain has started, cancelling the idle handle no longer helps —
// the disposed check between imports is what stops a user who left session
// mode from pulling the remaining graphs on whatever page they went to.
// the disposed check between imports is what stops a user who left the
// session from pulling the remaining graphs on whatever page they went to.
// (An import already in flight can't be aborted; only the tail is skipped.)
let disposed = false
const prefetch = async () => {
@@ -177,11 +177,10 @@
})
// Family reconcile: a workspace switch can land this page with no session
// selected or with another family's session in the URL (the sidebar picker's
// selected or with another family's session in the URL (the workspace menu's
// link navigation keeps the route), and a chat must not bleed across
// families. Re-enter session mode scoped to the active family: keep the open
// chat when it belongs there, else its most recent active session, else a
// fresh one. A `session` that resolves to nothing is left to the
// families. Both resume as the switch's AI Sessions side does, within the
// active family. A `session` that resolves to nothing is left to the
// recovery effect below.
$effect(() => {
if (embedded || !sessionState.hydrated) return
@@ -194,15 +193,14 @@
$workspaceStore
$userWorkspaces
const current = activeSession
const shouldReenter = current ? !sessionInCurrentFamily(current) : !requestsSession
if (!shouldReenter) return
untrack(() => void enterSessionMode({ replace: true }))
const leaves = current ? !sessionInCurrentFamily(current) : !requestsSession
if (!leaves) return
untrack(() => void resumeAiSessions({ replace: true }))
})
// Held across the swap so the session layout mounts once, after the navigation
// settles: mounting the panes mid-navigation makes Splitpanes miss the collapsed
// pane's `maxSize: 0` and leave it open.
let recovering = $state(false)
// Set once this page is on its way to Home, so no session layout mounts for the
// moment it is still on screen.
let leaving = $state(false)
// Bounds the wait for the workspace list the guard above needs. The list can
// fail to arrive for good, and a spinner that never resolves is a worse
@@ -214,20 +212,24 @@
return () => clearTimeout(handle)
})
// The URL names a session this browser doesn't hold. Land on an empty one,
// never the most recent: an existing conversation would read as a successful
// load. `recovering` also guards re-entry: recovery mutates the session list
// this effect tracks, while the URL that would stop it only updates on `goto`.
// The URL names a session this browser doesn't hold. Say so and go to Home rather
// than open another session in its place, which would read as a successful load.
// The toast names no cause: deleted, another browser, cleared site data and a
// damaged link are indistinguishable from here.
$effect(() => {
if (embedded || !globalEnabled || !sessionsAllowedFor(!$roleCapabilities.code)) return
if (!sessionState.hydrated || recovering) return
if (!sessionState.hydrated || leaving) return
// A deliberate delete removes the open session ahead of its own navigation.
// Claiming that gap would take over the URL and tell the user the session
// they just deleted couldn't be found.
if (isTearingDownOpenSession()) return
if ($usersWorkspaceStore === undefined && !workspaceListOverdue) return
if (!requestsSession || activeSession) return
untrack(() => void recoverToNewSession())
untrack(() => {
leaving = true
sendUserToast("We couldn't find that session")
void goto('/', { replaceState: true })
})
})
// Touch the runtime for the active session so it gets created on first visit
@@ -248,6 +250,13 @@
if (lastArrivedSessionId === session.id) return
lastArrivedSessionId = session.id
untrack(() => {
// Judged once, on arrival: a hand-off's draft is unsent until its first send
// commits, a moment after it has claimed its auto-send.
if (opensOnHome(session)) {
leaving = true
void openDraftOnHome(session.id, { replace: true })
return
}
// Keep currentSessionId in sync with the URL so consumers react to
// deep links the same way they react to picker clicks.
selectSession(session.id)
@@ -298,25 +307,6 @@
untrack(() => markSessionSeen(id, count))
})
async function recoverToNewSession() {
recovering = true
try {
// Prefer an existing empty session over stacking another blank onto the
// sidebar: createSession reuses only its own in-memory drafts, so one
// persisted by any other touch (a workspace pick, a preview tab) would
// be passed over.
const target = findEmptyLandingSession() ?? createSession()
selectSession(target.id)
markSessionRecovered(target.id)
await goto(sessionPageHref(target.id), {
replaceState: true
})
await tick()
} finally {
recovering = false
}
}
// Preview panel: a tiny tabbed browser over Windmill. Every tab stays mounted
// (stacked, visibility-toggled, like the warm chat sessions) so switching
// preserves each previewed page's scroll/edit state. The tab model lives on
@@ -1042,22 +1032,18 @@
<div class="p-8 flex flex-col items-start gap-3 text-secondary text-sm">
<p class="text-primary font-medium">AI Sessions are deactivated</p>
<p>You switched back to the legacy chat. Activate AI Sessions (beta) to open this page.</p>
<Button unifiedSize="sm" onclick={() => clearSessionsBetaOptOut('/sessions')}>
Activate AI Sessions
</Button>
<Button unifiedSize="sm" onclick={activateAiSessions}>Activate AI Sessions</Button>
</div>
{:else if !sessionState.hydrated}
<!-- Sessions hydrate from IndexedDB after the user resolves; until then an
empty list means "loading", so recovery below must not fire and strand
the user in a new session while their own is still arriving. -->
empty list means "loading", so recovery must not fire and send the user
to Home while their session is still arriving. -->
<div class="flex-1 flex items-center justify-center">
<Loader2 class="animate-spin" />
</div>
{:else if !requestsSession}
<div class="p-8 text-secondary">No session selected — pick one in the sidebar.</div>
{:else if !activeSession || recovering}
<!-- A tick while recovery swaps in an empty session, or the length of a
fork teardown's HTTP round trip while a delete holds recovery off. -->
{:else if !requestsSession || !activeSession || leaving}
<!-- On the way to Home, or the length of a fork teardown's HTTP round trip
while a delete holds recovery off. -->
<div class="flex-1 flex items-center justify-center">
<Loader2 class="animate-spin" />
</div>
@@ -1286,7 +1272,7 @@
>
<p class="text-primary font-medium">AI Sessions are hidden in this workspace</p>
<p>A workspace admin hid AI sessions in the workspace settings.</p>
<Button unifiedSize="sm" onclick={() => goto('/')}>Back to workspace</Button>
<Button unifiedSize="sm" onclick={() => returnToWorkspace()}>Back to workspace</Button>
</div>
{/if}
</div>