From 1ba8d1f294fbd45b816efc969191b6efb92d93f1 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Thu, 22 Oct 2026 05:02:05 -0700 Subject: [PATCH] feat: one home for the workspace and AI sessions Co-Authored-By: Claude Opus 5.5 (1M context) --- frontend/src/lib/assets/app.css | 36 +-- .../lib/components/copilot/chat/AIChat.svelte | 4 - .../copilot/chat/AIChatDisplay.svelte | 69 +---- .../chat/starter/ComposerSuggestions.svelte | 13 +- .../chat/starter/SessionGreeting.svelte | 28 -- .../copilot/chat/starter/greeting.test.ts | 41 --- .../copilot/chat/starter/greeting.ts | 37 --- .../chat/starter/starterPrompts.svelte.ts | 9 +- .../src/lib/components/home/HomeAIChat.svelte | 77 ++--- .../components/home/homeComposerPin.svelte.ts | 21 ++ .../sessions/HomeSessionStarter.svelte | 70 ++--- .../sessions/SessionChangesBar.svelte | 5 +- .../sessions/SessionModeSwitch.svelte | 66 ++--- .../components/sessions/SessionPicker.svelte | 158 +++------- .../sessions/SessionWorkspaceBar.svelte | 60 ---- .../components/sessions/SessionWrapper.svelte | 195 +++--------- .../sessions/SessionsBetaBanner.svelte | 10 +- .../sessions/WorkspaceFamilyPicker.svelte | 3 +- .../sessions/homeSessionsTransition.svelte.ts | 68 +---- .../sessions/homeSessionsTransition.test.ts | 14 - .../sessions/openInSessionContext.ts | 33 +-- .../sessions/sessionRecoveryNotice.svelte.ts | 18 -- .../sessions/sessionState.svelte.ts | 221 +++++++------- .../components/sessions/sessionState.test.ts | 112 ++----- .../sessions/sessionSwitch.svelte.ts | 232 +++++++-------- .../components/sessions/sessionSwitch.test.ts | 277 ++++-------------- .../components/sessions/sidebarList.svelte.ts | 27 ++ .../components/sidebar/workspaceMenuHref.ts | 6 +- .../components/sidebar/workspaceSwitchUrl.ts | 57 ++-- frontend/src/lib/newDraftFlag.test.ts | 16 +- frontend/src/lib/newDraftFlag.ts | 17 +- .../src/routes/(root)/(logged)/+layout.svelte | 121 ++++---- .../(root)/(logged)/sessions/+page.svelte | 106 +++---- 33 files changed, 722 insertions(+), 1505 deletions(-) delete mode 100644 frontend/src/lib/components/copilot/chat/starter/SessionGreeting.svelte delete mode 100644 frontend/src/lib/components/copilot/chat/starter/greeting.test.ts delete mode 100644 frontend/src/lib/components/copilot/chat/starter/greeting.ts create mode 100644 frontend/src/lib/components/home/homeComposerPin.svelte.ts delete mode 100644 frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte delete mode 100644 frontend/src/lib/components/sessions/homeSessionsTransition.test.ts delete mode 100644 frontend/src/lib/components/sessions/sessionRecoveryNotice.svelte.ts create mode 100644 frontend/src/lib/components/sessions/sidebarList.svelte.ts diff --git a/frontend/src/lib/assets/app.css b/frontend/src/lib/assets/app.css index f7f9b53972..e562e9027f 100644 --- a/frontend/src/lib/assets/app.css +++ b/frontend/src/lib/assets/app.css @@ -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; } diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index a9312bc5fb..1cd884535e 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -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} diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 5f31bd4272..e851bba857 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -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 @@
{/if} {#if messages.length === 0} {#if starter} - - {#if centreComposer} -
-
- -
-
- {/if} + {: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}
{/if} {#if footerMessageShown} - -
- {@render actingOn?.()} -
- -
+
+
{:else}
@@ -1402,7 +1374,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
aiChatInput?.setText(prompt)} />
@@ -1426,12 +1397,4 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/if}
- -
diff --git a/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte b/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte index 6d7dc379a4..72cdec05f2 100644 --- a/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte +++ b/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte @@ -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() - +
{#each suggestions.slice(0, 4) as suggestion (suggestion.label)}
+ 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} - (shownForRoot = $currentWorkspaceRootId)} - {placeholder} - onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)} - /> - {/key} + +
(homeSidebarList.val = 'sessions')}> + {#key `${$currentWorkspaceRootId}:${homeDraft.requests}`} + (shownForRoot = $currentWorkspaceRootId)} + {placeholder} + onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)} + /> + {/key} +
{:else} {@render placeholder()} {/if} @@ -237,7 +240,7 @@ displayName: 'Pin session hero to homepage', action: () => { logFeatureUsage('home', 'ai_hero_pin') - setRemoved(false) + setHomeComposerRemoved(false) } } ] diff --git a/frontend/src/lib/components/home/homeComposerPin.svelte.ts b/frontend/src/lib/components/home/homeComposerPin.svelte.ts new file mode 100644 index 0000000000..ff7aaed0d1 --- /dev/null +++ b/frontend/src/lib/components/home/homeComposerPin.svelte.ts @@ -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) +} diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index 9ab68c3742..f4e8043ee7 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -1,32 +1,31 @@ -{#snippet actingOn()} - {#if session} - - {/if} -{/snippet} - - -

- Keeping it opens it in the preview, so the chat starts with it as context. -

-
- - -
-
diff --git a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte deleted file mode 100644 index 41cbb73a81..0000000000 --- a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte +++ /dev/null @@ -1,60 +0,0 @@ - - - -
- - - {#snippet trigger()} - - {/snippet} - -
diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index d26dd76c3b..b1271955d9 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -9,15 +9,12 @@ @@ -18,12 +18,6 @@ Try AI Sessions (beta) · - + diff --git a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte index e6e27b0a13..417bcd2e9c 100644 --- a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte @@ -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, diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts index 74a72ec0ce..2e7b62808c 100644 --- a/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts +++ b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts @@ -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 | 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() diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts deleted file mode 100644 index 4be3f18fce..0000000000 --- a/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts +++ /dev/null @@ -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) - }) -}) diff --git a/frontend/src/lib/components/sessions/openInSessionContext.ts b/frontend/src/lib/components/sessions/openInSessionContext.ts index af1a5113ad..27284802cc 100644 --- a/frontend/src/lib/components/sessions/openInSessionContext.ts +++ b/frontend/src/lib/components/sessions/openInSessionContext.ts @@ -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() - 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(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 -} diff --git a/frontend/src/lib/components/sessions/sessionRecoveryNotice.svelte.ts b/frontend/src/lib/components/sessions/sessionRecoveryNotice.svelte.ts deleted file mode 100644 index 443f972334..0000000000 --- a/frontend/src/lib/components/sessions/sessionRecoveryNotice.svelte.ts +++ /dev/null @@ -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() - -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) -} diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index 4a3abebb4f..652605e27c 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -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 diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index 4c6666a349..6d48f236d0 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -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 diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index 30b7792487..560e31f9d7 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -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 { - 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 { - 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 { + 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 { + 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 { - 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 { + 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 { + // 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 { + 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 { + 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 } diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index 497e3cbad9..7614c540fc 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -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 { - 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 & { 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): { 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() - } - }) -}) diff --git a/frontend/src/lib/components/sessions/sidebarList.svelte.ts b/frontend/src/lib/components/sessions/sidebarList.svelte.ts new file mode 100644 index 0000000000..6f6f99ca45 --- /dev/null +++ b/frontend/src/lib/components/sessions/sidebarList.svelte.ts @@ -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( + '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('/') +} diff --git a/frontend/src/lib/components/sidebar/workspaceMenuHref.ts b/frontend/src/lib/components/sidebar/workspaceMenuHref.ts index 707104955d..3075e7b5f4 100644 --- a/frontend/src/lib/components/sidebar/workspaceMenuHref.ts +++ b/frontend/src/lib/components/sidebar/workspaceMenuHref.ts @@ -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 diff --git a/frontend/src/lib/components/sidebar/workspaceSwitchUrl.ts b/frontend/src/lib/components/sidebar/workspaceSwitchUrl.ts index c8bc6d070c..7a9a0d6fe4 100644 --- a/frontend/src/lib/components/sidebar/workspaceSwitchUrl.ts +++ b/frontend/src/lib/components/sidebar/workspaceSwitchUrl.ts @@ -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 { - 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 { + 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 diff --git a/frontend/src/lib/newDraftFlag.test.ts b/frontend/src/lib/newDraftFlag.test.ts index 4a2141817e..c60fe5bb3e 100644 --- a/frontend/src/lib/newDraftFlag.test.ts +++ b/frontend/src/lib/newDraftFlag.test.ts @@ -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 () => { diff --git a/frontend/src/lib/newDraftFlag.ts b/frontend/src/lib/newDraftFlag.ts index 88e58f030a..d6184ba705 100644 --- a/frontend/src/lib/newDraftFlag.ts +++ b/frontend/src/lib/newDraftFlag.ts @@ -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//draft_?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 diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 6b79582958..6336e83789 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -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 - + {#snippet quickLinks(collapsed: boolean)} - {/snippet} - @@ -1218,9 +1209,9 @@ outside this layout, and their shortcut must reopen the URL that is their creden {/snippet} - + {#snippet settingsMenu(collapsed: boolean)}
{/if} - + +
+ +
{#if switchRowShown} -
+
(preserveMenuOnNextNav = true) : undefined} /> @@ -1282,23 +1281,21 @@ outside this layout, and their shortcut must reopen the URL that is their creden
{/if} - {#if sessionMode} - + {#if sidebarListsSessions} +
{@render settingsMenu(collapsed)} {:else} - + - -
+ +
{@render quickLinks(collapsed)} {#snippet children({ createMenu })} @@ -1578,8 +1575,8 @@ outside this layout, and their shortcut must reopen the URL that is their creden