feat: make the sidebar switch a button row that only swaps the list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-28 09:23:49 -07:00
co-authored by Claude Opus 5.5
parent c3ba8caaf8
commit b74fc9e187
12 changed files with 259 additions and 342 deletions
@@ -1,65 +1,58 @@
<script lang="ts">
import { Building, MessagesSquare } from 'lucide-svelte'
import { ChevronLeft, ChevronRight, 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 { resumeAiSessions, returnToWorkspace, swapHomeList } from './sessionSwitch.svelte'
import MenuButton from '$lib/components/sidebar/MenuButton.svelte'
import SessionPicker from './SessionPicker.svelte'
import { swapSidebarList } from './sessionSwitch.svelte'
import type { SidebarList } from './sidebarList.svelte'
let {
list,
isCollapsed = false,
// 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
}: { list: SidebarList; isCollapsed?: boolean; onToggle?: () => void } = $props()
let { list, isCollapsed = false }: { list: SidebarList; isCollapsed?: boolean } = $props()
// 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)
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
// Hovering the row opens the session menu; a click shows the session list instead. Taken
// in the capture phase, ahead of the menu's own trigger, which would pin the menu open.
// The menu opens and closes on hover by calling click() on that trigger: those untrusted
// clicks are its own and pass through.
function showSessions(e: MouseEvent) {
if (!e.isTrusted) return
e.preventDefault()
e.stopPropagation()
swapSidebarList('sessions', page.url.pathname === '/')
}
</script>
<!-- Each ToggleButton renders inside a Tooltip wrapper, which is the actual flex
child of the group's track — so the buttons fill the rail width only if those
wrappers grow. `[&>*]:flex-1` makes every direct child split the track evenly. -->
<ToggleButtonGroup
bind:selected
{onSelected}
tabListClass={isCollapsed ? 'flex-col w-full [&>*]:w-full' : 'w-full [&>*]:flex-1'}
>
{#snippet children({ item })}
<ToggleButton
{item}
value="workspace"
icon={isCollapsed ? Building : undefined}
label="Workspace"
iconOnly={isCollapsed}
tooltip={isCollapsed ? 'Workspace' : undefined}
size="sm"
class="w-full justify-center whitespace-nowrap"
/>
<ToggleButton
{item}
value="sessions"
icon={isCollapsed ? MessagesSquare : undefined}
label="AI Sessions"
iconOnly={isCollapsed}
tooltip={isCollapsed ? 'AI Sessions (beta)' : undefined}
size="sm"
class="w-full justify-center whitespace-nowrap"
/>
{/snippet}
</ToggleButtonGroup>
{#if list === 'workspace'}
<div onclickcapture={showSessions} role="none">
<SessionPicker {isCollapsed}>
{#snippet hoverTrigger({ trigger, unread })}
<div class="relative">
<MenuButton
{trigger}
{isCollapsed}
icon={MessagesSquare}
label="AI Sessions"
class="!text-xs"
trailingIcon={ChevronRight}
aiId="sidebar-menu-ai-sessions"
aiDescription="Button to show the AI sessions list in the sidebar"
/>
{#if unread > 0}
<span
class="absolute top-1 right-1 pointer-events-none inline-block w-2 h-2 rounded-full bg-surface-accent-primary"
aria-label="{unread} unread message{unread === 1 ? '' : 's'} across all sessions"
></span>
{/if}
</div>
{/snippet}
</SessionPicker>
</div>
{:else}
<MenuButton
on:click={() => swapSidebarList('workspace', page.url.pathname === '/')}
{isCollapsed}
icon={ChevronLeft}
label="Workspace"
class="!text-xs"
aiId="sidebar-menu-workspace"
aiDescription="Button to show the workspace navigation in the sidebar"
/>
{/if}
@@ -20,6 +20,7 @@
Trash2
} from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import type { Snippet } from 'svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import { goto } from '$lib/navigation'
import { leaveForHome, openDraftOnHome, openNewSession } from './sessionSwitch.svelte'
@@ -141,6 +142,13 @@
// Drop the section's own outer padding/border so it sits flush inside a
// parent container (e.g. gathered with Favorites/Search in the sidebar).
embedded?: boolean
// Render only the collapsed rail's session menu, opened by hovering this trigger
// (rendered with melt's `trigger` and the unread total). The trigger's own click is
// the host's: it never reaches the menu.
hoverTrigger?: Snippet<[{ trigger: any; unread: number }]>
// Shares the options row, left of its menu. With it the picker fills its parent and
// scrolls the list alone, so the row stays in place.
leading?: Snippet
}
let {
@@ -150,7 +158,9 @@
browsedWorkspaceId = undefined,
onBrowseWorkspace = undefined,
onSelectSession = undefined,
embedded = false
embedded = false,
hoverTrigger = undefined,
leading = undefined
}: Props = $props()
const sectionCollapsed = useLocalStorageValue(
@@ -424,12 +434,6 @@
}
}
// 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() {
await openNewSession()
}
// 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) {
@@ -667,46 +671,36 @@
unavailable (no provider configured or disabled in the user's settings)
the section still shows — the per-session chat input is disabled with an
explanatory message, mirroring the sidebar AI chat. -->
{:else if isCollapsed}
<div class={embedded ? '' : 'px-2 pt-3 pb-2 border-b border-light'}>
<MenuButton
stopPropagationOnClick={true}
on:click={createAndOpen}
{isCollapsed}
icon={Plus}
label="New session"
class="!text-xs"
/>
{:else if isCollapsed || hoverTrigger}
<div class={embedded || hoverTrigger ? '' : 'px-2 pt-3 pb-2 border-b border-light'}>
<Menubar>
{#snippet children({ createMenu })}
<Menu {createMenu} usePointerDownOutside submenuSafe>
<Menu {createMenu} usePointerDownOutside submenuSafe openOnHover={!!hoverTrigger}>
{#snippet triggr({ trigger })}
<div class="relative">
<MenuButton
class="!text-xs"
icon={MessageSquare}
label="AI sessions"
{isCollapsed}
{trigger}
/>
{#if totalUnread > 0}
<span
class="absolute top-1 right-1 pointer-events-none inline-block w-2 h-2 rounded-full bg-surface-accent-primary"
aria-label="{totalUnread} unread message{totalUnread === 1
? ''
: 's'} across all sessions"
></span>
{/if}
</div>
{#if hoverTrigger}
{@render hoverTrigger({ trigger, unread: totalUnread })}
{:else}
<div class="relative">
<MenuButton
class="!text-xs"
icon={MessageSquare}
label="AI sessions"
{isCollapsed}
{trigger}
/>
{#if totalUnread > 0}
<span
class="absolute top-1 right-1 pointer-events-none inline-block w-2 h-2 rounded-full bg-surface-accent-primary"
aria-label="{totalUnread} unread message{totalUnread === 1
? ''
: 's'} across all sessions"
></span>
{/if}
</div>
{/if}
{/snippet}
{#snippet children({ item, builders })}
<div class="divide-y min-w-48" role="none">
<div class="py-1" role="none">
<MenuItem class={menuItemBase} onClick={createAndOpen} {item}>
<Plus size={14} />
New session
</MenuItem>
</div>
<div class="py-1" role="none">
<SessionFilterMenu
{builders}
@@ -780,10 +774,10 @@
<div
class="flex flex-col gap-1 {embedded ? '' : 'px-2 pt-3 pb-2'} {!embedded && collapsible
? 'border-b border-light'
: ''}"
: ''} {leading ? 'flex-1 min-h-0' : ''}"
>
<!-- Selection mode reuses the New session row (same h-8 slot, same px-2) so
the list below it never moves. -->
<!-- Selection mode reuses the options row (same h-8 slot) so the list below it
never moves. -->
{#if selectionMode}
<div class="flex flex-row items-center gap-1.5 h-8 px-2">
<Checkbox
@@ -826,17 +820,10 @@
{GROUP_BY_OPTIONS.find((o) => o.value === groupBy.val)?.hint ?? ''}
</span>
{/snippet}
<div class="flex flex-row items-center gap-0.5 pr-0.5">
<div class="flex-1 min-w-0">
<MenuButton
stopPropagationOnClick={true}
on:click={createAndOpen}
isCollapsed={false}
icon={Plus}
label="New session"
class="!text-xs"
/>
</div>
<div class="flex flex-row items-center gap-0.5 h-8 pr-0.5 {leading ? '' : 'justify-end'}">
{#if leading}
<div class="flex-1 min-w-0">{@render leading()}</div>
{/if}
<DropdownV2
fixedHeight={false}
placement="bottom-end"
@@ -928,7 +915,8 @@
selectionMode ? 'select-none' : '',
// In the rail the picker is the whole list and the rail scrolls;
// only cap height when it's one section among others (normal sidebar).
collapsible ? 'max-h-[40vh]' : ''
collapsible ? 'max-h-[40vh]' : '',
leading ? 'flex-1 min-h-0' : ''
)}
onkeydown={handleListKeydown}
role="listbox"
@@ -52,7 +52,7 @@ export function homeSessionsTransition(navigation: OnNavigate): Promise<void> |
})
}
/** For the Workspace ⇄ AI Sessions switch on Home, which stays on the page: runs `swap` as a
/** For the Workspace ⇄ AI Sessions switch, which stays on the page: runs `swap` as a
* view transition in which the sidebar's list comes in from the side of the button pressed.
* The name and timing live in app.css, keyed on `data-home-side-transition`: set only for the
* switch, so a move to a session page does not pick the name up.
@@ -21,11 +21,8 @@ import {
type SessionTarget
} from './sessionState.svelte'
import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte'
import { homeSidebarList, type SidebarList } from './sidebarList.svelte'
import {
fixupUrlAfterWorkspaceSwitch,
hrefAfterWorkspaceSwitch
} from '../sidebar/workspaceSwitchUrl'
import { chosenSidebarList, type SidebarList } from './sidebarList.svelte'
import { fixupUrlAfterWorkspaceSwitch } from '../sidebar/workspaceSwitchUrl'
import { pinHomeComposer } from '../home/homeComposerPin.svelte'
import { homeComposerContext } from './homeComposerContext.svelte'
import { swapHomeSide } from './homeSessionsTransition.svelte'
@@ -38,44 +35,26 @@ import { presetScopeFor } from '../copilot/chat/workingScope'
// `seedDomElement` rides only with `autoSend`: it is the chip of the prompt being sent.
type SeedOpts = { seedPrompt?: string; autoSend?: boolean; seedDomElement?: AppDomSelectorElement }
// 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 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.
// The session last opened, on its page or in Home's composer. Plain module state: a
// reload forgets it, and the family's most recently used session stands in.
let lastSessionId: string | undefined
/** 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 }
}
/** Where a navigation landed, for the switch to come back to. Landing anywhere but Home
* also sets the list Home will show. */
/** Where a navigation landed: a session's page records the session, for the sessions
* page to resume when it is opened without one. */
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 switch on Home, which belongs to both lists: it swaps the list and stays. Home is the
* same page beside either; the switch only opens its composer, for AI Sessions, or folds it.
* Both after the click has played out, or the switch button it landed on takes focus back. */
export function swapHomeList(list: SidebarList, homeHref: string): void {
const swapped = swapHomeSide(list, () => (homeSidebarList.val = list))
if (list === 'workspace') {
rememberWorkspacePage(homeHref)
void swapped.then(() => homeComposerContext.fold())
} else void swapped.then(() => homeComposerContext.focus())
/** The Workspace ⇄ AI Sessions switch: swaps the sidebar's list and leaves the page where it
* is. On Home it also opens the composer, for AI Sessions, or folds it, after the click has
* played out, or the switch button it landed on takes focus back. */
export function swapSidebarList(list: SidebarList, onHome: boolean): void {
const swapped = swapHomeSide(list, () => (chosenSidebarList.val = list))
if (!onHome) return
if (list === 'workspace') void swapped.then(() => homeComposerContext.fold())
else void swapped.then(() => homeComposerContext.focus())
}
// The session last opened, else the family's most recently used one. Scoped to the
@@ -89,9 +68,10 @@ function resumableSession(): Session | undefined {
.sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0]
}
/** 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. */
/** The sessions page opened on no session of this family: 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)) {
@@ -102,23 +82,10 @@ export async function resumeAiSessions(opts?: { replace?: boolean }): Promise<vo
await goto(sessionPageHref(session.id), { replaceState: opts?.replace ?? false })
}
/** 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)
}
// 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.
// page of its own. 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()
@@ -4,9 +4,9 @@ import {
noteArrival,
openSourceInSession,
resumeAiSessions,
returnToWorkspace,
startSessionWithPrompt
} from './sessionSwitch.svelte'
import { chosenSidebarList } from './sidebarList.svelte'
import {
getSessionAutoSendDomElement,
homeDraft,
@@ -52,7 +52,7 @@ function withTwoFamilies(activeWorkspace: string): () => void {
}
}
describe('the sidebar switch comes back where each side was left', () => {
describe('the sessions page resumes the last session opened', () => {
beforeEach(() => {
vi.mocked(goto).mockClear()
})
@@ -87,7 +87,7 @@ describe('the sidebar switch comes back where each side was left', () => {
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.
// Not on Home already, so the resume navigates there.
vi.stubGlobal('window', { location: { pathname: '/runs' } })
try {
noteArrival(new URL('http://localhost/sessions?session=sw-draft'))
@@ -101,25 +101,24 @@ describe('the sidebar switch comes back where each side was left', () => {
}
})
it('returns to the workspace page left, moved by the picker’s rule after a switch', async () => {
// The sidebar's list is the switch's alone: neither a navigation nor opening a
// session in Home's composer may change it.
it('leaves the sidebar list to the switch', async () => {
const restore = withTwoFamilies('rootA')
vi.stubGlobal('window', { location: { pathname: '/runs' } })
const prev = chosenSidebarList.val
try {
noteArrival(new URL('http://localhost/runs?workspace=rootA'))
// Home with the session list beside it is not a workspace page to come back to.
chosenSidebarList.val = 'workspace'
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('/')
await resumeAiSessions()
expect(chosenSidebarList.val).toBe('workspace')
chosenSidebarList.val = 'sessions'
noteArrival(new URL('http://localhost/runs'))
expect(chosenSidebarList.val).toBe('sessions')
} finally {
chosenSidebarList.val = prev
vi.unstubAllGlobals()
homeDraft.id = undefined
restore()
}
})
@@ -28,24 +28,17 @@ export function sessionsSwitchShown(): boolean {
)
}
/** 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 the switch changes it. Per browser, so a reload of Home keeps it too. */
export const homeSidebarList = useLocalStorageValue<SidebarList>(
/** The list the sidebar shows, on every page. Only the Workspace ⇄ AI Sessions switch
* changes it: navigating never does, so a session's page can sit beside the workspace nav
* and a workspace page beside the session list. Per browser, so a reload keeps it. */
export const chosenSidebarList = useLocalStorageValue<SidebarList>(
'windmill_sidebar_list',
'workspace',
'string'
)
/** The list the sidebar shows beside `pathname`, where it offers sessions. */
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'
chosenSidebarList.val = 'sessions'
clearSessionsBetaOptOut('/')
}
@@ -43,6 +43,8 @@
buttonClass?: string | undefined
// Show a trailing chevron to signal the button opens a dropdown.
showChevron?: boolean
// An icon at the row's end, hidden with the label when collapsed.
trailingIcon?: any | undefined
// Render the label with stronger weight/size (e.g. the workspace name).
emphasizeLabel?: boolean
// Drop the native `title` attributes — for callers that wrap the button
@@ -78,6 +80,7 @@
class: classNames = undefined,
buttonClass = undefined,
showChevron = false,
trailingIcon = undefined,
emphasizeLabel = false,
disableTitle = false,
ariaLabel = undefined,
@@ -213,6 +216,14 @@
/>
{/if}
{#if trailingIcon && !isCollapsed}
{@const TrailingIcon = trailingIcon}
<TrailingIcon
size={14}
class="flex-shrink-0 text-tertiary transition-colors group-hover:text-secondary"
/>
{/if}
{#if isCollapsed && notificationsCount > 0}
<div class="absolute top-1 right-1 flex h-fit w-fit">
<SideBarNotification notificationCount={notificationsCount} small={true} />
@@ -1,13 +1,11 @@
import { page } from '$app/state'
import { goto } from '$lib/navigation'
// 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.
// Post-workspace-switch URL fixup shared by the sidebar workspace pickers.
// 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 the switch restores the page, silently
// switching the workspace back.
// they get re-applied on reload, 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
@@ -27,13 +25,21 @@ const EDIT_PAGES = [
'/apps_raw/get/'
]
/** 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 {
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)
let changed = false
for (const key of WORKSPACE_PARAMS) {
if (url.searchParams.get(key) === id) continue
@@ -46,33 +52,7 @@ function moveWorkspaceParams(url: URL, id: string): boolean {
url.searchParams.delete(key)
changed = true
}
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
if (!changed) 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
+2 -9
View File
@@ -17,18 +17,14 @@ vi.mock('./localDraftHints.svelte', () => ({
setLocalDraftHint: vi.fn(),
getLocalDraftHint: () => hints.value
}))
// `stripNewDraftFlag` rewrites the URL through SvelteKit's `replaceState` and
// 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())
// `stripNewDraftFlag` rewrites the URL through SvelteKit's `replaceState`. Mock it
// so the strip is observable via `window.location.href` (mirroring jsdom).
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', () => ({ rememberWorkspacePage }))
import { UserDraftDbSyncer } from './userDraftDbSyncer.svelte'
import { stripNewDraftFlagOnSave, shouldSeedNewDraft } from './newDraftFlag'
@@ -120,9 +116,6 @@ describe('stripNewDraftFlagOnSave', () => {
expect(window.location.href).not.toContain('new_draft')
// Sibling seeding params are preserved.
expect(window.location.href).toContain('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 () => {
+2 -7
View File
@@ -1,6 +1,5 @@
import { page } from '$app/state'
import { replaceState } from '$app/navigation'
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,17 +10,13 @@ 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 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. */
* bookkeeping and `page.state`. */
export function stripNewDraftFlag(): void {
if (typeof window === 'undefined') return
const url = new URL(window.location.href)
if (url.searchParams.get('new_draft') !== 'true') return
url.searchParams.delete('new_draft')
replaceState(url, page.state)
rememberWorkspacePage(url.pathname + url.search)
}
/**
@@ -31,7 +26,7 @@ export function stripNewDraftFlag(): void {
* `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: a return to the editor's URL
* (Back, the sidebar switch's Workspace side, a link kept from before) still
* (Back, 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.
@@ -120,7 +120,10 @@
parsePreviewItemRoute,
barePath
} from '$lib/components/sessions/previewPaths'
import { sessionsSwitchShown, sidebarListFor } from '$lib/components/sessions/sidebarList.svelte'
import {
chosenSidebarList,
sessionsSwitchShown
} 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'
@@ -154,10 +157,6 @@
})
)
let menuOpen = $state(false)
// 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 —
// the manual toggle and a drag past the collapse threshold. The contextual
@@ -324,10 +323,8 @@
// A workspace that hid the assistant (`ai_config.copilot_disabled`) loses both entry
// points: the Workspace ⇄ AI Sessions switch and the legacy Ask-AI button.
const switchRowShown = $derived(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))
// Where the switch is hidden, so is the session list.
const sidebarList = $derived(chosenSidebarList.val)
const sidebarListsSessions = $derived(switchRowShown && sidebarList === 'sessions')
const askAiShown = $derived(
(!globalAiEnabled || !sessionsAllowed) && !$copilotInfo.workspaceDisabled
@@ -448,11 +445,7 @@
onNavigate(homeSessionsTransition)
beforeNavigate((navigation) => {
if (preserveMenuOnNextNav) {
preserveMenuOnNextNav = false
} else {
menuOpen = false
}
menuOpen = false
// Inside a sessions-preview iframe, hand an editor-route navigation up to the
// parent so it mounts the in-process editor (sharing the session runtime)
@@ -789,9 +782,7 @@
$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.
// Not inside a preview iframe: it opens no session page of its own.
afterNavigate((n) => {
if (!embedded && n.to) noteArrival(n.to.url)
})
@@ -1262,87 +1253,98 @@ outside this layout, and their shortcut must reopen the URL that is their creden
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 pb-1 flex {collapsed ? 'flex-col items-center' : ''}">
<div class="min-w-0 flex-1">
<SessionModeSwitch
list={sidebarList}
isCollapsed={collapsed}
onToggle={panel ? () => (preserveMenuOnNextNav = true) : undefined}
/>
<!-- One box for the switch row and either list: the switch's view transition slides
it sideways, and a box that changed size between the two would also move it
vertically. Expanded, the session list carries the way back in its own row. -->
<div class="wm-vt-sidebar-list flex flex-col flex-1 min-h-0">
{#if switchRowShown && !(sidebarListsSessions && !collapsed)}
<div class="flex-shrink-0 px-2 pb-1 flex {collapsed ? 'flex-col items-center' : ''}">
<div class="min-w-0 flex-1">
<SessionModeSwitch list={sidebarList} isCollapsed={collapsed} />
</div>
</div>
</div>
{/if}
{/if}
{#if sidebarListsSessions}
<!-- The session list owns the column. A session's page shows workspace pages in
{#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="wm-vt-sidebar-list 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}
<!-- The workspace nav: Runs → Settings scroll as ONE block with an
{#if collapsed}
<div class="px-2 py-2 flex flex-col gap-1 flex-1 min-h-0 overflow-y-auto">
<SessionPicker isCollapsed embedded collapsible={false} />
</div>
{:else}
<div class="px-2 pb-2 flex flex-col flex-1 min-h-0">
<SessionPicker embedded collapsible={false}>
{#snippet leading()}
<SessionModeSwitch list="sessions" />
{/snippet}
</SessionPicker>
</div>
{/if}
{@render settingsMenu(collapsed)}
{:else}
<!-- 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 class="wm-vt-sidebar-list" color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
<!-- 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 })}
<FavoriteMenu
{createMenu}
favoriteLinks={favoriteManager.current}
isCollapsed={collapsed}
/>
{/snippet}
</Menubar>
<MenuButton
stopPropagationOnClick={true}
on:click={() => openSearchModal()}
isCollapsed={collapsed}
icon={Search}
label="Search"
class="!text-xs"
shortcut={`${getModifierKey()}k`}
/>
{#if askAiShown}
<!-- Legacy Ask-AI pane, shown only when the user opted out of the
AI Sessions beta (otherwise SessionModeSwitch replaces it). -->
<SidebarScrollArea color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
<!-- 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 })}
<FavoriteMenu
{createMenu}
favoriteLinks={favoriteManager.current}
isCollapsed={collapsed}
/>
{/snippet}
</Menubar>
<MenuButton
stopPropagationOnClick={true}
on:click={() => aiChatManager.toggleOpen()}
on:click={() => openSearchModal()}
isCollapsed={collapsed}
icon={WandSparkles}
iconProps={{ forceDarkMode: true }}
label="Ask AI"
icon={Search}
label="Search"
class="!text-xs"
iconClasses="!text-ai"
shortcut={`${getModifierKey()}L`}
shortcut={`${getModifierKey()}k`}
/>
{/if}
</div>
{#if askAiShown}
<!-- Legacy Ask-AI pane, shown only when the user opted out of the
AI Sessions beta (otherwise SessionModeSwitch replaces it). -->
<MenuButton
stopPropagationOnClick={true}
on:click={() => aiChatManager.toggleOpen()}
isCollapsed={collapsed}
icon={WandSparkles}
iconProps={{ forceDarkMode: true }}
label="Ask AI"
class="!text-xs"
iconClasses="!text-ai"
shortcut={`${getModifierKey()}L`}
/>
{/if}
</div>
<!-- Section 2: workspace items -->
<SidebarContent
isCollapsed={collapsed}
showSecondary={false}
excludeMainLabels={['Home', 'Runs']}
numUnacknowledgedCriticalAlerts={isCriticalAlertsUiMuted
? 0
: numUnacknowledgedCriticalAlerts}
/>
<!-- Section 2: workspace items -->
<SidebarContent
isCollapsed={collapsed}
showSecondary={false}
excludeMainLabels={['Home', 'Runs']}
numUnacknowledgedCriticalAlerts={isCriticalAlertsUiMuted
? 0
: numUnacknowledgedCriticalAlerts}
/>
<!-- Section 3: instance settings — mt-auto drops it to the bottom
<!-- Section 3: instance settings — mt-auto drops it to the bottom
when the column has spare room, and collapses back to the normal
inter-section gap once the content overflows and scrolls. -->
<div class="mt-auto">
{@render settingsMenu(collapsed)}
</div>
</SidebarScrollArea>
{/if}
<div class="mt-auto">
{@render settingsMenu(collapsed)}
</div>
</SidebarScrollArea>
{/if}
</div>
<div class="flex-shrink-0">
{@render accountSetupBanner(collapsed)}
@@ -50,11 +50,7 @@
type SessionPreviewTab
} from '$lib/components/sessions/sessionState.svelte'
import { withWorkspaceParam } from '$lib/components/sessions/sessionMode.svelte'
import {
openDraftOnHome,
resumeAiSessions,
returnToWorkspace
} from '$lib/components/sessions/sessionSwitch.svelte'
import { openDraftOnHome, resumeAiSessions } from '$lib/components/sessions/sessionSwitch.svelte'
import { sendUserToast } from '$lib/toast'
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
import {
@@ -179,8 +175,8 @@
// Family reconcile: a workspace switch can land this page with no session
// 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. Both resume as the switch's AI Sessions side does, within the
// active family. A `session` that resolves to nothing is left to the
// families. Both resume the last session opened, within the active family.
// A `session` that resolves to nothing is left to the
// recovery effect below.
$effect(() => {
if (embedded || !sessionState.hydrated) return
@@ -1238,7 +1234,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={() => returnToWorkspace()}>Back to workspace</Button>
<Button unifiedSize="sm" onclick={() => goto('/')}>Back to workspace</Button>
</div>
{/if}
</div>