mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-21 16:06:54 +00:00
feat: one home and ai sessions in the sidebar (#12126)
* feat: one home for the workspace and AI sessions Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: home's ai side opens its composer, lists sessions, previews items Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep a hand-off that reuses home's draft on its session page Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: address local review findings on home's ai side Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: address local review findings on home's draft routing and links Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: keep home's layout on both sides of the sidebar switch Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: drop home's continue last session row Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: scope ai session writes to the folders it works in Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: show each folder's instructions, skills and mcp servers Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: stop the breadcrumb sliding when switching sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: make the sidebar switch a button row that only swaps the list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: list ai sessions inline in the workspace sidebar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: keep home's composer open while switching workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: data stores in the data menu and a customizable sidebar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: move folders and groups to settings and add a data section to the sidebar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: space the sidebar's sections apart and give its rows a little more height Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: remove the session mode switch the sidebar no longer renders Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: follow same-page chat links, restore new session on the rail and list ai chats once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: follow a chat link whenever the panel shows another conversation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: let the sidebar's session list fill the space above its pinned rows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: drop the group data pages option and keep data as a sidebar section Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep home's composer open only in an empty workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: tell admins without ai credentials they can also hide ai sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: fold home's composer on an outside click while the sidebar is hidden Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: scroll the sidebar as one list and pin the session edit actions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: iterate the open overlays with Array.from so the type check passes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: move working folders and folder instructions to their own pr Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep a sending home draft in the workspace it was sent from Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: build the sidebar section headers on the design-system button Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
384295b6bc
commit
af836f1ca6
@@ -429,6 +429,25 @@ input[type='time']::-webkit-calendar-picker-indicator {
|
||||
outline: 2px solid rgb(var(--color-border-accent, 59 130 246));
|
||||
}
|
||||
|
||||
/* Home's composer, pointed at by New session (AIChatDisplay's flashComposer): its box's outline
|
||||
lights up in the accent color and fades, as a setting does when the settings search lands on
|
||||
it. Scoped to the flash, so the box carries no outline otherwise. */
|
||||
[data-composer-flash] [data-composer-box] {
|
||||
outline: 2px solid transparent;
|
||||
outline-offset: 1px;
|
||||
animation: wm-composer-flash 0.8s ease-in;
|
||||
}
|
||||
@keyframes wm-composer-flash {
|
||||
from {
|
||||
outline-color: rgb(var(--color-border-accent, 59 130 246));
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-composer-flash] [data-composer-box] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.svelte-flow__edges {
|
||||
z-index: -10;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
import Badge from './common/badge/Badge.svelte'
|
||||
import InputError from './InputError.svelte'
|
||||
import Popover from './meltComponents/Popover.svelte'
|
||||
import GroupsPageLink from './GroupsPageLink.svelte'
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import {
|
||||
folderPermissionDiff,
|
||||
@@ -652,6 +653,9 @@
|
||||
<div class="flex flex-col w-72 p-4 gap-4">
|
||||
<span class="text-sm leading-6 font-semibold">Add a member</span>
|
||||
<Label label="User or group">
|
||||
{#snippet action()}
|
||||
<GroupsPageLink />
|
||||
{/snippet}
|
||||
<div class="flex items-center gap-1">
|
||||
<!-- The toggle group is `w-full`; unwrapped it takes half the row. -->
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { ExternalLink } from 'lucide-svelte'
|
||||
|
||||
// A new tab: every group picker sits in a drawer or modal whose unsaved form a navigation would drop.
|
||||
</script>
|
||||
|
||||
<a
|
||||
href="/groups"
|
||||
target="_blank"
|
||||
class="inline-flex items-center gap-1 text-2xs font-normal whitespace-nowrap"
|
||||
>
|
||||
Manage groups <ExternalLink size={12} />
|
||||
</a>
|
||||
@@ -284,35 +284,39 @@ not this component) — so the lead can run the whole line.
|
||||
<ChevronDown size={ICON} class="flex-shrink-0" />
|
||||
</span>
|
||||
{:else}
|
||||
<Menubar>
|
||||
{#snippet children({ createMenu })}
|
||||
<Menu
|
||||
bind:this={workspaceMenu}
|
||||
{createMenu}
|
||||
usePointerDownOutside
|
||||
placement="bottom-start"
|
||||
class="h-auto"
|
||||
contentStyle="margin-left: {-nameWidth}px"
|
||||
>
|
||||
{#snippet triggr({ trigger })}
|
||||
<MeltButton
|
||||
meltElement={trigger}
|
||||
class="flex items-center h-9 px-1.5 rounded text-tertiary hover:bg-surface-hover hover:text-primary transition-colors"
|
||||
title="Switch workspace"
|
||||
>
|
||||
<ChevronDown size={ICON} class="flex-shrink-0" />
|
||||
</MeltButton>
|
||||
{/snippet}
|
||||
{#snippet children({ item: menuItem })}
|
||||
<WorkspacePickerBody
|
||||
item={menuItem}
|
||||
collapseFamilies={actingWorkspaceId != undefined}
|
||||
closeMenu={() => workspaceMenu?.close()}
|
||||
/>
|
||||
{/snippet}
|
||||
</Menu>
|
||||
{/snippet}
|
||||
</Menubar>
|
||||
<!-- `data-works-with-composer`: switching workspace leaves Home's composer open; the menu is
|
||||
portaled away from here, so WorkspacePickerBody carries the marker too. -->
|
||||
<span data-works-with-composer class="contents">
|
||||
<Menubar>
|
||||
{#snippet children({ createMenu })}
|
||||
<Menu
|
||||
bind:this={workspaceMenu}
|
||||
{createMenu}
|
||||
usePointerDownOutside
|
||||
placement="bottom-start"
|
||||
class="h-auto"
|
||||
contentStyle="margin-left: {-nameWidth}px"
|
||||
>
|
||||
{#snippet triggr({ trigger })}
|
||||
<MeltButton
|
||||
meltElement={trigger}
|
||||
class="flex items-center h-9 px-1.5 rounded text-tertiary hover:bg-surface-hover hover:text-primary transition-colors"
|
||||
title="Switch workspace"
|
||||
>
|
||||
<ChevronDown size={ICON} class="flex-shrink-0" />
|
||||
</MeltButton>
|
||||
{/snippet}
|
||||
{#snippet children({ item: menuItem })}
|
||||
<WorkspacePickerBody
|
||||
item={menuItem}
|
||||
collapseFamilies={actingWorkspaceId != undefined}
|
||||
closeMenu={() => workspaceMenu?.close()}
|
||||
/>
|
||||
{/snippet}
|
||||
</Menu>
|
||||
{/snippet}
|
||||
</Menubar>
|
||||
</span>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
starter = undefined,
|
||||
onSent = undefined,
|
||||
inputPreface,
|
||||
actingOn,
|
||||
workModeLock = undefined,
|
||||
initialInstructions = undefined,
|
||||
onDraftChange = undefined,
|
||||
@@ -46,8 +45,6 @@
|
||||
starter?: import('./starter/starterPrompts.svelte').ChatStarter
|
||||
onSent?: () => void
|
||||
inputPreface?: import('svelte').Snippet
|
||||
/** Forwarded to AIChatDisplay: where the session acts, first among the controls. */
|
||||
actingOn?: import('svelte').Snippet
|
||||
workModeLock?: import('./workMode').WorkModeLock
|
||||
// Seed / observe the composer's draft (forwarded to AIChatDisplay).
|
||||
initialInstructions?: string
|
||||
@@ -90,7 +87,7 @@
|
||||
: $aiUserDisabled
|
||||
? 'Windmill AI is disabled in your account settings'
|
||||
: isAdmin
|
||||
? 'Enable Windmill AI in your [workspace settings](/workspace_settings?tab=ai) to use this chat'
|
||||
? 'Enable Windmill AI in your [workspace settings](/workspace_settings?tab=ai) to use this chat, or hide AI sessions there'
|
||||
: 'Ask an admin to enable Windmill AI in this workspace to use this chat'
|
||||
: aiChatManager.mode === AIMode.SCRIPT &&
|
||||
aiChatManager.scriptEditorOptions?.lang &&
|
||||
@@ -127,6 +124,10 @@
|
||||
aiChatDisplay?.focusInput(selection)
|
||||
}
|
||||
|
||||
export function flashComposer() {
|
||||
aiChatDisplay?.flashComposer()
|
||||
}
|
||||
|
||||
export async function attachContext(element: import('./context').ContextElement) {
|
||||
await aiChatDisplay?.attachContext(element)
|
||||
}
|
||||
@@ -222,7 +223,6 @@
|
||||
{starter}
|
||||
{onSent}
|
||||
{inputPreface}
|
||||
{actingOn}
|
||||
{workModeLock}
|
||||
{initialInstructions}
|
||||
{onDraftChange}
|
||||
|
||||
@@ -73,11 +73,10 @@
|
||||
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'
|
||||
import { isComposerOverlay } from './starter/composerCollapse'
|
||||
import { asksForComposer, isComposerOverlay } from './starter/composerCollapse'
|
||||
import { smoothHeight } from './starter/smoothHeight'
|
||||
|
||||
const MAX_YOLO_TOOLTIP_TOOLS = 8
|
||||
@@ -120,7 +119,6 @@
|
||||
starter = undefined,
|
||||
onSent = undefined,
|
||||
inputPreface,
|
||||
actingOn,
|
||||
workModeLock = undefined,
|
||||
footerSettings,
|
||||
initialInstructions = undefined,
|
||||
@@ -155,15 +153,12 @@
|
||||
// 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
|
||||
/** 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
|
||||
/** Holds a session chat in Use, and says why in the picker. */
|
||||
workModeLock?: WorkModeLock
|
||||
/** The settings control at the footer's right edge, where the copilot puts its
|
||||
@@ -592,8 +587,6 @@
|
||||
const heldInUse = $derived(
|
||||
chatHost.workModesAvailable && (!!workModeLock || chatHost.workMode === AIWorkMode.USE)
|
||||
)
|
||||
// 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
|
||||
@@ -602,10 +595,8 @@
|
||||
// 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.
|
||||
// and have not left) keeps it open, and so does a host that has it rest open.
|
||||
// Until the input is bound, the draft it starts with is the one it is seeded with: reading
|
||||
// it as empty collapses a remounted composer that holds text for a frame, and the box then
|
||||
// animates open as if the user had opened it.
|
||||
@@ -617,9 +608,9 @@
|
||||
!initialAttachments?.blobs.length
|
||||
)
|
||||
const composerCollapsed = $derived(
|
||||
homeComposer &&
|
||||
starterLayout &&
|
||||
!disabled &&
|
||||
!(starter?.where === 'home' && starter.fewItems) &&
|
||||
!starter?.restsOpen &&
|
||||
!composerOpened &&
|
||||
(aiChatInput ? aiChatInput.isDraftEmpty() : seededDraftEmpty)
|
||||
)
|
||||
@@ -627,13 +618,24 @@
|
||||
if (aiChatInput?.isDraftEmpty() ?? true) composerOpened = false
|
||||
}
|
||||
function onComposerPointerDown(e: PointerEvent) {
|
||||
if (!homeComposer || !composerOpened || composerEl?.contains(e.target as Node)) return
|
||||
if (!isComposerOverlay(e.target)) closeComposer()
|
||||
if (!starterLayout || !composerOpened || composerEl?.contains(e.target as Node)) return
|
||||
if (!isComposerOverlay(e.target) && !asksForComposer(e.target)) closeComposer()
|
||||
}
|
||||
|
||||
// While the box plays its accent outline (app.css, `data-composer-flash`).
|
||||
let flashing = $state(false)
|
||||
|
||||
/** Points the eye at a composer the user was sent to without it moving: its box's outline
|
||||
* lights up in the accent color and fades. */
|
||||
export function flashComposer() {
|
||||
// Off for a frame first, so a flash asked for while one plays starts over.
|
||||
flashing = false
|
||||
requestAnimationFrame(() => (flashing = true))
|
||||
}
|
||||
|
||||
// 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'}`
|
||||
@@ -693,7 +695,6 @@
|
||||
const showFooterLeftControls = $derived(
|
||||
!footerMessageShown &&
|
||||
(canAttachFiles ||
|
||||
!!actingOn ||
|
||||
attachmentsOffReason !== undefined ||
|
||||
showContextPicker ||
|
||||
showAutonomyModeSelector ||
|
||||
@@ -744,7 +745,7 @@
|
||||
<!-- tabindex="-1": clicks on non-focusable chat content must move focus into
|
||||
the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<div
|
||||
class="flex flex-col h-full relative outline-none {starterLayout ? 'justify-center' : ''}"
|
||||
class="flex flex-col h-full relative outline-none"
|
||||
tabindex="-1"
|
||||
bind:this={panelEl}
|
||||
ondragenter={onPanelDragEnter}
|
||||
@@ -854,16 +855,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
{/if}
|
||||
{#if messages.length === 0}
|
||||
{#if starter}
|
||||
<!-- The greeting rides on top of the centred composer instead of being centred with
|
||||
it: it takes the space above, the spacer after the composer the same below. Home
|
||||
has none: there the composer is one control among the page's. -->
|
||||
{#if centreComposer}
|
||||
<div class="flex-1 min-h-0 flex flex-col justify-end">
|
||||
<div class={columnClass}>
|
||||
<SessionGreeting />
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Home's composer is one control among the page's: nothing above it. -->
|
||||
{:else if emptyHint}
|
||||
{@render emptyHint()}
|
||||
{:else}
|
||||
@@ -988,19 +980,26 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<!-- The focus and key handlers take events bubbling from the field inside, which is the
|
||||
interactive element; the group itself is never focused. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<!-- `data-composer-open`: while the reader is in Home's composer, Home keeps it at the top
|
||||
and quiets its cards. -->
|
||||
<div
|
||||
data-session-composer
|
||||
data-composer-open={starterLayout && composerOpened ? '' : undefined}
|
||||
data-composer-flash={flashing ? '' : undefined}
|
||||
role="group"
|
||||
aria-label="Message composer"
|
||||
bind:this={composerEl}
|
||||
class="relative {columnClass} pb-2"
|
||||
onanimationend={(e) => {
|
||||
if (e.animationName === 'wm-composer-flash') flashing = false
|
||||
}}
|
||||
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()
|
||||
}}
|
||||
@@ -1072,7 +1071,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()}
|
||||
@@ -1272,7 +1271,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
onchange={onFolderInputChange}
|
||||
/>
|
||||
{/if}
|
||||
{@render actingOn?.()}
|
||||
{#if showAutonomyModeSelector}
|
||||
<AutonomyModePicker
|
||||
mode={chatHost.autonomyMode}
|
||||
@@ -1326,13 +1324,8 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
</div>
|
||||
{/if}
|
||||
{#if footerMessageShown}
|
||||
<!-- The workspace picker stays: picking another workspace is how a chat that
|
||||
cannot run here becomes usable again. -->
|
||||
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
|
||||
{@render actingOn?.()}
|
||||
<div class="text-primary text-xs my-2 px-2">
|
||||
<Markdown md={disabledMessage} />
|
||||
</div>
|
||||
<div class="text-primary text-xs my-2 px-2">
|
||||
<Markdown md={disabledMessage} />
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center">
|
||||
@@ -1412,7 +1405,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<div class="pt-2">
|
||||
<ComposerSuggestions
|
||||
suggestions={starter.suggestions}
|
||||
wrap={starter.where === 'session'}
|
||||
onPick={(prompt) => aiChatInput?.setText(prompt)}
|
||||
/>
|
||||
</div>
|
||||
@@ -1436,12 +1428,4 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Equal to the space above while the session is empty, so the composer sits centred.
|
||||
Always mounted and shrunk on the first message rather than removed: flex-grow
|
||||
transitions, so the composer slides down to the bottom instead of jumping. -->
|
||||
<div
|
||||
class="min-h-0 basis-0 transition-[flex-grow] duration-[380ms] ease-[cubic-bezier(0.2,0.8,0.2,1)] motion-reduce:transition-none {centreComposer
|
||||
? 'grow'
|
||||
: 'grow-0'}"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
@@ -813,6 +813,7 @@
|
||||
|
||||
<!-- The box that opens a session grows and shrinks between its one-line and full shapes. -->
|
||||
<div
|
||||
data-composer-box
|
||||
class={twMerge(composerBoxClass(disabled), hero && HERO_BOX_CLASS)}
|
||||
use:smoothHeight={{ enabled: hero, key: oneLine }}
|
||||
>
|
||||
@@ -857,7 +858,7 @@
|
||||
bind:this={textarea}
|
||||
onkeydown={handleKeyDown}
|
||||
bind:value
|
||||
use:autosize={hero && !oneLine ? { maxHeight: 160, minHeight: 56 } : { maxHeight: '40vh' }}
|
||||
use:autosize={hero && !oneLine ? { maxHeight: 160, minHeight: 80 } : { maxHeight: '40vh' }}
|
||||
rows={1}
|
||||
oninput={handleInput}
|
||||
onpaste={handlePaste}
|
||||
|
||||
@@ -23,8 +23,11 @@ export function composerBoxClass(disabled: boolean = false): string {
|
||||
}
|
||||
|
||||
/** Added to a usable box that opens a session (Home, an empty session). Focus shows as the
|
||||
* base box's border colour alone: the brand has no focus ring. */
|
||||
export const HERO_BOX_CLASS = 'rounded-[10px]'
|
||||
* base box's border colour alone: the brand has no focus ring. On Home, an open composer
|
||||
* floats over the lists scrolling under it, so it takes the brand's elevation for moving
|
||||
* elements. */
|
||||
export const HERO_BOX_CLASS =
|
||||
'rounded-[10px] transition-[border-color,box-shadow] group-has-[[data-composer-open]]/home:shadow-md'
|
||||
|
||||
/** Applied to the field inside the box; without it the field draws a second border. */
|
||||
export const COMPOSER_FIELD_RESET =
|
||||
|
||||
@@ -5,22 +5,17 @@
|
||||
|
||||
let {
|
||||
suggestions,
|
||||
onPick,
|
||||
wrap = false
|
||||
onPick
|
||||
}: {
|
||||
suggestions: ComposerSuggestion[]
|
||||
onPick: (prompt: string) => void
|
||||
/** Wrap onto more lines instead of one row that scrolls sideways. */
|
||||
wrap?: boolean
|
||||
} = $props()
|
||||
</script>
|
||||
|
||||
<!-- Unwrapped, one row whatever the width: it scrolls sideways and fades out at its end, so the
|
||||
page under the composer does not move with the window width. -->
|
||||
<!-- One row whatever the width: it scrolls sideways and fades out at its end, so the page under
|
||||
the composer does not move with the window width. -->
|
||||
<div
|
||||
class="flex flex-row items-center gap-1.5 {wrap
|
||||
? 'flex-wrap'
|
||||
: 'overflow-x-auto no-scrollbar [mask-image:linear-gradient(90deg,#000_calc(100%-24px),transparent)]'}"
|
||||
class="flex flex-row items-center gap-1.5 overflow-x-auto no-scrollbar [mask-image:linear-gradient(90deg,#000_calc(100%-24px),transparent)]"
|
||||
>
|
||||
{#each suggestions.slice(0, 4) as suggestion (suggestion.label)}
|
||||
<Button
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { userStore, userWorkspaces, workspaceStore } from '$lib/stores'
|
||||
import { takeFirstVisit, timeOfDayGreeting } from './greeting'
|
||||
|
||||
// `name` is the full name when the account has one; the greeting uses the first word.
|
||||
const userName = $derived($userStore?.name?.trim().split(/\s+/)[0] || $userStore?.username)
|
||||
const workspaceName = $derived(
|
||||
$userWorkspaces.find((w) => w.id === $workspaceStore)?.name ?? $workspaceStore
|
||||
)
|
||||
// Read once the membership for this workspace has loaded: `userStore` still describes the
|
||||
// previous workspace for a moment after a switch.
|
||||
const firstVisit = $derived(
|
||||
!!$workspaceStore &&
|
||||
$userStore?.workspace_id === $workspaceStore &&
|
||||
takeFirstVisit($workspaceStore, $userStore.created_at)
|
||||
)
|
||||
const greeting = timeOfDayGreeting()
|
||||
</script>
|
||||
|
||||
<div class="flex items-center justify-center gap-2 mb-4">
|
||||
<p class="text-center font-regular text-3xl">
|
||||
{#if firstVisit}
|
||||
Welcome to {workspaceName}{userName ? `, ${userName}` : ''}
|
||||
{:else}
|
||||
{greeting}{userName ? `, ${userName}` : ''}
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
@@ -1,11 +1,26 @@
|
||||
// The layers the composer's controls open render in portals under <body>, outside the
|
||||
// composer's own element: DropdownV2 menus, melt popovers, and the settings modals. Not
|
||||
// `[data-menu]`: DropdownV2 puts it on its trigger too, and Home has triggers everywhere.
|
||||
const OVERLAY = '[data-melt-dropdown-menu], [data-melt-popover-content], [role="dialog"]'
|
||||
// `.wm-modal-form-popup` is Modal2's box, which carries no dialog role: without it a press
|
||||
// inside Assistant settings folds the composer, and the modal goes with it.
|
||||
const OVERLAY =
|
||||
'[data-melt-dropdown-menu], [data-melt-popover-content], [role="dialog"], .wm-modal-form-popup'
|
||||
|
||||
/** Whether a pointer-down outside the composer still leaves it open: it landed in a menu or
|
||||
* dialog, or one is open, and the press is closing it rather than leaving the composer. */
|
||||
export function isComposerOverlay(target: EventTarget | null): boolean {
|
||||
if (target instanceof Element && target.closest(OVERLAY)) return true
|
||||
return document.querySelector(OVERLAY) !== null
|
||||
// An inert one is closed but kept mounted: the hidden sidebar's floating card is a dialog.
|
||||
return Array.from(document.querySelectorAll(OVERLAY)).some((el) => !el.closest('[inert]'))
|
||||
}
|
||||
|
||||
/** Whether a pointer-down outside the composer leaves it open: it is on a control that brings
|
||||
* the user to it (`data-asks-for-composer`, New session), where folding it on the way in would
|
||||
* collapse it and open it again under the user's eyes, or on what the user works in alongside
|
||||
* it (`data-works-with-composer`, Home's lists), where a click adds an item to it. */
|
||||
export function asksForComposer(target: EventTarget | null): boolean {
|
||||
return (
|
||||
target instanceof Element &&
|
||||
target.closest('[data-asks-for-composer], [data-works-with-composer]') !== null
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const scoped = vi.hoisted(() => ({ key: 'welcomed::ada@example.com' as string | undefined }))
|
||||
vi.mock('$lib/userScopedStorage', () => ({ scopedKey: () => scoped.key }))
|
||||
|
||||
import { takeFirstVisit } from './greeting'
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000
|
||||
const daysAgo = (n: number) => new Date(Date.now() - n * DAY).toISOString()
|
||||
|
||||
const store = new Map<string, string>()
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: (k: string) => store.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void store.set(k, v)
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
store.clear()
|
||||
scoped.key = 'welcomed::ada@example.com'
|
||||
})
|
||||
|
||||
describe('takeFirstVisit', () => {
|
||||
it('welcomes a new member once per workspace, for the whole page load', () => {
|
||||
expect(takeFirstVisit('acme', daysAgo(2))).toBe(true)
|
||||
// Back on Home or the empty session in the same load: still the welcome.
|
||||
expect(takeFirstVisit('acme', daysAgo(2))).toBe(true)
|
||||
expect(JSON.parse(store.get('welcomed::ada@example.com')!)).toEqual(['acme'])
|
||||
})
|
||||
|
||||
it('greets by time of day for an older member, or a workspace already welcomed', () => {
|
||||
expect(takeFirstVisit('old-team', daysAgo(45))).toBe(false)
|
||||
store.set('welcomed::ada@example.com', JSON.stringify(['seen-before']))
|
||||
expect(takeFirstVisit('seen-before', daysAgo(1))).toBe(false)
|
||||
})
|
||||
|
||||
it('records nothing before the user is known', () => {
|
||||
scoped.key = undefined
|
||||
expect(takeFirstVisit('fresh', daysAgo(1))).toBe(false)
|
||||
expect(store.size).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
import { scopedKey } from '$lib/userScopedStorage'
|
||||
|
||||
const WELCOMED_KEY = 'session-block-welcomed-workspaces'
|
||||
/** A membership older than this is not a first visit, whatever this browser remembers: without
|
||||
* it, everyone already in a workspace would be welcomed to it once on their next visit. */
|
||||
const NEW_MEMBER_MS = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
// Workspaces welcomed during this page load: the welcome holds for the whole visit (Home, the
|
||||
// empty session, back), and only a later load greets by time of day.
|
||||
const welcomedThisLoad = new Set<string>()
|
||||
|
||||
/** Whether this is the user's first visit to `workspace`: a recent member this browser has not
|
||||
* welcomed there yet. Answering yes records the welcome. */
|
||||
export function takeFirstVisit(workspace: string, memberSince: string | undefined): boolean {
|
||||
if (welcomedThisLoad.has(workspace)) return true
|
||||
const key = scopedKey(WELCOMED_KEY)
|
||||
if (!key) return false
|
||||
let welcomed: string[] = []
|
||||
try {
|
||||
welcomed = JSON.parse(localStorage.getItem(key) ?? '[]')
|
||||
} catch {}
|
||||
if (welcomed.includes(workspace)) return false
|
||||
const joined = memberSince ? Date.parse(memberSince) : NaN
|
||||
if (!(Date.now() - joined < NEW_MEMBER_MS)) return false
|
||||
welcomedThisLoad.add(workspace)
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify([...welcomed, workspace]))
|
||||
} catch {}
|
||||
return true
|
||||
}
|
||||
|
||||
export function timeOfDayGreeting(now = new Date()): string {
|
||||
const hour = now.getHours()
|
||||
if (hour >= 5 && hour < 12) return 'Good morning'
|
||||
if (hour >= 12 && hour < 18) return 'Good afternoon'
|
||||
return 'Good evening'
|
||||
}
|
||||
@@ -99,11 +99,11 @@ export class StarterPrompts {
|
||||
return composerSuggestions(signals, builds ? role : { ...role, operator: true })
|
||||
})
|
||||
|
||||
/** Whether the workspace holds fewer than `FEW_ITEMS`, below which Home's composer rests
|
||||
* open as the page's main way in; undefined until known. */
|
||||
get fewItems(): boolean | undefined {
|
||||
/** Whether the workspace holds no item the reader can list, where Home's composer rests
|
||||
* open as the page's only way in; undefined until known. */
|
||||
get empty(): boolean | undefined {
|
||||
const count = this.#currentSignals?.itemCount
|
||||
return count === undefined ? undefined : count < FEW_ITEMS
|
||||
return count === undefined ? undefined : count === 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,9 +272,6 @@ function composerItem(item: RunnableItem, path = item.path): ComposerItem {
|
||||
}
|
||||
}
|
||||
|
||||
/** What turns an empty chat into the block that starts a session. */
|
||||
export type ChatStarter = { suggestions: ComposerSuggestion[] } & (
|
||||
| /** An empty session centres the block in the pane under a greeting. */
|
||||
{ where: 'session' } /** Home shows it alone, collapsed to one line at rest unless `fewItems`. */
|
||||
| { where: 'home'; fewItems: boolean }
|
||||
)
|
||||
/** What turns an empty chat into Home's block that starts a session, collapsed to one line at
|
||||
* rest unless `restsOpen`. */
|
||||
export type ChatStarter = { suggestions: ComposerSuggestion[]; restsOpen: boolean }
|
||||
|
||||
@@ -86,6 +86,7 @@
|
||||
useOperatingWorkspaceHref
|
||||
} from '$lib/components/operatingWorkspace.svelte'
|
||||
import FlowChat from '$lib/components/flows/conversations/FlowChat.svelte'
|
||||
import { page } from '$app/state'
|
||||
import { slide } from 'svelte/transition'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import CiTestResults from '$lib/components/CiTestResults.svelte'
|
||||
@@ -869,6 +870,7 @@
|
||||
flowModules={flow?.value?.modules}
|
||||
wideLayout
|
||||
frame="none"
|
||||
openConversation={page.url.searchParams.get('conversation') ?? undefined}
|
||||
>
|
||||
{#snippet sidebarFooter({ expanded })}
|
||||
{#if workspace && flow}
|
||||
|
||||
@@ -59,6 +59,8 @@
|
||||
onLoadState?: (state: 'loaded' | 'not_found') => void
|
||||
/** The deployed agent's summary, for a host that names the page after it. */
|
||||
onSummary?: (summary: string | undefined) => void
|
||||
/** A chat conversation to show once the chat is up, as a link to it names one. */
|
||||
openConversation?: string
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -69,7 +71,8 @@
|
||||
onNavigate = (url) => goto(url),
|
||||
pendingRun = undefined,
|
||||
onLoadState = undefined,
|
||||
onSummary = undefined
|
||||
onSummary = undefined,
|
||||
openConversation = undefined
|
||||
}: Props = $props()
|
||||
|
||||
// Every workspace-scoped call below and in the drawers this page opens (the summary's save,
|
||||
@@ -388,6 +391,7 @@
|
||||
view
|
||||
onOpenConfig={() => configModal?.open()}
|
||||
onRunStarted={embedded || pendingRun ? runStarted : undefined}
|
||||
{openConversation}
|
||||
>
|
||||
{#snippet chatSidebarFooter({ expanded })}
|
||||
{#if ws}
|
||||
|
||||
@@ -71,6 +71,8 @@
|
||||
view?: boolean
|
||||
/** Opens the agent's configuration, offered beside the model it runs with. */
|
||||
onOpenConfig?: () => void
|
||||
/** A chat conversation to show once the chat is up, as a link to it names one. */
|
||||
openConversation?: string
|
||||
/** Takes a view's run once it has started, instead of opening its run page: for a host that
|
||||
* is not the app's top-level route (a session tab), or a call waiting on that run. */
|
||||
onRunStarted?: (jobId: string, args: Record<string, any>) => void
|
||||
@@ -102,6 +104,7 @@
|
||||
isNew = false,
|
||||
view = false,
|
||||
onOpenConfig = undefined,
|
||||
openConversation = undefined,
|
||||
onRunStarted = undefined,
|
||||
viewForm = undefined,
|
||||
configFooter = undefined,
|
||||
@@ -770,6 +773,7 @@
|
||||
inputSchema={AGENT_CHAT_SCHEMA}
|
||||
flowModules={chatModules}
|
||||
composerSettings={onOpenConfig ? configButton : undefined}
|
||||
{openConversation}
|
||||
sidebarFooter={chatSidebarFooter}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import FlowConversationsSidebar from './FlowConversationsSidebar.svelte'
|
||||
import FlowChatInterface from './FlowChatInterface.svelte'
|
||||
import { getContext, untrack } from 'svelte'
|
||||
import { afterNavigate } from '$app/navigation'
|
||||
import type { FlowEditorContext } from '../types'
|
||||
import { ApiError, type FlowModule } from '$lib/gen'
|
||||
import { FlowChatPool, type FlowChatPoolState } from './flowChatPool'
|
||||
@@ -63,6 +64,8 @@
|
||||
subject?: 'flow' | 'agent'
|
||||
/** The host's own controls, after the model's in the composer's footer. */
|
||||
composerSettings?: import('svelte').Snippet
|
||||
/** A conversation to show once the chat is up, as a link to it names one. */
|
||||
openConversation?: string
|
||||
/** Pinned at the foot of the conversations sidebar. */
|
||||
sidebarFooter?: import('svelte').Snippet<[{ expanded: boolean }]>
|
||||
}
|
||||
@@ -81,6 +84,7 @@
|
||||
conversationKind = 'deployed',
|
||||
subject = 'flow',
|
||||
composerSettings = undefined,
|
||||
openConversation = undefined,
|
||||
sidebarFooter = undefined
|
||||
}: Props = $props()
|
||||
|
||||
@@ -167,6 +171,10 @@
|
||||
}
|
||||
})
|
||||
const unsubscribePool = createdPool.subscribe((s) => (poolState = s))
|
||||
// Untracked: a later change of the prop must not rebuild every chat of the flow; the
|
||||
// navigation below follows it instead.
|
||||
const linked = untrack(() => openConversation)
|
||||
if (linked) createdPool.select(linked)
|
||||
listChat = createdList
|
||||
pool = createdPool
|
||||
return () => {
|
||||
@@ -177,6 +185,16 @@
|
||||
}
|
||||
})
|
||||
|
||||
// A link to another chat of this flow changes only the query, so the page is not remounted
|
||||
// and the pool stays: it is shown here. Compared with what the panel shows, not with the
|
||||
// link last followed: picking a chat in the panel's own sidebar leaves the query as it was,
|
||||
// and the reader can still link back to it.
|
||||
afterNavigate(() => {
|
||||
const linked = openConversation
|
||||
if (!linked || !pool || linked === poolState?.selectedId) return
|
||||
pool.select(linked)
|
||||
})
|
||||
|
||||
// The panel on screen. Every other panel the pool holds stays mounted behind it.
|
||||
const shownKey = $derived(poolState?.shownKey)
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ export function agentChatPath(agentPath: string): string {
|
||||
return `${agentPath}.chat`
|
||||
}
|
||||
|
||||
/** The agent a conversation's path files it under, or undefined for a flow's own chat. */
|
||||
export function agentOfChatPath(chatPath: string): string | undefined {
|
||||
return chatPath.endsWith('.chat') ? chatPath.slice(0, -'.chat'.length) : undefined
|
||||
}
|
||||
|
||||
/** The id of the one step a saved agent's run is made of, as the server names it too: job-read
|
||||
* scoping and the run's agent detection match on it, so it is only ever relabeled for display. */
|
||||
export const AGENT_STEP_ID = '__wm_agent_root'
|
||||
|
||||
@@ -113,6 +113,11 @@
|
||||
|
||||
// kept static so tailwind doesn't purge the badge tones
|
||||
const badgeAdvanced = 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300'
|
||||
// While Home's composer is open (`data-composer-open`) the button looks like the default
|
||||
// variant: that state lives in the DOM, not in a prop. The border is an inset ring so the
|
||||
// button keeps its width.
|
||||
const QUIET_AS_DEFAULT =
|
||||
'group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:hover:bg-surface-hover group-has-[[data-composer-open]]/home:text-primary group-has-[[data-composer-open]]/home:ring-1 group-has-[[data-composer-open]]/home:ring-inset group-has-[[data-composer-open]]/home:ring-border-light'
|
||||
const badgeLegacy = 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'
|
||||
const badgeAlpha = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
|
||||
const badgeRecommended = 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300'
|
||||
@@ -535,6 +540,7 @@
|
||||
aiDescription="Create a new script, flow or app"
|
||||
unifiedSize="md"
|
||||
variant="accent"
|
||||
btnClasses={QUIET_AS_DEFAULT}
|
||||
startIcon={{ icon: Plus }}
|
||||
endIcon={{ icon: ChevronDown }}
|
||||
bind:element={triggerEl}
|
||||
|
||||
@@ -16,10 +16,10 @@
|
||||
import CloseButton from '../common/CloseButton.svelte'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { hubBaseUrlStore, roleCapabilities, workspaceStore } from '$lib/stores'
|
||||
import { sessionState } from '../sessions/sessionState.svelte'
|
||||
import { homeDraft, sessionState } from '../sessions/sessionState.svelte'
|
||||
import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte'
|
||||
import { HOME_SHOW_HUB } from '$lib/consts'
|
||||
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
|
||||
import { homeComposerPin, setHomeComposerRemoved } from './homeComposerPin.svelte'
|
||||
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
|
||||
import { BROWSER } from 'esm-env'
|
||||
import HomeConnectDrawer from './HomeConnectDrawer.svelte'
|
||||
@@ -35,8 +35,6 @@
|
||||
import { useWorkspaceAiHidden } from '../copilot/workspaceAiHidden.svelte'
|
||||
import { homeQuickAccessSettings } from './homeQuickAccessSettings.svelte'
|
||||
|
||||
const COLLAPSED_SETTING = 'home-ai-composer-collapsed'
|
||||
|
||||
/** Bar width from which the two side trips stand in the bar rather than folding into the menu.
|
||||
* Home's trail is ~250px and the rest of its actions ~400, so this leaves room for both
|
||||
* labelled buttons without the trail starting to truncate. Below it they fold back. */
|
||||
@@ -46,14 +44,9 @@
|
||||
|
||||
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
|
||||
|
||||
// Whether this reader wants the composer on the home page at all, so it lives per browser
|
||||
// rather than per workspace or account. It has nothing to do with the composer's one-line
|
||||
// state despite the key's name; renaming the key would reset every reader's choice.
|
||||
let removed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true')
|
||||
function setRemoved(next: boolean) {
|
||||
removed = next
|
||||
storeLocalSetting(COLLAPSED_SETTING, next ? 'true' : undefined)
|
||||
}
|
||||
// Whether this reader wants the composer on the home page at all. Starting a session puts
|
||||
// it back (see pinHomeComposer).
|
||||
const removed = $derived(homeComposerPin.removed)
|
||||
|
||||
// Removing puts the composer away rather than throwing it out, and the way back is one item in
|
||||
// the band's menu — so the ellipsis flashes as it appears, in a corner nobody is watching while
|
||||
@@ -71,7 +64,7 @@
|
||||
function removeComposer() {
|
||||
// The `close` key keeps these events in the series they have always been counted in.
|
||||
logFeatureUsage('home', 'ai_hero_remove', { key: 'close' })
|
||||
setRemoved(true)
|
||||
setHomeComposerRemoved(true)
|
||||
if (reducedMotion.val) return
|
||||
clearTimeout(pulseEndTimer)
|
||||
pulsing = true
|
||||
@@ -85,16 +78,17 @@
|
||||
// are no extra wait.
|
||||
if ($workspaceStore) prefetchComposerSignals($workspaceStore)
|
||||
|
||||
// Whether Home's own workspace hides the assistant, read for that workspace: once the block
|
||||
// shows, the shared copilot config is the draft's, so a draft acting on a workspace that hides
|
||||
// AI would otherwise take the whole block, and the picker that could undo it, off Home.
|
||||
// Whether Home's own workspace hides the assistant, read for that workspace rather than from
|
||||
// the shared copilot config, which still describes the last session's workspace for a moment
|
||||
// after leaving its page.
|
||||
const homeAiHidden = useWorkspaceAiHidden(() => $workspaceStore ?? undefined)
|
||||
|
||||
// The composer hands off to /sessions, which refuses roles that cannot code and users opted out
|
||||
// of the sessions beta — so hide it from them (the prompt would be silently dropped) while the
|
||||
// AI-independent CLI/MCP row below stays.
|
||||
// The composer hands off to /sessions, which refuses roles that cannot code, users opted out
|
||||
// of the sessions beta and a session's own preview frame — so hide it there (the prompt would
|
||||
// be silently dropped) while the AI-independent CLI/MCP row below stays.
|
||||
const inPreviewFrame = BROWSER && window.self !== window.top
|
||||
let showComposer = $derived(
|
||||
prefersSessionHandoff(!$roleCapabilities.code) && !homeAiHidden.hidden
|
||||
prefersSessionHandoff(!$roleCapabilities.code) && !inPreviewFrame && !homeAiHidden.hidden
|
||||
)
|
||||
|
||||
let hero = $derived(showComposer && !removed)
|
||||
@@ -116,9 +110,10 @@
|
||||
</div>
|
||||
<!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on
|
||||
the workspace family, not the workspace: another family needs its own draft, but a
|
||||
fork shares its parent's, and remounting for it only flashes the block. -->
|
||||
fork shares its parent's, and remounting for it only flashes the block. Also keyed
|
||||
on the asks for another draft (New session, a draft picked in the session list). -->
|
||||
{#if HomeSessionStarter && sessionState.hydrated}
|
||||
{#key $currentWorkspaceRootId}
|
||||
{#key `${$currentWorkspaceRootId}:${homeDraft.requests}`}
|
||||
<HomeSessionStarter
|
||||
{placeholder}
|
||||
onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)}
|
||||
@@ -219,7 +214,7 @@
|
||||
displayName: 'Pin session hero to homepage',
|
||||
action: () => {
|
||||
logFeatureUsage('home', 'ai_hero_pin')
|
||||
setRemoved(false)
|
||||
setHomeComposerRemoved(false)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -368,7 +368,7 @@
|
||||
{#snippet card(item: Entry, favorite: boolean)}
|
||||
{@const draft = draftByItem.get(`${item.starKind}/${item.path}`)}
|
||||
<div
|
||||
class="group flex items-center gap-1 rounded-md border border-light bg-surface-tertiary hover:bg-surface-hover transition-colors min-w-0"
|
||||
class="group flex items-center gap-1 rounded-md border border-light bg-surface-tertiary hover:bg-surface-hover transition-colors min-w-0 group-has-[[data-composer-open]]/home:border-transparent group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:hover:bg-surface-hover"
|
||||
>
|
||||
<a
|
||||
href={getFavoriteHref(item.path, item.kind)}
|
||||
@@ -453,7 +453,7 @@
|
||||
landing in front of them would push every card over. -->
|
||||
{#if favoriteManager.loadedFor === workspace && (entries.length > 0 || emptiedBySettings) && !hidden}
|
||||
<!-- 30px under the cards: the gap from the composer down to this section's heading text. -->
|
||||
<section class="flex flex-col gap-2 px-4 sm:px-0 pb-[30px]">
|
||||
<section data-works-with-composer class="flex flex-col gap-2 px-4 sm:px-0 pb-[30px]">
|
||||
<div class="flex items-center gap-1 -my-1">
|
||||
<HomeSectionLabel>
|
||||
{#if favoriteCount > 0}
|
||||
|
||||
@@ -1564,7 +1564,10 @@
|
||||
// button asynchronously after the menu closes. Without overriding it, pressing
|
||||
// an arrow key would re-open / re-highlight the workspace picker instead of
|
||||
// moving the flat list's selection. Run several times to win the focus race.
|
||||
// Never over Home's composer: New session in another workspace switches it too, and asks
|
||||
// for the caret there.
|
||||
const focusSearch = () => {
|
||||
if (document.activeElement?.closest('[data-session-composer]')) return
|
||||
const el = document.getElementById('home-search-input') as HTMLInputElement | null
|
||||
el?.focus()
|
||||
}
|
||||
@@ -1945,10 +1948,19 @@
|
||||
{/if}
|
||||
<!-- The items section, one card: its controls, its filters and its rows. No `overflow-hidden`
|
||||
on it: the page scrolls, and that would stop the controls sticking. -->
|
||||
<div class="flex flex-col bg-surface-tertiary border border-border-light rounded-lg">
|
||||
<!-- While Home's composer is open the card loses its border and background, and so do the
|
||||
Favorites and Recent cards (HomeQuickAccess), the search field loses its background and New
|
||||
looks like a default button (CreateActionsMenu), so the lists sit quietly under the
|
||||
composer. The border turns transparent rather than going, so nothing moves. -->
|
||||
<!-- `data-works-with-composer`: a press in the card leaves Home's composer open
|
||||
(composerCollapse), since its menus add items to it. -->
|
||||
<div
|
||||
data-works-with-composer
|
||||
class="flex flex-col bg-surface-tertiary border border-border-light rounded-lg transition-colors duration-300 group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:border-transparent"
|
||||
>
|
||||
<div
|
||||
bind:clientHeight={toolbarHeight}
|
||||
class="sticky top-0 z-10 bg-surface-tertiary rounded-t-lg flex flex-wrap gap-2 items-center justify-between px-5 py-3 shrink-0"
|
||||
class="sticky top-0 group-has-[[data-composer-open]]/home:top-[var(--home-pinned)] z-10 bg-surface-tertiary transition-colors duration-300 group-has-[[data-composer-open]]/home:bg-surface rounded-t-lg flex flex-wrap gap-2 items-center justify-between px-5 py-3 shrink-0"
|
||||
use:triggerableByAI={{
|
||||
id: 'home-items-list',
|
||||
description: 'Lists of scripts, flows, and apps'
|
||||
@@ -1970,6 +1982,7 @@
|
||||
autofocus
|
||||
hideDropdownOnFreeText
|
||||
inputId="home-search-input"
|
||||
class="group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:[&>*]:!bg-transparent"
|
||||
onDropdownVisibleChange={(v) => (searchbarDropdownOpen = v)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
import { ChevronDown, Plus, Trash } from 'lucide-svelte'
|
||||
import GroupEditorDrawer from '$lib/components/GroupEditorDrawer.svelte'
|
||||
import FolderEditorDrawer from '$lib/components/FolderEditorDrawer.svelte'
|
||||
import GroupsPageLink from '$lib/components/GroupsPageLink.svelte'
|
||||
import { Cell, DataTable, Row } from '$lib/components/table'
|
||||
import Head from '$lib/components/table/Head.svelte'
|
||||
import AccessHelp from './AccessHelp.svelte'
|
||||
@@ -324,6 +325,9 @@
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex justify-end">
|
||||
<GroupsPageLink />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Takes what the list's own height leaves (its default `h-full`), which needs that height to
|
||||
|
||||
@@ -42,6 +42,12 @@
|
||||
// the trigger to the content.
|
||||
debounceDelay?: number
|
||||
classNames?: string
|
||||
/** Element to focus when the menu closes; defaults to the trigger, `null` leaves focus alone. */
|
||||
closeFocus?:
|
||||
| string
|
||||
| HTMLElement
|
||||
| ((trigger?: HTMLElement | null) => HTMLElement | null)
|
||||
| null
|
||||
triggr?: import('svelte').Snippet<[any]>
|
||||
children?: import('svelte').Snippet<[any]>
|
||||
class?: string
|
||||
@@ -64,6 +70,7 @@
|
||||
openOnHover = false,
|
||||
debounceDelay = 150,
|
||||
class: classNames = '',
|
||||
closeFocus = undefined,
|
||||
triggr,
|
||||
children
|
||||
}: Props = $props()
|
||||
@@ -80,6 +87,7 @@
|
||||
strategy: 'fixed'
|
||||
},
|
||||
loop: true,
|
||||
closeFocus: untrack(() => closeFocus),
|
||||
// Hover tooltips (e.g. NameIdTooltip on menu rows) portal to body, so a
|
||||
// click inside one — like its copy button — registers as an outside click.
|
||||
// Veto the close so interacting with a tooltip doesn't tear the menu down.
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
Code2Icon,
|
||||
Database,
|
||||
DollarSignIcon,
|
||||
FolderOpenIcon,
|
||||
HomeIcon,
|
||||
LayoutDashboardIcon,
|
||||
MailIcon,
|
||||
@@ -29,6 +30,7 @@
|
||||
Search,
|
||||
SearchCode,
|
||||
Unplug,
|
||||
UsersIcon,
|
||||
WandSparkles
|
||||
} from 'lucide-svelte'
|
||||
import Portal from '$lib/components/Portal.svelte'
|
||||
@@ -216,6 +218,20 @@
|
||||
icon: CalendarIcon,
|
||||
disabled: false
|
||||
},
|
||||
{
|
||||
search_id: 'nav:folders',
|
||||
label: 'Go to Folders',
|
||||
action: (newtab: boolean = false) => gotoPage('/folders', newtab),
|
||||
icon: FolderOpenIcon,
|
||||
disabled: !$roleCapabilities.visibility.folders
|
||||
},
|
||||
{
|
||||
search_id: 'nav:groups',
|
||||
label: 'Go to Groups',
|
||||
action: (newtab: boolean = false) => gotoPage('/groups', newtab),
|
||||
icon: UsersIcon,
|
||||
disabled: !$roleCapabilities.visibility.groups
|
||||
},
|
||||
...switchModeItems,
|
||||
{
|
||||
search_id: 'nav:service_logs',
|
||||
|
||||
@@ -1,90 +1,73 @@
|
||||
<script lang="ts">
|
||||
import { onMount, setContext, type Snippet } from 'svelte'
|
||||
import AIChat from '$lib/components/copilot/chat/AIChat.svelte'
|
||||
import type { DraftAttachments } from '$lib/components/copilot/chat/messageDraft.svelte'
|
||||
import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
|
||||
import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { getOrCreateRuntime } from './sessionRuntime.svelte'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot'
|
||||
import { copilotWorkspace } from '$lib/aiStore'
|
||||
import {
|
||||
getEffectiveWorkspaceId,
|
||||
getSessionDraftAttachments,
|
||||
getSessionDraftPrompt,
|
||||
holdHomeDraft,
|
||||
homeStarterSession,
|
||||
setSessionDraftAttachments,
|
||||
selectSession,
|
||||
sessionInCurrentFamily,
|
||||
sessionPageHref,
|
||||
sessionState,
|
||||
setNewSessionWorkspace,
|
||||
setSessionDraftPrompt
|
||||
setSessionDraftPrompt,
|
||||
takeHomeDraftFlash,
|
||||
takeHomeDraftFocus
|
||||
} from './sessionState.svelte'
|
||||
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
|
||||
import { useWorkModeLock } from './workModeLock.svelte'
|
||||
import { AIWorkMode } from '$lib/components/copilot/chat/workMode'
|
||||
import { takeComposerFocus } from './homeComposerFocus'
|
||||
import { homeComposerContext } from './homeComposerContext.svelte'
|
||||
|
||||
// Home's block is the empty session's own chat, run by that session's manager: the
|
||||
// Home's block is the unsent session's own chat, run by that session's manager: the
|
||||
// composer, its controls and what a send does are the session's, not a copy of them.
|
||||
// Picked once; the parent remounts this on a workspace switch, which changes the family.
|
||||
// Picked once; the parent remounts this on a workspace family switch and whenever
|
||||
// another draft is asked for (New session, a draft picked in the session list).
|
||||
// `placeholder` stands in while the chat waits on its config; `onSettled` reports the height
|
||||
// the chat first took, for the next placeholder to take.
|
||||
// the chat first took, for the next placeholder to take. A workspace small enough that the
|
||||
// composer is the page's main way in keeps it open at rest.
|
||||
let {
|
||||
onShown,
|
||||
placeholder,
|
||||
onSettled
|
||||
}: { onShown?: () => void; placeholder?: Snippet; onSettled?: (height: number) => void } =
|
||||
$props()
|
||||
}: {
|
||||
placeholder?: Snippet
|
||||
onSettled?: (height: number) => void
|
||||
} = $props()
|
||||
|
||||
const initialSession = homeStarterSession()
|
||||
const sessionId = initialSession.id
|
||||
holdHomeDraft(sessionId)
|
||||
const runtime = getOrCreateRuntime(initialSession)
|
||||
setContext<AIChatManager>('aiChatManager', runtime.manager)
|
||||
|
||||
const session = $derived(sessionState.sessions.find((s) => s.id === sessionId))
|
||||
// Switches the page along with the session, as the workspace bar below does.
|
||||
// The draft acts on the workspace the page header names: holdHomeDraft keeps it there, so
|
||||
// the lock's way out to a dev workspace switches the page.
|
||||
const workModeLock = useWorkModeLock(() => session, true)
|
||||
const actingWorkspaceId = $derived(
|
||||
(session ? getEffectiveWorkspaceId(session) : undefined) ?? $workspaceStore ?? undefined
|
||||
)
|
||||
const starterPrompts = new StarterPrompts(
|
||||
() => actingWorkspaceId,
|
||||
() => $workspaceStore ?? undefined,
|
||||
() => !workModeLock.current && runtime.manager.workMode !== AIWorkMode.USE
|
||||
)
|
||||
|
||||
// The AI config (models, whether AI is hidden) of the workspace the draft acts on, as the
|
||||
// session page loads it, so a fork picked here shows its own models and the session page
|
||||
// can judge it at once on arrival instead of covering it while it asks. The layout also
|
||||
// loads Home's own workspace into the same shared config, and the last request wins, so
|
||||
// this asks again whenever a later request named another workspace.
|
||||
$effect(() => {
|
||||
if (actingWorkspaceId && $copilotWorkspaceRequested !== actingWorkspaceId)
|
||||
loadCopilot(actingWorkspaceId)
|
||||
})
|
||||
|
||||
// The turn is already running on the session's manager; the page it belongs to takes over.
|
||||
function onSent() {
|
||||
selectSession(sessionId)
|
||||
void goto(sessionPageHref(sessionId))
|
||||
}
|
||||
|
||||
function onDraftChange(text: string) {
|
||||
setSessionDraftPrompt(sessionId, text)
|
||||
// A prompt typed here is what the AI Sessions switch should open; an empty box leaves
|
||||
// the switch resuming whatever session the user was last in.
|
||||
if (text.trim()) selectSession(sessionId)
|
||||
}
|
||||
|
||||
function onAttachmentsChange(attachments: DraftAttachments) {
|
||||
setSessionDraftAttachments(sessionId, attachments)
|
||||
if (Object.values(attachments).some((lane) => lane.length > 0)) selectSession(sessionId)
|
||||
}
|
||||
|
||||
// Asked for with the draft, and taken once the chat is there: it mounts only after a config
|
||||
// has loaded, and this block can remount meanwhile (a workspace switch reloads both).
|
||||
let aiChat: AIChat | undefined = $state(undefined)
|
||||
function bindChat(chat: AIChat | undefined) {
|
||||
aiChat = chat
|
||||
if (chat && takeHomeDraftFocus()) setTimeout(() => chat.focusInput(), 0)
|
||||
if (chat && takeHomeDraftFlash()) setTimeout(() => chat.flashComposer(), 0)
|
||||
}
|
||||
let chatWrapper: HTMLDivElement | undefined = $state(undefined)
|
||||
// A seeded draft holds the composer open, which is not the shape it rests in once the
|
||||
// draft is sent, so only a mount with an empty draft is measured.
|
||||
@@ -98,57 +81,41 @@
|
||||
const wrapper = chatWrapper
|
||||
requestAnimationFrame(() => onSettled?.(wrapper.offsetHeight))
|
||||
})
|
||||
// The draft acts on the workspace Home shows, whichever picker switched it: a switch within
|
||||
// the family keeps this mount, so the draft's pick has to follow. A switch to another family
|
||||
// remounts with that family's draft, so this one is left where it was. A staged fork of the
|
||||
// shown workspace stays. On mount, a draft that differs is one that follows Home, moved off it
|
||||
// by a switch made elsewhere (homeStarterSession).
|
||||
onMount(() =>
|
||||
workspaceStore.subscribe((ws) => {
|
||||
const s = sessionState.sessions.find((x) => x.id === sessionId)
|
||||
if (!ws || !s || s.workspace_id || s.pending_workspace_id === ws) return
|
||||
if (sessionInCurrentFamily(s)) setNewSessionWorkspace(sessionId, ws)
|
||||
})
|
||||
)
|
||||
onMount(() => {
|
||||
onShown?.()
|
||||
if (takeComposerFocus()) setTimeout(() => aiChat?.focusInput(), 0)
|
||||
// The rows' "Ask AI" lands here. Before the chat has mounted (its config still
|
||||
// loading) there is nowhere to put the item, and the attach does nothing.
|
||||
return homeComposerContext.register(async (element) => {
|
||||
await aiChat?.attachContext(element)
|
||||
return homeComposerContext.register({
|
||||
sessionId,
|
||||
attach: async (element) => {
|
||||
await aiChat?.attachContext(element)
|
||||
},
|
||||
focus: () => aiChat?.focusInput(),
|
||||
flash: () => aiChat?.flashComposer(),
|
||||
runtime
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
{#snippet actingOn()}
|
||||
{#if session}
|
||||
<SessionWorkspaceBar {session} switchesWorkspace />
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<!-- Until a config has loaded the chat reads "AI not configured" and would flash its disabled
|
||||
state. Any loaded config will do, so a fork switch does not hide it while the fork's loads.
|
||||
The item count decides whether the composer rests collapsed, so it waits for that too
|
||||
rather than open and fold up a moment later. -->
|
||||
{#if session && $copilotWorkspace !== undefined && starterPrompts.fewItems !== undefined}
|
||||
{#if session && $copilotWorkspace !== undefined && starterPrompts.empty !== undefined}
|
||||
<div bind:this={chatWrapper}>
|
||||
<AIChat
|
||||
bind:this={aiChat}
|
||||
bind:this={() => aiChat, bindChat}
|
||||
hideHeader
|
||||
hideModeSelector
|
||||
wideLayout
|
||||
initialInstructions={getSessionDraftPrompt(sessionId)}
|
||||
{onDraftChange}
|
||||
onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)}
|
||||
initialAttachments={getSessionDraftAttachments(sessionId)}
|
||||
{onAttachmentsChange}
|
||||
onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)}
|
||||
starter={{
|
||||
where: 'home',
|
||||
suggestions: starterPrompts.suggestions,
|
||||
fewItems: starterPrompts.fewItems
|
||||
restsOpen: starterPrompts.empty
|
||||
}}
|
||||
{onSent}
|
||||
{actingOn}
|
||||
workModeLock={workModeLock.current}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
)
|
||||
const isFork = $derived(!!parentWorkspaceId)
|
||||
|
||||
// Same gate as the sidebar WorkspaceMenu / SessionWorkspaceBar. On cloud,
|
||||
// Same gate as the sidebar WorkspaceMenu. On cloud,
|
||||
// forking is a premium-only feature (backend caps it per paid seat).
|
||||
const forksAllowed = $derived(
|
||||
(!isCloudHosted() || $maybePremium) &&
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Building, MessagesSquare } from 'lucide-svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import { enterSessionModeFromNav, exitSessionMode } from './sessionSwitch.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { page } from '$app/state'
|
||||
|
||||
// Which side of the switch is active. `nav` = workspace navigation (the classic
|
||||
// app), `session` = the sessions sidebar + chat + preview.
|
||||
let {
|
||||
mode,
|
||||
isCollapsed = false,
|
||||
// Fired right before the toggle navigates. Lets a host (e.g. the mobile menu
|
||||
// drawer) keep itself open across the mode switch.
|
||||
onToggle
|
||||
}: { mode: 'nav' | 'session'; isCollapsed?: boolean; onToggle?: () => void } = $props()
|
||||
|
||||
// The group's highlighted side. Melt moves it on click, before the navigation
|
||||
// that would change `mode`, so it is derived from the route (which wins once
|
||||
// a switch navigates) and pushed back when one does not, or the rail would
|
||||
// read "AI Sessions" on an editor page with the clicked side inert until
|
||||
// "Workspace" was pressed first.
|
||||
let selected: string | string[] | null | undefined = $derived(mode)
|
||||
|
||||
function onSelected(next: 'nav' | 'session') {
|
||||
if (next === mode) return
|
||||
onToggle?.()
|
||||
if (next === 'session') {
|
||||
// An editor whose draft could not be persisted keeps the user on the
|
||||
// page, as its own "Open in AI session" button does, rather than open a
|
||||
// session on an older draft than the one on screen.
|
||||
void enterSessionModeFromNav().catch((e) => {
|
||||
selected = mode
|
||||
sendUserToast(e instanceof Error ? e.message : String(e), true)
|
||||
})
|
||||
} else void exitSessionMode()
|
||||
}
|
||||
|
||||
// Pressing the already-active "Workspace" side goes home, so the toggle doubles
|
||||
// as the home button when there is no mode to switch to. `onToggle` is
|
||||
// deliberately not fired: this is a plain in-mode navigation, so the mobile menu
|
||||
// drawer should dismiss like it does for any other nav link.
|
||||
function onNavActivate() {
|
||||
if (mode !== 'nav') return
|
||||
// `goto` has no same-URL short-circuit, so navigating from home would push a
|
||||
// duplicate history entry and make the next Back press look broken.
|
||||
if (page.url.pathname === '/') return
|
||||
void goto('/')
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Each ToggleButton renders inside a Tooltip wrapper, which is the actual flex
|
||||
child of the group's track — so the buttons fill the rail width only if those
|
||||
wrappers grow. `[&>*]:flex-1` makes every direct child split the track evenly. -->
|
||||
<ToggleButtonGroup
|
||||
bind:selected
|
||||
{onSelected}
|
||||
tabListClass={isCollapsed ? 'flex-col w-full [&>*]:w-full' : 'w-full [&>*]:flex-1'}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="nav"
|
||||
icon={isCollapsed ? Building : undefined}
|
||||
label="Workspace"
|
||||
iconOnly={isCollapsed}
|
||||
tooltip={isCollapsed ? 'Workspace' : undefined}
|
||||
size="sm"
|
||||
class="w-full justify-center whitespace-nowrap"
|
||||
onActivate={onNavActivate}
|
||||
/>
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="session"
|
||||
icon={isCollapsed ? MessagesSquare : undefined}
|
||||
label="AI Sessions"
|
||||
iconOnly={isCollapsed}
|
||||
tooltip={isCollapsed ? 'AI Sessions (beta)' : undefined}
|
||||
size="sm"
|
||||
class="w-full justify-center whitespace-nowrap"
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts">
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import Modal from '$lib/components/common/modal/Modal.svelte'
|
||||
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import SidebarSectionHeader from '$lib/components/sidebar/SidebarSectionHeader.svelte'
|
||||
import {
|
||||
Archive,
|
||||
ArchiveRestore,
|
||||
@@ -23,20 +23,21 @@
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { takeNewSessionSeed, type NewSessionSeed } from './sessionSwitch.svelte'
|
||||
import { leaveForHome, openDraftOnHome, openNewSession } from './sessionSwitch.svelte'
|
||||
import { homeComposerContext } from './homeComposerContext.svelte'
|
||||
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
|
||||
import { slide } from 'svelte/transition'
|
||||
import {
|
||||
createSession,
|
||||
deleteSessionsForWorkspace,
|
||||
homeDraft,
|
||||
isForkSession,
|
||||
opensOnHome,
|
||||
reconcileAfterWorkspaceChange,
|
||||
renameSession,
|
||||
selectSession,
|
||||
sessionPageHref,
|
||||
sessionLastActivityAt,
|
||||
sessionState,
|
||||
setNewSessionWorkspace,
|
||||
setSessionArchived,
|
||||
syncWorkspaceTo,
|
||||
withOpenSessionTeardown,
|
||||
@@ -49,8 +50,7 @@
|
||||
getRuntime,
|
||||
getSessionChatPeek,
|
||||
getSessionChatStatus,
|
||||
removeSession,
|
||||
resetSessionPreviewTabs
|
||||
removeSession
|
||||
} from './sessionRuntime.svelte'
|
||||
import SessionStatusDot from './SessionStatusDot.svelte'
|
||||
import UnreadCountBadge from '$lib/components/common/badge/UnreadCountBadge.svelte'
|
||||
@@ -116,10 +116,15 @@
|
||||
return () => clearInterval(handle)
|
||||
})
|
||||
|
||||
// Only highlight the active session while the sessions page is open — elsewhere
|
||||
// `currentSessionId` lingers but no row should appear selected.
|
||||
const onSessionsPage = $derived(page.url.pathname.startsWith('/sessions'))
|
||||
const sessionActive = $derived(onSessionsPage)
|
||||
// The row the page is showing: the open session on its page, the draft in Home's
|
||||
// composer on Home. Elsewhere `currentSessionId` lingers but no row is selected.
|
||||
const activeRowId = $derived(
|
||||
page.url.pathname.startsWith('/sessions')
|
||||
? sessionState.currentSessionId
|
||||
: page.url.pathname === '/'
|
||||
? homeDraft.id
|
||||
: undefined
|
||||
)
|
||||
|
||||
interface Props {
|
||||
isCollapsed?: boolean
|
||||
@@ -176,10 +181,12 @@
|
||||
// total, and keyboard navigation.
|
||||
const visibleSessions = $derived(
|
||||
sessionState.sessions.filter((s) => {
|
||||
// A blank nobody has typed in is Home's composer at rest, not a session yet.
|
||||
if (s.transient) return false
|
||||
// Pending (unsent) sessions show like any other, so several drafts can be
|
||||
// set up in parallel; they group by pending_workspace_id via sessionRootOf.
|
||||
// The open session always stays in the list, ignoring every filter.
|
||||
if (s.id === sessionState.currentSessionId) return true
|
||||
// The row on screen always stays in the list, ignoring every filter.
|
||||
if (s.id === activeRowId) return true
|
||||
if (s.archived && !showArchived.val) return false
|
||||
if (lastActivityDays.val > 0) {
|
||||
const cutoff = clock - lastActivityDays.val * 24 * 60 * 60 * 1000
|
||||
@@ -352,7 +359,7 @@
|
||||
const archivedCount = $derived(
|
||||
sessionState.sessions.filter((s) => {
|
||||
if (!s.archived || s.transient) return false
|
||||
if (s.id === sessionState.currentSessionId) return true
|
||||
if (s.id === activeRowId) return true
|
||||
if (lastActivityDays.val > 0) {
|
||||
const cutoff = clock - lastActivityDays.val * 24 * 60 * 60 * 1000
|
||||
if (sessionLastActivityAt(s) < cutoff) return false
|
||||
@@ -396,6 +403,10 @@
|
||||
async function activate(session: Session, restoreFocus: boolean = false) {
|
||||
// Picking a session leaves browse mode so the chat comes back.
|
||||
onSelectSession?.()
|
||||
if (opensOnHome(session)) {
|
||||
await openDraftOnHome(session.id)
|
||||
return
|
||||
}
|
||||
selectSession(session.id)
|
||||
// The global workspaceStore is intentionally NOT switched here: a session
|
||||
// runs against its own workspace via the chat manager's workspace resolver,
|
||||
@@ -415,59 +426,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function createAndOpen() {
|
||||
// A new session opened from a Windmill page adopts that page as its first
|
||||
// preview tab.
|
||||
if (!onSessionsPage) {
|
||||
await createAndOpenWith(page.url.pathname + page.url.search)
|
||||
return
|
||||
}
|
||||
// On the sessions page there is nothing meaningful on screen to capture,
|
||||
// except the item the user just left to get here: that one is offered (once)
|
||||
// before the session is created, and answerSeedOffer picks up from there.
|
||||
const seed = takeNewSessionSeed()
|
||||
if (seed) {
|
||||
seedOffer = seed
|
||||
seedOfferOpen = true
|
||||
return
|
||||
}
|
||||
await createAndOpenWith(undefined)
|
||||
// The rail menu hands focus back to its trigger once it has closed, after New session has
|
||||
// focused Home's composer: the composer takes it back instead.
|
||||
let newSessionFromRail = false
|
||||
function railMenuCloseFocus(trigger?: HTMLElement | null): HTMLElement | null {
|
||||
if (!newSessionFromRail) return trigger ?? null
|
||||
newSessionFromRail = false
|
||||
homeComposerContext.focus()
|
||||
return null
|
||||
}
|
||||
|
||||
// `previewUrl` undefined leaves the preview empty until the chat opens something.
|
||||
async function createAndOpenWith(previewUrl: string | undefined) {
|
||||
const fresh = createSession()
|
||||
if (previewUrl) resetSessionPreviewTabs(fresh.id, previewUrl)
|
||||
await activate(fresh)
|
||||
}
|
||||
|
||||
// The item createAndOpen is asking about. Closing the dialog any other way than
|
||||
// answering (Escape, the corner X, the backdrop) creates nothing: the click was
|
||||
// met with a question, not a session. Kept after the dialog closes, since the
|
||||
// title reads it through the close fade; `seedOfferOpen` alone gates rendering.
|
||||
let seedOffer = $state<NewSessionSeed | undefined>(undefined)
|
||||
let seedOfferOpen = $state(false)
|
||||
// Focus moves onto the primary answer as the dialog opens. Enter is left to
|
||||
// the focused button (the dialog does not bind it), and the "New session"
|
||||
// button that opened the dialog would otherwise keep focus and answer Enter
|
||||
// with a second, unasked session underneath.
|
||||
let keepButton: Button | undefined = $state(undefined)
|
||||
$effect(() => {
|
||||
if (seedOfferOpen) keepButton?.focus()
|
||||
})
|
||||
async function answerSeedOffer(keep: boolean) {
|
||||
const offer = seedOffer
|
||||
seedOfferOpen = false
|
||||
if (!offer) return
|
||||
await createAndOpenWith(keep ? offer.url : undefined)
|
||||
}
|
||||
|
||||
// The `+` on a workspace group header: a new session parked on that group's
|
||||
// workspace rather than the one currently open.
|
||||
// The `+` on a workspace group header: a new session in that group's workspace,
|
||||
// which the header switches to, since Home's draft acts on the header's workspace.
|
||||
async function createAndOpenIn(workspaceId: string) {
|
||||
const fresh = createSession()
|
||||
setNewSessionWorkspace(fresh.id, workspaceId)
|
||||
await activate(fresh)
|
||||
await openNewSession(workspaceId)
|
||||
}
|
||||
|
||||
let editingId: string | undefined = $state(undefined)
|
||||
@@ -584,6 +556,13 @@
|
||||
selectedIds = allSelected ? [] : [...selectableIds]
|
||||
}
|
||||
|
||||
// Home shows no archived draft, so archiving the one its composer holds moves Home on.
|
||||
function leaveArchivedHomeDraft(ids: string[]) {
|
||||
if (page.url.pathname === '/' && homeDraft.id && ids.includes(homeDraft.id)) {
|
||||
void leaveForHome()
|
||||
}
|
||||
}
|
||||
|
||||
function handleBatchArchive() {
|
||||
const archive = !allSelectedArchived
|
||||
let skipped = 0
|
||||
@@ -599,6 +578,7 @@
|
||||
}
|
||||
setSessionArchived(id, archive)
|
||||
}
|
||||
if (archive) leaveArchivedHomeDraft(selectedIds)
|
||||
exitSelectionMode()
|
||||
if (skipped > 0) {
|
||||
sendUserToast(
|
||||
@@ -607,31 +587,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
// After deleting the open session, land somewhere usable: the newest remaining
|
||||
// session, else a fresh one. The page derives the visible session from the
|
||||
// `session` query, so leaving the URL on a deleted session would fall
|
||||
// through to recovery and open a blank one rather than their recent work.
|
||||
async function openReplacementSession() {
|
||||
const next = sessionState.sessions[0]
|
||||
if (next) await activate(next)
|
||||
else {
|
||||
const fresh = createSession()
|
||||
await goto(sessionPageHref(fresh.id))
|
||||
}
|
||||
}
|
||||
|
||||
// Batch delete never touches fork workspaces — same default as the single
|
||||
// delete, where the user has to tick the fork box explicitly.
|
||||
async function handleConfirmedBatchDelete() {
|
||||
const ids = selectedIds
|
||||
batchDeleteOpen = false
|
||||
if (ids.length === 0) return
|
||||
const current = sessionState.currentSessionId
|
||||
const wasActive = !!current && ids.includes(current)
|
||||
const active = activeRowId
|
||||
const wasActive = !!active && ids.includes(active)
|
||||
await withOpenSessionTeardown(async () => {
|
||||
for (const id of ids) removeSession(id)
|
||||
exitSelectionMode()
|
||||
if (wasActive) await openReplacementSession()
|
||||
if (wasActive) await leaveForHome()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -647,7 +614,7 @@
|
||||
pendingDelete = undefined
|
||||
deleteAlsoFork = false
|
||||
if (!session) return
|
||||
const wasActive = sessionState.currentSessionId === session.id
|
||||
const wasActive = activeRowId === session.id
|
||||
await withOpenSessionTeardown(async () => {
|
||||
removeSession(session.id)
|
||||
if (forkToDelete) {
|
||||
@@ -665,7 +632,7 @@
|
||||
if (forkToDelete && forkParentId && $workspaceStore === forkToDelete) {
|
||||
syncWorkspaceTo(forkParentId)
|
||||
}
|
||||
if (wasActive) await openReplacementSession()
|
||||
if (wasActive) await leaveForHome()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -708,17 +675,9 @@
|
||||
explanatory message, mirroring the sidebar AI chat. -->
|
||||
{:else if isCollapsed}
|
||||
<div class={embedded ? '' : 'px-2 pt-3 pb-2 border-b border-light'}>
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={createAndOpen}
|
||||
{isCollapsed}
|
||||
icon={Plus}
|
||||
label="New session"
|
||||
class="!text-xs"
|
||||
/>
|
||||
<Menubar>
|
||||
{#snippet children({ createMenu })}
|
||||
<Menu {createMenu} usePointerDownOutside submenuSafe>
|
||||
<Menu {createMenu} usePointerDownOutside submenuSafe closeFocus={railMenuCloseFocus}>
|
||||
{#snippet triggr({ trigger })}
|
||||
<div class="relative">
|
||||
<MenuButton
|
||||
@@ -740,8 +699,15 @@
|
||||
{/snippet}
|
||||
{#snippet children({ item, builders })}
|
||||
<div class="divide-y min-w-48" role="none">
|
||||
<div class="py-1" role="none">
|
||||
<MenuItem class={menuItemBase} onClick={createAndOpen} {item}>
|
||||
<div class="py-1" role="none" data-asks-for-composer>
|
||||
<MenuItem
|
||||
class={menuItemBase}
|
||||
onClick={() => {
|
||||
newSessionFromRail = true
|
||||
void openNewSession()
|
||||
}}
|
||||
{item}
|
||||
>
|
||||
<Plus size={14} />
|
||||
New session
|
||||
</MenuItem>
|
||||
@@ -771,8 +737,7 @@
|
||||
{@const status = runtime
|
||||
? getSessionChatStatus(runtime)
|
||||
: (getSessionChatPeek(session.id)?.status ?? 'idle')}
|
||||
{@const isSelected =
|
||||
sessionActive && session.id === sessionState.currentSessionId}
|
||||
{@const isSelected = session.id === activeRowId}
|
||||
{@const unread = unreadFor(session)}
|
||||
{@const draft = hasDraft(session)}
|
||||
<MenuItem
|
||||
@@ -822,8 +787,8 @@
|
||||
? 'border-b border-light'
|
||||
: ''}"
|
||||
>
|
||||
<!-- Selection mode reuses the New session row (same h-8 slot, same px-2) so
|
||||
the list below it never moves. -->
|
||||
<!-- Selection mode reuses the options row (same h-8 slot) so the list below it
|
||||
never moves. -->
|
||||
{#if selectionMode}
|
||||
<div class="flex flex-row items-center gap-1.5 h-8 px-2">
|
||||
<Checkbox
|
||||
@@ -866,17 +831,7 @@
|
||||
{GROUP_BY_OPTIONS.find((o) => o.value === groupBy.val)?.hint ?? ''}
|
||||
</span>
|
||||
{/snippet}
|
||||
<div class="flex flex-row items-center gap-0.5 pr-0.5">
|
||||
<div class="flex-1 min-w-0">
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={createAndOpen}
|
||||
isCollapsed={false}
|
||||
icon={Plus}
|
||||
label="New session"
|
||||
class="!text-xs"
|
||||
/>
|
||||
</div>
|
||||
{#snippet listOptions(size: 'sm' | 'md')}
|
||||
<DropdownV2
|
||||
fixedHeight={false}
|
||||
placement="bottom-end"
|
||||
@@ -924,7 +879,7 @@
|
||||
{#snippet buttonReplacement()}
|
||||
<Button
|
||||
nonCaptureEvent
|
||||
unifiedSize="md"
|
||||
unifiedSize={size}
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: EllipsisVertical }}
|
||||
@@ -934,41 +889,44 @@
|
||||
/>
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
</div>
|
||||
{/if}
|
||||
{#if collapsible}
|
||||
<!-- Only the collapsible sidebar section needs a title: it doubles as the
|
||||
fold toggle. In the rail the list owns the pane, so the label is noise. -->
|
||||
<div class="flex flex-row items-center pl-1 pr-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (sectionCollapsed.val = !sectionCollapsed.val)}
|
||||
class="text-secondary text-[0.5rem] uppercase flex flex-row items-center gap-1 rounded px-1 -mx-1 py-0.5 hover:bg-surface-hover focus:outline-none"
|
||||
aria-expanded={!sectionCollapsed.val}
|
||||
{/snippet}
|
||||
{#if collapsible}
|
||||
<SidebarSectionHeader
|
||||
title="AI sessions"
|
||||
collapsed={sectionCollapsed.val}
|
||||
onToggle={() => (sectionCollapsed.val = !sectionCollapsed.val)}
|
||||
disabled={visibleSessions.length === 0}
|
||||
>
|
||||
AI sessions
|
||||
{#if visibleSessions.length > 0}
|
||||
{#if sectionCollapsed.val}
|
||||
<ChevronRight size={10} />
|
||||
{:else}
|
||||
<ChevronDown size={10} />
|
||||
{/if}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{#snippet actions()}
|
||||
{@render listOptions('sm')}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: Plus }}
|
||||
title="New session"
|
||||
aria-label="New session"
|
||||
data-asks-for-composer
|
||||
btnClasses="text-secondary"
|
||||
onClick={() => openNewSession()}
|
||||
/>
|
||||
{/snippet}
|
||||
</SidebarSectionHeader>
|
||||
{:else}
|
||||
<!-- Where the list owns the pane, a title would only repeat what the pane is. -->
|
||||
<div class="flex flex-row items-center gap-0.5 h-8 pr-0.5 justify-end">
|
||||
{@render listOptions('md')}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if !collapsible || !sectionCollapsed.val}
|
||||
<div
|
||||
bind:this={listRoot}
|
||||
transition:slide={{ duration: 180 }}
|
||||
class={twMerge(
|
||||
'flex flex-col gap-0.5 overflow-y-auto',
|
||||
'flex flex-col gap-0.5',
|
||||
// Shift-clicking rows would otherwise paint a text selection across them.
|
||||
selectionMode ? 'select-none' : '',
|
||||
// In the rail the picker is the whole list and the rail scrolls;
|
||||
// only cap height when it's one section among others (normal sidebar).
|
||||
collapsible ? 'max-h-[40vh]' : ''
|
||||
selectionMode ? 'select-none' : ''
|
||||
)}
|
||||
onkeydown={handleListKeydown}
|
||||
role="listbox"
|
||||
@@ -984,7 +942,7 @@
|
||||
{@const status = runtime
|
||||
? getSessionChatStatus(runtime)
|
||||
: (getSessionChatPeek(session.id)?.status ?? 'idle')}
|
||||
{@const isSelected = sessionActive && session.id === sessionState.currentSessionId}
|
||||
{@const isSelected = session.id === activeRowId}
|
||||
{@const isEditing = editingId === session.id}
|
||||
{@const unread = unreadFor(session)}
|
||||
{@const draft = hasDraft(session)}
|
||||
@@ -1112,7 +1070,10 @@
|
||||
{
|
||||
displayName: 'Archive',
|
||||
icon: Archive,
|
||||
action: () => setSessionArchived(session.id, true)
|
||||
action: () => {
|
||||
setSessionArchived(session.id, true)
|
||||
leaveArchivedHomeDraft([session.id])
|
||||
}
|
||||
}
|
||||
]),
|
||||
{
|
||||
@@ -1209,7 +1170,7 @@
|
||||
plain text, no workspace icon or chip. -->
|
||||
<div
|
||||
class={twMerge(
|
||||
'group flex flex-row items-center gap-1 pl-1 pr-0.5 pt-2 pb-1 min-w-0',
|
||||
'group flex flex-row items-center gap-1 pl-2 pr-0.5 pt-2 pb-1 min-w-0',
|
||||
// Space groups apart so their boundaries read clearly.
|
||||
groupIdx > 0 ? 'mt-4' : ''
|
||||
)}
|
||||
@@ -1235,6 +1196,7 @@
|
||||
on:click={() => createAndOpenIn(groupWsId)}
|
||||
title="New session in {group.label}"
|
||||
aria-label="New session in {group.label}"
|
||||
data-asks-for-composer
|
||||
wrapperClasses="ml-auto shrink-0"
|
||||
btnClasses="text-tertiary opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
|
||||
/>
|
||||
@@ -1248,7 +1210,11 @@
|
||||
{/if}
|
||||
</div>
|
||||
{#if selectionMode}
|
||||
<div class="flex flex-col gap-1 px-1 pt-1.5">
|
||||
<!-- Pinned to the sidebar's bottom edge while the rows scroll under it; z-10 keeps it
|
||||
above the sidebar's bottom fade. -->
|
||||
<div
|
||||
class="sticky bottom-0 z-10 flex flex-col gap-1 px-1 pt-1.5 pb-2 bg-[var(--sidebar-bg-light)] dark:bg-[var(--sidebar-bg-dark)]"
|
||||
>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
@@ -1330,30 +1296,3 @@
|
||||
{/if}
|
||||
</div>
|
||||
</ConfirmationModal>
|
||||
|
||||
<!-- Two answers of equal standing, so Enter is left to whichever button has
|
||||
focus rather than bound to one of them by the dialog. -->
|
||||
<Modal
|
||||
bind:open={seedOfferOpen}
|
||||
kind="X"
|
||||
enterConfirms={false}
|
||||
title="Keep this {seedOffer?.kind ?? 'item'} in the new session?"
|
||||
description="You came here from {seedOffer?.path ?? ''}."
|
||||
>
|
||||
<p class="text-sm text-secondary">
|
||||
Keeping it opens it in the preview, so the chat starts with it as context.
|
||||
</p>
|
||||
<div class="flex justify-end gap-2 mt-4">
|
||||
<Button variant="default" unifiedSize="sm" onClick={() => answerSeedOffer(false)}>
|
||||
Start empty
|
||||
</Button>
|
||||
<Button
|
||||
bind:this={keepButton}
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
onClick={() => answerSeedOffer(true)}
|
||||
>
|
||||
Keep in preview
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
<script lang="ts" module>
|
||||
import { get } from 'svelte/store'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { setSessionPendingWorkspace, stopFollowingHome } from './sessionState.svelte'
|
||||
import { switchWorkspace } from '$lib/storeUtils'
|
||||
import { workspaceAIClients } from '$lib/components/copilot/lib'
|
||||
import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl'
|
||||
|
||||
function followPick(id: string, switchesWorkspace: boolean) {
|
||||
if (!switchesWorkspace || get(workspaceStore) === id) return
|
||||
workspaceAIClients.init(id)
|
||||
switchWorkspace(id)
|
||||
void fixupUrlAfterWorkspaceSwitch(id)
|
||||
}
|
||||
|
||||
// Before the pick, which stores the session: Home would otherwise move a draft picked off
|
||||
// Home back to the workspace it shows.
|
||||
function releaseFromHome(sessionId: string, switchesWorkspace: boolean) {
|
||||
if (!switchesWorkspace) stopFollowingHome(sessionId)
|
||||
}
|
||||
|
||||
/** Point a session that has not sent yet at workspace `id`, as a pick in this bar does. */
|
||||
export function pickSessionWorkspace(sessionId: string, id: string, switchesWorkspace: boolean) {
|
||||
releaseFromHome(sessionId, switchesWorkspace)
|
||||
// Pre-send only: writes the pending pick. workspace_id stays undefined until
|
||||
// the user sends their first message. The chat targets this pending workspace
|
||||
// via the manager's workspace resolver, not the global workspaceStore.
|
||||
setSessionPendingWorkspace(sessionId, id)
|
||||
followPick(id, switchesWorkspace)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import {
|
||||
getEffectiveWorkspaceId,
|
||||
setSessionPendingFork,
|
||||
type Session
|
||||
} from './sessionState.svelte'
|
||||
import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte'
|
||||
import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte'
|
||||
|
||||
// `switchesWorkspace`: a pick also moves the navigation workspace. For a host whose page
|
||||
// shows the navigation workspace around the composer (Home), where a pick that left it
|
||||
// behind would read as ignored; the session page follows the session's own workspace instead.
|
||||
let { session, switchesWorkspace = false }: { session: Session; switchesWorkspace?: boolean } =
|
||||
$props()
|
||||
|
||||
// Effective workspace for display: committed → pending pick → active store.
|
||||
const effectiveId = $derived(getEffectiveWorkspaceId(session) ?? $workspaceStore ?? undefined)
|
||||
const pendingFork = $derived(session.pending_fork)
|
||||
|
||||
function pick(id: string) {
|
||||
pickSessionWorkspace(session.id, id, switchesWorkspace)
|
||||
}
|
||||
|
||||
function stageFork(req: { parent_workspace_id: string; id: string; name: string }) {
|
||||
releaseFromHome(session.id, switchesWorkspace)
|
||||
setSessionPendingFork(session.id, req)
|
||||
followPick(req.parent_workspace_id, switchesWorkspace)
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- A control of the composer's toolbar; on a narrow window it gives up its label first. -->
|
||||
<div class="flex flex-row items-center gap-1 min-w-0 text-2xs text-secondary">
|
||||
<span class="shrink-0 hidden lg:inline">Acting on</span>
|
||||
<WorkspaceFamilyPicker
|
||||
selectedId={effectiveId}
|
||||
{pendingFork}
|
||||
onPick={pick}
|
||||
onCreateFork={stageFork}
|
||||
createForkCaption="Created when you send your first message."
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<WorkspaceScopeTrigger workspaceId={effectiveId} {pendingFork} class="max-w-[16rem]" />
|
||||
{/snippet}
|
||||
</WorkspaceFamilyPicker>
|
||||
</div>
|
||||
@@ -9,21 +9,16 @@
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { onDestroy, setContext, untrack } from 'svelte'
|
||||
import { setContext, untrack } from 'svelte'
|
||||
import { Pane, Splitpanes } from 'svelte-splitpanes'
|
||||
import type AIChat from '$lib/components/copilot/chat/AIChat.svelte'
|
||||
import ComposerPlaceholder from '$lib/components/copilot/chat/ComposerPlaceholder.svelte'
|
||||
import SessionGreeting from '$lib/components/copilot/chat/starter/SessionGreeting.svelte'
|
||||
import ComposerSuggestions from '$lib/components/copilot/chat/starter/ComposerSuggestions.svelte'
|
||||
import {
|
||||
globalComposerSuggestion,
|
||||
STARTER_PLACEHOLDER,
|
||||
USE_STARTER_PLACEHOLDER,
|
||||
type ComposerSelection
|
||||
} from '$lib/components/copilot/chat/composerBox'
|
||||
import { useSessionPermissions } from './sessionPermissions.svelte'
|
||||
import { useWorkModeLock } from './workModeLock.svelte'
|
||||
import { AIWorkMode } from '$lib/components/copilot/chat/workMode'
|
||||
import EditableInput from '$lib/components/common/EditableInput.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
@@ -37,23 +32,10 @@
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
|
||||
import { loadCopilot } from '$lib/components/copilot/loadCopilot'
|
||||
import {
|
||||
Archive,
|
||||
ArchiveRestore,
|
||||
EllipsisVertical,
|
||||
MessageSquareDashed,
|
||||
Pencil,
|
||||
Plus,
|
||||
Trash2,
|
||||
X
|
||||
} from 'lucide-svelte'
|
||||
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
|
||||
import { Archive, ArchiveRestore, EllipsisVertical, Pencil, Trash2 } from 'lucide-svelte'
|
||||
import SessionChangesBar from './SessionChangesBar.svelte'
|
||||
import SessionShareButton from './SessionShareButton.svelte'
|
||||
import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte'
|
||||
import {
|
||||
composerFocusRequest,
|
||||
createSession,
|
||||
deleteSessionsForWorkspace,
|
||||
getEffectiveWorkspaceId,
|
||||
moveSessionToNewFork,
|
||||
@@ -67,20 +49,19 @@
|
||||
takeSessionAutoSend,
|
||||
reconcileAfterWorkspaceChange,
|
||||
renameSession,
|
||||
selectSession,
|
||||
sessionPageHref,
|
||||
sessionState,
|
||||
setSessionArchived,
|
||||
syncWorkspaceTo,
|
||||
withOpenSessionTeardown
|
||||
withOpenSessionTeardown,
|
||||
type Session,
|
||||
type SessionPreviewTab
|
||||
} from './sessionState.svelte'
|
||||
import { leaveForHome } from './sessionSwitch.svelte'
|
||||
import { getOrCreateRuntime, removeSession } from './sessionRuntime.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { splitterPointerCapture } from '$lib/utils/splitterPointerCapture'
|
||||
import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte'
|
||||
import { AIWorkMode } from '$lib/components/copilot/chat/workMode'
|
||||
import { resolvePreviewTab } from './previewRouter'
|
||||
import { whereIs } from './sessionPreviewTabs.svelte'
|
||||
import type { SessionPreviewTab } from './sessionState.svelte'
|
||||
|
||||
let {
|
||||
sessionId,
|
||||
@@ -111,11 +92,6 @@
|
||||
// through PageHeaderContent, outside the page's tree, once more before the wrapper unmounts.
|
||||
const session = $derived(sessionState.sessions.find((s) => s.id === sessionId) ?? initialSession)
|
||||
|
||||
// Only a session that has never sent opens as the starter block. Read off the record, not
|
||||
// the transcript: a cold session's history is still loading from storage when it mounts,
|
||||
// and an empty transcript would show the greeting and then glide the composer away.
|
||||
// The first send commits the workspace, so this flips only after the transcript has.
|
||||
const opensSession = $derived(!session?.workspace_id)
|
||||
const permissions = useSessionPermissions(
|
||||
() => runtime?.manager.operatingWorkspace,
|
||||
() => runtime?.manager
|
||||
@@ -126,10 +102,11 @@
|
||||
const heldInUse = $derived(!!workModeLock.current || runtime?.manager.workMode === AIWorkMode.USE)
|
||||
// The item an unsent session opened on ("Open in AI session", or a tab opened before the
|
||||
// first send): the chat reads the displayed tab with each message, so the empty chat asks
|
||||
// about that item instead of greeting. What is on screen only: a collapsed panel hides it.
|
||||
// Named as its tab is, so a deployed item in View mode gets its summary from the listing.
|
||||
// about that item. What is on screen only: a collapsed panel hides it. Named as its tab is,
|
||||
// so a deployed item in View mode gets its summary from the listing. The first send commits
|
||||
// the workspace, so an unsent session is one without it.
|
||||
const previewedItem = $derived.by(() => {
|
||||
if (!opensSession) return undefined
|
||||
if (session?.workspace_id) return undefined
|
||||
const tab = runtime?.previewTabs.displayedTab
|
||||
if (!tab) return undefined
|
||||
const slot = resolvePreviewTab(whereIs(tab))
|
||||
@@ -140,11 +117,6 @@
|
||||
name: previewTabName(tab)
|
||||
}
|
||||
})
|
||||
const greets = $derived(opensSession && !previewedItem)
|
||||
const starterPrompts = new StarterPrompts(
|
||||
() => (greets ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined),
|
||||
() => !heldInUse
|
||||
)
|
||||
|
||||
// Seed the composer with the unsent prompt a reload preserved on the session
|
||||
// record (script-init: AIChatInput reads it once at mount).
|
||||
@@ -226,16 +198,11 @@
|
||||
|
||||
let summaryInput: EditableInput | undefined = $state(undefined)
|
||||
|
||||
// Drop the user on a fresh new-session page. Used after archiving or
|
||||
// deleting the open session: the session they were on is no longer
|
||||
// usable, and routing to a sibling would feel arbitrary.
|
||||
async function resetToNewSession() {
|
||||
const fresh = createSession()
|
||||
selectSession(fresh.id)
|
||||
// The page derives the visible session from the `session` query, not
|
||||
// currentSessionId: navigate so the URL leaves the deleted/archived session,
|
||||
// which would otherwise fall through to recovery or stay on the archived one.
|
||||
await goto(sessionPageHref(fresh.id))
|
||||
// After archiving or deleting the open session, Home: the session the user was on
|
||||
// is no longer usable, and routing to a sibling would feel arbitrary. The URL has to
|
||||
// leave it, or the page would fall through to recovery or stay on the archived one.
|
||||
async function leaveRemovedSession() {
|
||||
await leaveForHome()
|
||||
}
|
||||
|
||||
// If the session targets a forked workspace that's still accessible,
|
||||
@@ -286,7 +253,7 @@
|
||||
if (forkToDelete && forkParentId && $workspaceStore === forkToDelete) {
|
||||
syncWorkspaceTo(forkParentId)
|
||||
}
|
||||
await resetToNewSession()
|
||||
await leaveRemovedSession()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -305,7 +272,7 @@
|
||||
sendUserToast(`Failed to archive fork ${forkToArchive}: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}
|
||||
await resetToNewSession()
|
||||
await leaveRemovedSession()
|
||||
}
|
||||
|
||||
// Kept for the "Archive" entry that doesn't go through the confirmation
|
||||
@@ -320,54 +287,16 @@
|
||||
return
|
||||
}
|
||||
setSessionArchived(session.id, true)
|
||||
await resetToNewSession()
|
||||
await leaveRemovedSession()
|
||||
}
|
||||
|
||||
// Workspace bar is shown only before the session sends its first user
|
||||
// message — after that the session's workspace is immutable. The
|
||||
// commit itself happens in `AIChatManager.beforeSend` (wired in
|
||||
// `createRuntime`) so it fires exactly once at send-time. A reactive
|
||||
// commit here would retry forever on backend failures (e.g. fork-id
|
||||
// collision after a previously-successful create whose response was
|
||||
// dropped) — restoration self-heal lives in `initRuntime` instead.
|
||||
const hasFirstUserMessage = $derived(
|
||||
runtime?.manager.displayMessages.some((m) => m.role === 'user') ?? false
|
||||
)
|
||||
|
||||
// Gated on the first message, not on typing: the notice sits directly above a
|
||||
// vertically centred composer, so dropping it mid-sentence would jump the
|
||||
// field out from under the user's cursor.
|
||||
const showRecoveryNotice = $derived(isSessionRecovered(sessionId) && !hasFirstUserMessage)
|
||||
|
||||
// The notice explains one arrival, and the arrival is exactly "this page is
|
||||
// open, on this session, nothing sent yet". Spend the marker the moment any of
|
||||
// those three breaks, so a later return can never replay it — masking it behind
|
||||
// the gate above instead leaves it to resurface. Dismiss is the user's own exit.
|
||||
$effect(() => {
|
||||
if (hasFirstUserMessage || sessionState.currentSessionId !== sessionId) {
|
||||
clearSessionRecovered(sessionId)
|
||||
}
|
||||
})
|
||||
onDestroy(() => clearSessionRecovered(sessionId))
|
||||
|
||||
// Focus the chat input whenever this session is the active one.
|
||||
// The textarea is disabled until copilotInfo loads (otherwise focus is
|
||||
// a silent no-op), so we wait for that too. Triggers on initial mount,
|
||||
// warm-session switch via the picker, and the moment copilot finishes
|
||||
// loading.
|
||||
let aiChat: AIChat | undefined = $state(undefined)
|
||||
let seenFocusNonce = untrack(() => composerFocusRequest.nonce)
|
||||
$effect(() => {
|
||||
// Focus the composer when this session becomes active, or on an explicit
|
||||
// focus request — the latter covers `+` reusing the untouched draft you're
|
||||
// already viewing, where currentSessionId doesn't change so activation alone
|
||||
// wouldn't re-run this.
|
||||
const focusNonce = composerFocusRequest.nonce
|
||||
if (focusNonce !== seenFocusNonce) {
|
||||
// An explicit request overrides the user having left the placeholder before it.
|
||||
seenFocusNonce = focusNonce
|
||||
handoff = undefined
|
||||
}
|
||||
if (sessionState.currentSessionId !== sessionId) {
|
||||
// The user left for another session: coming back is an activation, which focuses.
|
||||
handoff = undefined
|
||||
@@ -438,42 +367,12 @@
|
||||
{#if !session || !runtime}
|
||||
<div class="p-8 text-secondary text-sm">Session not found</div>
|
||||
{:else}
|
||||
<!-- A sent session whose transcript is still loading (or came back empty) shows nothing
|
||||
rather than the docked copilot's keyboard-shortcut hint, which means nothing here. -->
|
||||
{#snippet sessionEmptyHint()}
|
||||
{#if previewedItem}
|
||||
<!-- Holds the composer at the bottom, as in a session under way. -->
|
||||
<div class="flex-1 min-h-0"></div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
<!-- A session with no message yet, or whose transcript is still loading, keeps its composer
|
||||
at the bottom, where it stays once the transcript shows, rather than the docked
|
||||
copilot's keyboard-shortcut hint, which means nothing here. -->
|
||||
{#snippet sessionEmptyHint()}<div class="flex-1 min-h-0"></div>{/snippet}
|
||||
|
||||
{#snippet inputPreface()}
|
||||
{#if showRecoveryNotice}
|
||||
<!-- mb-6, not the banner column's mb-1: at that gap it reads as one more
|
||||
row of composer chrome rather than as a message about the session. -->
|
||||
<!-- Tinted, where the other banners are white: this one has to be spotted
|
||||
without being looked for, above a composer the user is already typing in. -->
|
||||
<!-- Announced: the composer takes focus the moment this appears, so without
|
||||
it a screen reader lands in an empty field with no account of the swap. -->
|
||||
<div role="status" class="{bannerClass} bg-surface-accent-selected mb-6">
|
||||
<div class="flex flex-row items-center gap-2 min-w-0">
|
||||
<MessageSquareDashed class="w-4 h-4 shrink-0 text-accent" />
|
||||
<!-- Names no cause: deleted, another browser, cleared site data and a
|
||||
damaged link are indistinguishable from here. The empty session it
|
||||
landed on is on screen, so the notice doesn't describe it. -->
|
||||
<span class="text-emphasis font-semibold">We couldn't find that session</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
title="Dismiss"
|
||||
aria-label="Dismiss"
|
||||
onclick={() => clearSessionRecovered(sessionId)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- gap-1 (4px) spaces the archived banner and the changes bar when both
|
||||
are visible. Each renders a single in-flow root (or nothing); the diff
|
||||
drawer is position:fixed, so it doesn't count as a flex item — no stray
|
||||
@@ -510,19 +409,14 @@
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet actingOn()}
|
||||
<SessionWorkspaceBar {session} />
|
||||
{/snippet}
|
||||
|
||||
<!-- The left of AIChatDisplay's controls row: the rest arrives with the chat. -->
|
||||
{#snippet placeholderToolbar()}
|
||||
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
|
||||
<Button unifiedSize="2xs" variant="subtle" iconOnly startIcon={{ icon: Plus }} disabled />
|
||||
{@render actingOn()}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<!-- Read by the page header bar, outside this branch, so `session` can be gone here: a delete
|
||||
removes the session while the bar still shows it, on the way to the next page. The
|
||||
section's label below reads it the same way. -->
|
||||
{#snippet sessionHeader()}
|
||||
{#if session}{@render sessionHeaderControls(session)}{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet sessionHeaderControls(session: Session)}
|
||||
<EditableInput
|
||||
bind:this={summaryInput}
|
||||
value={session.summary ?? ''}
|
||||
@@ -594,7 +488,7 @@
|
||||
fork reads like anything else in that fork. -->
|
||||
<PageHeaderContent
|
||||
section={{
|
||||
label: session.summary ?? 'Untitled session',
|
||||
label: session?.summary ?? 'Untitled session',
|
||||
content: sessionHeader,
|
||||
noNavPicker: true
|
||||
}}
|
||||
@@ -626,64 +520,33 @@
|
||||
: session.archived
|
||||
? 'This session is archived. Unarchive it from the banner above to keep working.'
|
||||
: ''}
|
||||
starter={greets
|
||||
? { where: 'session', suggestions: starterPrompts.suggestions }
|
||||
: undefined}
|
||||
emptyHint={sessionEmptyHint}
|
||||
{inputPreface}
|
||||
actingOn={hasFirstUserMessage ? undefined : actingOn}
|
||||
workModeLock={workModeLock.current}
|
||||
/>
|
||||
{:else}
|
||||
<!-- AIChatDisplay's layout, so the composer stays put when the chat replaces it:
|
||||
its transcript area, its column, and its footer row's height; for a session
|
||||
that has never sent, the greeting above the centred composer. -->
|
||||
its transcript area, its column, and its footer row's height. -->
|
||||
<div
|
||||
class="flex flex-col h-full {greets ? 'justify-center' : ''}"
|
||||
class="flex flex-col h-full"
|
||||
{@attach () => () =>
|
||||
runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, false)}
|
||||
>
|
||||
{#if greets}
|
||||
<div class="flex-1 min-h-0 flex flex-col justify-end">
|
||||
<div class="w-full max-w-3xl mx-auto px-7">
|
||||
<SessionGreeting />
|
||||
</div>
|
||||
</div>
|
||||
{:else if previewedItem || runtime.manager.displayMessages.length > 0}
|
||||
<div class="flex-1 min-h-0"></div>
|
||||
{/if}
|
||||
<div class="flex-1 min-h-0"></div>
|
||||
<div class="w-full max-w-3xl mx-auto px-7 pb-2">
|
||||
{@render inputPreface()}
|
||||
<ComposerPlaceholder
|
||||
bind:value={() => draftText, setPlaceholderText}
|
||||
toolbar={greets ? placeholderToolbar : undefined}
|
||||
placeholder={greets
|
||||
? heldInUse
|
||||
? USE_STARTER_PLACEHOLDER
|
||||
: STARTER_PLACEHOLDER
|
||||
: runtime.manager.displayMessages.length > 0
|
||||
? 'Ask followup'
|
||||
: (previewedItemPlaceholder ?? composerPlaceholder)}
|
||||
placeholder={runtime.manager.displayMessages.length > 0
|
||||
? 'Ask followup'
|
||||
: (previewedItemPlaceholder ?? composerPlaceholder)}
|
||||
disabled={isUnavailable || !!session.archived}
|
||||
autofocus={sessionState.currentSessionId === sessionId && !covered}
|
||||
onSelectionChange={(selection) => (handoff = selection ?? null)}
|
||||
onCompositionChange={(composing) => (placeholderComposing = composing)}
|
||||
/>
|
||||
{#if !greets}
|
||||
<div class="mt-1 h-5"></div>
|
||||
{:else if !isUnavailable && !session.archived && starterPrompts.suggestions.length > 0}
|
||||
<div class="pt-2">
|
||||
<ComposerSuggestions
|
||||
suggestions={starterPrompts.suggestions}
|
||||
wrap
|
||||
onPick={setPlaceholderText}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="mt-1 h-5"></div>
|
||||
</div>
|
||||
{#if greets}
|
||||
<div class="flex-1 min-h-0"></div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import { classes as alertClasses, icons as alertIcons } from '$lib/components/common/alert/model'
|
||||
import { clearSessionsBetaOptOut } from '$lib/components/copilot/chat/global/gate'
|
||||
import { activateAiSessions } from './sidebarList.svelte'
|
||||
|
||||
const InfoIcon = alertIcons.info
|
||||
</script>
|
||||
@@ -18,12 +18,6 @@
|
||||
<InfoIcon size={14} class="shrink-0 {alertClasses.info.iconClass}" />
|
||||
<span class="font-medium">Try AI Sessions (beta)</span>
|
||||
<span>·</span>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
onclick={() => clearSessionsBetaOptOut('/sessions')}
|
||||
>
|
||||
Activate
|
||||
</Button>
|
||||
<Button variant="subtle" unifiedSize="xs" onclick={activateAiSessions}>Activate</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -41,8 +41,7 @@
|
||||
// drives the family-root resolution and the "selected" highlight).
|
||||
// Defaults to the active workspace store when not set.
|
||||
selectedId,
|
||||
// A staged-but-not-yet-created fork (e.g. SessionWorkspaceBar's
|
||||
// pre-send draft). Highlighted as the active row when set.
|
||||
// A staged-but-not-yet-created fork. Highlighted as the active row when set.
|
||||
pendingFork,
|
||||
onPick,
|
||||
onCreateFork,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ContextElement } from '$lib/components/copilot/chat/context'
|
||||
import type { BulkKind } from '$lib/components/home/homeSelection.svelte'
|
||||
import type { SessionRuntime } from './sessionRuntime.svelte'
|
||||
|
||||
/** Resolves once the element is in the draft, so several attach in the order given. */
|
||||
type Attach = (element: ContextElement) => Promise<void>
|
||||
@@ -25,7 +26,18 @@ export function itemContextElement(item: {
|
||||
return { type, path: item.path, title: item.path, summary: item.summary, deletable: true }
|
||||
}
|
||||
|
||||
let attach = $state<Attach | undefined>(undefined)
|
||||
type Registration = {
|
||||
/** The draft the composer shows. */
|
||||
sessionId: string
|
||||
attach: Attach
|
||||
focus: () => void
|
||||
/** The box's accent outline, for a composer the user is sent to without it moving. */
|
||||
flash: () => void
|
||||
runtime: SessionRuntime
|
||||
}
|
||||
|
||||
// Raw: the runtime is shared with the session page and must stay the same object there.
|
||||
let registered = $state.raw<Registration | undefined>(undefined)
|
||||
|
||||
/**
|
||||
* The way from anywhere on Home into Home's composer: a row's "Ask AI" hands its item over
|
||||
@@ -34,17 +46,32 @@ let attach = $state<Attach | undefined>(undefined)
|
||||
*/
|
||||
export const homeComposerContext = {
|
||||
get available(): boolean {
|
||||
return attach !== undefined
|
||||
return registered !== undefined
|
||||
},
|
||||
/** The runtime of the draft in Home's composer, whose preview tabs Home's panel shows. Read
|
||||
* from here because Home must not import the runtime's code (it reaches monaco). */
|
||||
get runtime(): SessionRuntime | undefined {
|
||||
return registered?.runtime
|
||||
},
|
||||
async attach(element: ContextElement): Promise<void> {
|
||||
await attach?.(element)
|
||||
await registered?.attach(element)
|
||||
},
|
||||
/** Whether Home's composer is on screen with this draft. */
|
||||
holds(sessionId: string): boolean {
|
||||
return registered?.sessionId === sessionId
|
||||
},
|
||||
focus(): void {
|
||||
registered?.focus()
|
||||
},
|
||||
flash(): void {
|
||||
registered?.flash()
|
||||
},
|
||||
/** Returns the unregister, which only clears its own registration: a remount registers
|
||||
* the new composer before the old one is destroyed. */
|
||||
register(fn: Attach): () => void {
|
||||
attach = fn
|
||||
register(registration: Registration): () => void {
|
||||
registered = registration
|
||||
return () => {
|
||||
if (attach === fn) attach = undefined
|
||||
if (registered === registration) registered = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { composerFocusAfter } from './homeComposerFocus'
|
||||
|
||||
describe('composerFocusAfter', () => {
|
||||
it('hands focus on only for the return from AI Sessions to Home', () => {
|
||||
expect(composerFocusAfter('/sessions', '/', true)).toBe(true)
|
||||
expect(composerFocusAfter('/sessions', '/', false)).toBe(false)
|
||||
// Going to AI Sessions: that page focuses its own composer, so nothing is kept for Home.
|
||||
expect(composerFocusAfter('/', '/sessions', true)).toBe(false)
|
||||
// Any other navigation clears it, so a later arrival on Home never reads a stale flag.
|
||||
expect(composerFocusAfter('/sessions', '/runs', true)).toBe(false)
|
||||
expect(composerFocusAfter('/runs', '/', true)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { OnNavigate } from '@sveltejs/kit'
|
||||
|
||||
// Leaving AI Sessions for Home with the composer focused hands that focus on to Home's
|
||||
// composer, so typing carries on across the move.
|
||||
|
||||
const HOME = '/'
|
||||
const SESSIONS = '/sessions'
|
||||
|
||||
/** Whether the composer had focus when the user left AI Sessions for Home. */
|
||||
let composerFocused = false
|
||||
|
||||
/** The focus flag to keep after a navigation from `from` to `to`. Only the return to Home
|
||||
* hands focus on — the sessions page focuses its composer on its own — and every other
|
||||
* navigation clears the flag, so a later arrival on Home never acts on a stale one. */
|
||||
export function composerFocusAfter(
|
||||
from: string | undefined,
|
||||
to: string | undefined,
|
||||
composerHadFocus: boolean
|
||||
): boolean {
|
||||
return from === SESSIONS && to === HOME && composerHadFocus
|
||||
}
|
||||
|
||||
/** Whether Home should give its composer the focus the sessions page's had. Read once:
|
||||
* a later visit starts unfocused. */
|
||||
export function takeComposerFocus(): boolean {
|
||||
const focused = composerFocused
|
||||
composerFocused = false
|
||||
return focused
|
||||
}
|
||||
|
||||
/** For SvelteKit's `onNavigate`: records whether the composer had focus as the page left. */
|
||||
export function recordComposerFocus(navigation: OnNavigate): void {
|
||||
composerFocused = composerFocusAfter(
|
||||
navigation.from?.url.pathname,
|
||||
navigation.to?.url.pathname,
|
||||
document.activeElement?.closest('[data-session-composer]') != null
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { getContext, onDestroy, setContext } from 'svelte'
|
||||
import { getContext, setContext } from 'svelte'
|
||||
import type { OpenInSessionSource } from './OpenInSessionButton.svelte'
|
||||
import type { SessionTarget } from './sessionState.svelte'
|
||||
|
||||
// The "Open in AI session" hand-off, published by the component that owns the
|
||||
// item being edited (FlowBuilder, RawAppEditor) for AI entry points too deep in
|
||||
@@ -15,40 +14,10 @@ export type OpenInSessionHandoff = {
|
||||
source: (opts?: { moduleId?: string }) => OpenInSessionSource | undefined
|
||||
}
|
||||
|
||||
// The hand-offs of every editor currently mounted. The navigation rail's "AI
|
||||
// Sessions" switch sits above every page, out of reach of the context, and
|
||||
// looks the editor of the item it is leaving up here instead.
|
||||
const mounted = new Set<OpenInSessionHandoff>()
|
||||
|
||||
export function setOpenInSessionHandoff(handoff: OpenInSessionHandoff): void {
|
||||
setContext(KEY, handoff)
|
||||
onDestroy(registerMountedOpenInSessionHandoff(handoff))
|
||||
}
|
||||
|
||||
/** Count `handoff` as mounted until the returned unregister runs. Split from
|
||||
* setOpenInSessionHandoff so the registry can be driven outside a component. */
|
||||
export function registerMountedOpenInSessionHandoff(handoff: OpenInSessionHandoff): () => void {
|
||||
mounted.add(handoff)
|
||||
return () => {
|
||||
mounted.delete(handoff)
|
||||
}
|
||||
}
|
||||
|
||||
export function getOpenInSessionHandoff(): OpenInSessionHandoff | undefined {
|
||||
return getContext<OpenInSessionHandoff | undefined>(KEY)
|
||||
}
|
||||
|
||||
/** The mounted editor's hand-off for `target`, or undefined when no editor on
|
||||
* screen publishes one for it (a detail page). Matched on the item rather than
|
||||
* taken as "the latest registered": a script editor mounted in a flow's drawer
|
||||
* registers too, and the rail wants the page's own item. */
|
||||
export function findMountedOpenInSessionSource(
|
||||
target: SessionTarget
|
||||
): OpenInSessionSource | undefined {
|
||||
for (const handoff of mounted) {
|
||||
const source = handoff.source()
|
||||
const t = source?.target
|
||||
if (t && t.kind === target.kind && t.path === target.path) return source
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { WorkspaceItem } from '$lib/components/workspacePicker'
|
||||
import { barePath, isPreviewListPath } from './previewPaths'
|
||||
import { previewLocationLabel } from './previewRouter'
|
||||
import type { SessionPreviewTabs } from './sessionPreviewTabs.svelte'
|
||||
|
||||
/**
|
||||
* A preview frame hands some navigations up rather than making them itself (the logged
|
||||
* layout's beforeNavigate); applied here to the panel showing that frame, `owner`.
|
||||
*/
|
||||
export function onPreviewFrameMessage(e: MessageEvent, owner: SessionPreviewTabs | undefined) {
|
||||
if (e.origin !== window.location.origin) return
|
||||
const d = e.data
|
||||
if (!d) return
|
||||
// A preview frame navigating to an editor route: re-point the active tab to the live
|
||||
// in-process editor instead of booting a second one in the frame.
|
||||
if (d.type === 'wm.session.openEditor') {
|
||||
if (d.kind !== 'script' && d.kind !== 'flow' && d.kind !== 'raw_app') return
|
||||
if (typeof d.path !== 'string') return
|
||||
const item: WorkspaceItem =
|
||||
d.kind === 'raw_app'
|
||||
? { kind: 'app', raw_app: true, path: d.path, summary: '' }
|
||||
: { kind: d.kind, path: d.path, summary: '' }
|
||||
owner?.navigate({ type: 'item', item })
|
||||
return
|
||||
}
|
||||
// A preview frame navigating to a list page: re-point the active tab to the list mounted in
|
||||
// process, whose rows open as tabs of their own.
|
||||
if (d.type === 'wm.session.openList') {
|
||||
if (typeof d.href !== 'string' || !isPreviewListPath(barePath(d.href))) return
|
||||
owner?.navigate({ type: 'page', href: d.href, label: previewLocationLabel(d.href) })
|
||||
return
|
||||
}
|
||||
// A job clicked inside a preview tab: open the run detail in a NEW tab so the originating
|
||||
// page (e.g. Runs) stays put. open() focuses an existing tab for the same run rather than
|
||||
// duplicating it.
|
||||
if (d.type === 'wm.session.openRun') {
|
||||
if (typeof d.href !== 'string') return
|
||||
owner?.open({
|
||||
type: 'page',
|
||||
href: d.href,
|
||||
label: typeof d.label === 'string' ? d.label : 'Run'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { SvelteSet } from 'svelte/reactivity'
|
||||
|
||||
// Session ids opened as a stand-in for a `session` URL this browser doesn't
|
||||
// hold. Kept in memory rather than on the Session record: persisted, the notice
|
||||
// would replay on every reload of a session the user has since made their own.
|
||||
const recovered = new SvelteSet<string>()
|
||||
|
||||
export function markSessionRecovered(id: string): void {
|
||||
recovered.add(id)
|
||||
}
|
||||
|
||||
export function isSessionRecovered(id: string): boolean {
|
||||
return recovered.has(id)
|
||||
}
|
||||
|
||||
export function clearSessionRecovered(id: string): void {
|
||||
recovered.delete(id)
|
||||
}
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
setSessionPreviewSize,
|
||||
setSessionTabs,
|
||||
setDraftsDiscardedHandler,
|
||||
setSendUnderWayCheck,
|
||||
setSessionWorkMode,
|
||||
type Session
|
||||
} from './sessionState.svelte'
|
||||
@@ -130,7 +131,6 @@ import {
|
||||
} from '$lib/components/copilot/chat/shared'
|
||||
import { readStoredChat } from '$lib/components/copilot/chat/HistoryManager.svelte'
|
||||
import { getCurrentUserEmail } from '$lib/userScopedStorage'
|
||||
import { navRouteItemMoved } from './sessionSwitch.svelte'
|
||||
import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
|
||||
|
||||
// Per-kind load state for a session's editor target. Pure state container the
|
||||
@@ -1222,7 +1222,6 @@ function createRuntime(session: Session): SessionRuntime {
|
||||
UserDraft.stopSync(kind, storagePath, { workspace })
|
||||
UserDraft.discard(kind, storagePath, undefined, { workspace })
|
||||
previewTabs.retargetEditor({ kind, path: storagePath }, { kind, path: deployedPath })
|
||||
navRouteItemMoved(kind === 'raw_app' ? 'app' : kind, workspace, storagePath, deployedPath)
|
||||
}
|
||||
const path = deployedPath
|
||||
// After deploy the editor state equals the deployed value; the reload
|
||||
@@ -1497,6 +1496,9 @@ export function resetSessionPreviewTabs(sessionId: string, seedUrl: string): voi
|
||||
const rt = runtimes.get(sessionId)
|
||||
if (rt) {
|
||||
rt.previewTabs.reset(tabs, 'session')
|
||||
// Written to the record now, not after the owner's debounce: the sessions page judges
|
||||
// the arrival by the record's tabs, and a draft without any opens on Home instead.
|
||||
rt.previewTabs.flushNow()
|
||||
} else {
|
||||
setSessionTabs(sessionId, tabs, 'session')
|
||||
setSessionPreviewCollapsed(sessionId, false)
|
||||
@@ -1523,6 +1525,10 @@ export function removeSession(sessionId: string): void {
|
||||
}
|
||||
|
||||
setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime))
|
||||
setSendUnderWayCheck((id) => {
|
||||
const m = runtimes.get(id)?.manager
|
||||
return !!m && (m.loading || m.sendInFlight || m.sendPending)
|
||||
})
|
||||
|
||||
// The chat calls a new item by its chosen name while its draft is stored at
|
||||
// `draft_<uuid>`; resolve the name the way the chat's write tools do.
|
||||
|
||||
@@ -16,7 +16,6 @@ import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { isReadOnlySessionWorkspace } from '../copilot/chat/global/sessionAccess'
|
||||
import { AIWorkMode } from '../copilot/chat/workMode'
|
||||
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'
|
||||
@@ -90,18 +89,15 @@ 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
|
||||
// Home's draft: it acts on whatever workspace Home shows, so a switch made on another page
|
||||
// moves it on Home's next mount. Cleared by a pick made on the session page, whose picker
|
||||
// leaves the navigation workspace where it is.
|
||||
followsHome?: boolean
|
||||
// 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.
|
||||
workspace_root_id?: string
|
||||
@@ -1049,9 +1045,25 @@ 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
|
||||
flash: boolean
|
||||
}>({
|
||||
id: undefined,
|
||||
requests: 0,
|
||||
focus: false,
|
||||
flash: 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
|
||||
@@ -1059,78 +1071,89 @@ 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. A draft already sending stays
|
||||
// too: its send commits the workspace it started in, but only after the pre-flight.
|
||||
// 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 || sendUnderWay(s.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`, whether its composer takes focus as it mounts, and whether it then
|
||||
* plays its accent outline. */
|
||||
export function showOnHome(id: string, opts?: { focus?: boolean; flash?: boolean }): void {
|
||||
homeDraft.id = id
|
||||
homeDraft.focus = opts?.focus ?? false
|
||||
homeDraft.flash = opts?.flash ?? 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
|
||||
}
|
||||
|
||||
/** Whether Home's composer should play its accent outline now that it is on screen. Read once. */
|
||||
export function takeHomeDraftFlash(): boolean {
|
||||
const flash = homeDraft.flash
|
||||
homeDraft.flash = false
|
||||
return flash
|
||||
}
|
||||
|
||||
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.
|
||||
// An `untilStarted` session is not blank: reused it would reopen its item, and dropped
|
||||
// while on screen it would leave the page showing a session that is gone.
|
||||
function isDiscardableDraft(s: Session): boolean {
|
||||
return !!s.transient && s.draftPrompt === undefined && !s.untilStarted
|
||||
}
|
||||
|
||||
// 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.untilStarted &&
|
||||
!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) {
|
||||
// It may be Home's draft; asked for here, it is the session page's now, and callers
|
||||
// park it on a workspace of their own that Home must not move it off.
|
||||
delete reusable.followsHome
|
||||
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()
|
||||
// The blank may be the one Home holds. The hand-off gives it an item and a workspace of its
|
||||
// own, so Home lets go of it: Home would otherwise show it, and move it with the header.
|
||||
if (homeDraft.id === session.id) homeDraft.id = undefined
|
||||
sessionState.currentSessionId = session.id
|
||||
return session
|
||||
}
|
||||
@@ -1144,6 +1167,14 @@ export function setDraftsDiscardedHandler(handler: (ids: string[]) => void): voi
|
||||
onDraftsDiscarded = handler
|
||||
}
|
||||
|
||||
// Whether a session's turn is under way, set by sessionRuntime the same way. A send commits
|
||||
// the workspace only once its pre-flight is through (the chat's ready gate, the attached files'
|
||||
// upkeep), so until then a draft whose first turn has started still reads as unsent.
|
||||
let sendUnderWay: (id: string) => boolean = () => false
|
||||
export function setSendUnderWayCheck(check: (id: string) => boolean): void {
|
||||
sendUnderWay = check
|
||||
}
|
||||
|
||||
function newTransientSession(): Session {
|
||||
const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id)
|
||||
sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s))
|
||||
@@ -1170,34 +1201,36 @@ 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, and one the session page picked onto
|
||||
* another workspace of the family is about that workspace: Home acts on the workspace it
|
||||
* shows, so it starts its own instead of moving either. */
|
||||
/** Whether a session opens in Home's composer rather than on a page of its own: unsent, not
|
||||
* archived (its page holds the way back), and neither about an item (it carries preview tabs,
|
||||
* which need the session page's panel), armed to send itself on arrival, nor already sending. */
|
||||
export function opensOnHome(s: Session): boolean {
|
||||
return (
|
||||
!s.workspace_id &&
|
||||
!s.archived &&
|
||||
!s.previewTabs?.length &&
|
||||
!autoSendIsFresh(s) &&
|
||||
!sendUnderWay(s.id)
|
||||
)
|
||||
}
|
||||
|
||||
/** 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 homeWs = get(workspaceStore)
|
||||
const homes = (s: Session) =>
|
||||
(s.followsHome || s.pending_workspace_id === homeWs) && sessionInCurrentFamily(s)
|
||||
const unsent = (s: Session) =>
|
||||
!s.archived && !s.workspace_id && !s.previewTabs?.length && homes(s)
|
||||
const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId)
|
||||
// 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) => 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]
|
||||
const draft =
|
||||
(current && unsent(current) ? current : undefined) ??
|
||||
touched ??
|
||||
sessionState.sessions.find((s) => isDiscardableDraft(s) && homes(s)) ??
|
||||
newTransientSession()
|
||||
if (!draft.followsHome) {
|
||||
draft.followsHome = true
|
||||
if (!draft.transient) void putSession(draft)
|
||||
}
|
||||
return draft
|
||||
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()
|
||||
}
|
||||
|
||||
// Promote an in-memory transient session to a persisted IndexedDB record.
|
||||
@@ -1222,13 +1255,6 @@ export function setSessionPendingWorkspace(id: string, workspace_id: string) {
|
||||
if (changed) persistTouched(s)
|
||||
}
|
||||
|
||||
export function stopFollowingHome(id: string) {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
if (!s?.followsHome) return
|
||||
delete s.followsHome
|
||||
if (!s.transient) void putSession(s)
|
||||
}
|
||||
|
||||
// Keep a just-created session in memory until the user starts it (see `untilStarted`).
|
||||
export function holdSessionUntilStarted(id: string) {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
@@ -1246,16 +1272,6 @@ export function setNewSessionWorkspace(id: string, workspace_id: string) {
|
||||
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
|
||||
|
||||
@@ -3,30 +3,28 @@ import { get } from 'svelte/store'
|
||||
import {
|
||||
commitSessionWorkspace,
|
||||
createSession,
|
||||
setNewSessionWorkspace,
|
||||
decideSessionLifecycle,
|
||||
findEmptyLandingSession,
|
||||
getSessionDraftAttachments,
|
||||
holdHomeDraft,
|
||||
holdSessionUntilStarted,
|
||||
homeDraft,
|
||||
homeStarterSession,
|
||||
isForkSession,
|
||||
isTearingDownOpenSession,
|
||||
opensOnHome,
|
||||
renameSession,
|
||||
setDraftsDiscardedHandler,
|
||||
sessionInCurrentFamily,
|
||||
setGeneratedSessionSummary,
|
||||
setSessionDraftAttachments,
|
||||
setSessionDraftPrompt,
|
||||
setSendUnderWayCheck,
|
||||
setSessionPendingWorkspace,
|
||||
setSessionTabs,
|
||||
sessionState,
|
||||
withOpenSessionTeardown,
|
||||
type Session
|
||||
} from './sessionState.svelte'
|
||||
import {
|
||||
clearSessionRecovered,
|
||||
isSessionRecovered,
|
||||
markSessionRecovered
|
||||
} from './sessionRecoveryNotice.svelte'
|
||||
import {
|
||||
enterpriseLicense,
|
||||
usersWorkspaceStore,
|
||||
@@ -521,28 +519,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
|
||||
@@ -670,59 +646,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
|
||||
@@ -745,12 +668,26 @@ describe('withOpenSessionTeardown — the gate that holds recovery off during a
|
||||
})
|
||||
})
|
||||
|
||||
describe('opensOnHome', () => {
|
||||
it('leaves an archived draft, and one whose first turn has started, to their own page', () => {
|
||||
const draft = session({ id: 'typed-draft', draftPrompt: 'hi' })
|
||||
expect(opensOnHome(draft)).toBe(true)
|
||||
expect(opensOnHome({ ...draft, archived: true })).toBe(false)
|
||||
setSendUnderWayCheck((id) => id === 'typed-draft')
|
||||
try {
|
||||
expect(opensOnHome(draft)).toBe(false)
|
||||
} finally {
|
||||
setSendUnderWayCheck(() => false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('homeStarterSession', () => {
|
||||
it("shows the family's stored draft, not the conversation in view, and selects nothing", () => {
|
||||
const restore = withTwoFamilies('forkA')
|
||||
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',
|
||||
@@ -762,7 +699,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(
|
||||
@@ -773,56 +710,67 @@ describe('homeStarterSession', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves a draft picked onto another workspace of the family to that workspace', () => {
|
||||
const restore = withTwoFamilies('rootA')
|
||||
const prevCurrent = sessionState.currentSessionId
|
||||
const picked = session({ id: 'picked-fork-draft', pending_workspace_id: 'forkA' })
|
||||
sessionState.sessions.push(picked)
|
||||
sessionState.currentSessionId = 'picked-fork-draft'
|
||||
let createdId: string | undefined
|
||||
try {
|
||||
createdId = homeStarterSession().id
|
||||
expect(createdId).not.toBe('picked-fork-draft')
|
||||
expect(picked.pending_workspace_id).toBe('forkA')
|
||||
} finally {
|
||||
sessionState.sessions = sessionState.sessions.filter(
|
||||
(s) => !['picked-fork-draft', createdId].includes(s.id)
|
||||
)
|
||||
sessionState.currentSessionId = prevCurrent
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps its own draft when the workspace was switched on another page', () => {
|
||||
it('keeps the draft Home holds, acting on the header workspace within its family only', () => {
|
||||
const restore = withTwoFamilies('forkA')
|
||||
const typed = session({
|
||||
id: 'home-draft',
|
||||
pending_workspace_id: 'rootA',
|
||||
draftPrompt: 'typed on Home',
|
||||
followsHome: true
|
||||
})
|
||||
sessionState.sessions.push(typed)
|
||||
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 {
|
||||
expect(homeStarterSession().id).toBe('home-draft')
|
||||
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 {
|
||||
sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'home-draft')
|
||||
homeDraft.id = undefined
|
||||
sessionState.sessions = sessionState.sessions.filter(
|
||||
(s) => !['recent-draft', 'held-draft'].includes(s.id)
|
||||
)
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
it('lets go of its draft once the session page reuses it for a new session', () => {
|
||||
it('keeps a draft whose first send is under way in the workspace it was sent from', () => {
|
||||
const restore = withTwoFamilies('forkA')
|
||||
sessionState.sessions.push(session({ id: 'sending-draft', pending_workspace_id: 'forkA' }))
|
||||
const sendingNow = () => sessionState.sessions.find((s) => s.id === 'sending-draft')
|
||||
try {
|
||||
holdHomeDraft('sending-draft')
|
||||
setSendUnderWayCheck((id) => id === 'sending-draft')
|
||||
workspaceStore.set('rootA')
|
||||
holdHomeDraft('sending-draft')
|
||||
expect(sendingNow()?.pending_workspace_id).toBe('forkA')
|
||||
} finally {
|
||||
setSendUnderWayCheck(() => false)
|
||||
homeDraft.id = undefined
|
||||
sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'sending-draft')
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
it('lets go of its blank once a hand-off reuses it for an item', () => {
|
||||
const restore = withTwoFamilies('forkA')
|
||||
const prevCurrent = sessionState.currentSessionId
|
||||
const ids: string[] = []
|
||||
try {
|
||||
ids.push(homeStarterSession().id)
|
||||
holdHomeDraft(ids[0])
|
||||
const reused = createSession()
|
||||
expect(reused.id).toBe(ids[0])
|
||||
setNewSessionWorkspace(reused.id, 'rootA')
|
||||
setSessionPendingWorkspace(reused.id, 'rootA')
|
||||
reused.previewTabs = [{ id: 'tab', url: '/flows/edit/f/x', loc: '/flows/edit/f/x' }]
|
||||
// The item opens on the session page, and Home starts a draft of its own.
|
||||
expect(opensOnHome(reused)).toBe(false)
|
||||
ids.push(homeStarterSession().id)
|
||||
expect(ids[1]).not.toBe(ids[0])
|
||||
expect(reused.pending_workspace_id).toBe('rootA')
|
||||
} finally {
|
||||
homeDraft.id = undefined
|
||||
sessionState.sessions = sessionState.sessions.filter((s) => !ids.includes(s.id))
|
||||
sessionState.currentSessionId = prevCurrent
|
||||
restore()
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { get } from 'svelte/store'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { DraftService } from '$lib/gen'
|
||||
import {
|
||||
blankHomeDraft,
|
||||
createSession,
|
||||
holdSessionUntilStarted,
|
||||
homeDraft,
|
||||
opensOnHome,
|
||||
selectSession,
|
||||
sessionPageHref,
|
||||
sessionInCurrentFamily,
|
||||
sessionLastActivityAt,
|
||||
sessionPageHref,
|
||||
sessionState,
|
||||
setSessionAutoSend,
|
||||
setSessionDraftPrompt,
|
||||
setNewSessionWorkspace,
|
||||
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 { fixupUrlAfterWorkspaceSwitch } from '../sidebar/workspaceSwitchUrl'
|
||||
import { pinHomeComposer } from '../home/homeComposerPin.svelte'
|
||||
import { homeComposerContext } from './homeComposerContext.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'
|
||||
@@ -35,197 +40,96 @@ type SeedOpts = {
|
||||
untilStarted?: boolean
|
||||
}
|
||||
|
||||
// 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 session last opened, on its page or in Home's composer. Plain module state: a
|
||||
// reload forgets it, and the family's most recently used session stands in.
|
||||
let lastSessionId: string | undefined
|
||||
|
||||
// The 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
|
||||
|
||||
export function rememberNavRoute(pathnameWithSearch: string): void {
|
||||
lastNavRoute = pathnameWithSearch
|
||||
navRouteOffered = false
|
||||
}
|
||||
|
||||
/**
|
||||
* A deploy from the session moved an item from `fromPath` (a new item's `draft_<uuid>` row) to
|
||||
* `toPath`. When the remembered route is that item's editor, point it at the new path: the old one
|
||||
* no longer exists, so leaving session mode would open an editor that cannot load it.
|
||||
*/
|
||||
export function navRouteItemMoved(
|
||||
kind: 'flow' | 'script' | 'app',
|
||||
workspace: string,
|
||||
fromPath: string,
|
||||
toPath: string
|
||||
): void {
|
||||
if (fromPath === toPath) return
|
||||
const route = parsePreviewItemRoute(lastNavRoute)
|
||||
if (route?.kind !== kind || route.itemPath !== fromPath) return
|
||||
const [pathname, query] = lastNavRoute.split('?')
|
||||
if (!pathname.endsWith(`/${fromPath}`)) return
|
||||
// A session may deploy to a fork of the workspace the route is on, where the same path names
|
||||
// another item: only a move in the route's own workspace is this item's.
|
||||
const routeWorkspace = (query && new URLSearchParams(query).get('workspace')) || undefined
|
||||
if ((routeWorkspace ?? get(workspaceStore)) !== workspace) return
|
||||
const prefix = pathname.slice(0, pathname.length - fromPath.length)
|
||||
// The flags a new item's editor carries (`new_draft`, `nodraft`) describe the draft, not the
|
||||
// deployed item: keep only the workspace.
|
||||
lastNavRoute =
|
||||
prefix + toPath + (routeWorkspace ? `?workspace=${encodeURIComponent(routeWorkspace)}` : '')
|
||||
}
|
||||
|
||||
/** 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: a session's page records the session, for the sessions
|
||||
* page to resume when it is opened without one. */
|
||||
export function noteArrival(url: URL): void {
|
||||
if (url.pathname.startsWith('/sessions')) {
|
||||
lastSessionId = url.searchParams.get('session') ?? lastSessionId
|
||||
}
|
||||
}
|
||||
|
||||
// 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 session entering session mode resumes: the active one if selected, else
|
||||
// the most recent non-archived one. Scoped to the active workspace family:
|
||||
// reviving a session from another family would pull that family's scope
|
||||
// (sidebar list, "Acting on" workspace) into the one the user is actually in.
|
||||
// The session last opened, else the family's most recently used one. Scoped to the
|
||||
// family: reviving another family's session would pull its scope into this one.
|
||||
function resumableSession(): Session | undefined {
|
||||
const current = sessionState.currentSessionId
|
||||
? sessionState.sessions.find((s) => s.id === sessionState.currentSessionId)
|
||||
: undefined
|
||||
return (
|
||||
(current && sessionInCurrentFamily(current) ? current : undefined) ??
|
||||
sessionState.sessions.find((s) => !s.archived && sessionInCurrentFamily(s))
|
||||
)
|
||||
const usable = (s: Session) => !s.archived && sessionInCurrentFamily(s)
|
||||
const last = sessionState.sessions.find((s) => s.id === lastSessionId)
|
||||
if (last && usable(last)) return last
|
||||
return sessionState.sessions
|
||||
.filter((s) => usable(s) && !s.transient)
|
||||
.sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0]
|
||||
}
|
||||
|
||||
// Enter session mode: resume the session `resumableSession` picks, else spin up
|
||||
// a fresh one — then route to it.
|
||||
// `replace` swaps the current history entry instead of pushing — for the
|
||||
// sessions page's family reconcile, where Back must not return to the
|
||||
// redirected-away URL just to bounce here again.
|
||||
export async function enterSessionMode(opts?: { replace?: boolean }): Promise<void> {
|
||||
const target = resumableSession() ?? createSession()
|
||||
selectSession(target.id)
|
||||
await goto(sessionPageHref(target.id), {
|
||||
replaceState: opts?.replace ?? false
|
||||
})
|
||||
}
|
||||
|
||||
// How long the resumable session may have sat idle before entering from an item
|
||||
// editor starts a session on that item instead. Long enough that stepping out to
|
||||
// the editor in the middle of a conversation comes back to the same chat; short
|
||||
// enough that a session left since the previous day is not taken for the task
|
||||
// the user is now on.
|
||||
const RESUME_IDLE_LIMIT_MS = 60 * 60 * 1000
|
||||
|
||||
// Enter session mode from the navigation rail. Coming from an item editor with
|
||||
// no session to resume, or one idle past RESUME_IDLE_LIMIT_MS, opens a fresh
|
||||
// session on that item straight away: a session that old is rarely what a visit
|
||||
// from a flow or app is about, and landing in it would only lead to "New
|
||||
// session" and the offer takeNewSessionSeed makes. Anything else resumes as
|
||||
// enterSessionMode does. Rejects when the editor could not persist its draft,
|
||||
// so the caller can stay on the page and say so.
|
||||
export async function enterSessionModeFromNav(): Promise<void> {
|
||||
const edited = editedAt(lastNavRoute)
|
||||
if (edited) {
|
||||
const resumable = resumableSession()
|
||||
if (!resumable || Date.now() - sessionLastActivityAt(resumable) > RESUME_IDLE_LIMIT_MS) {
|
||||
// The editor's own hand-off is what its "Open in AI session" button uses:
|
||||
// it persists the draft the preview loads (an edit still inside the
|
||||
// autosave debounce, the row of a never-saved new item) and names the
|
||||
// workspace the item lives in. Only an item with no such editor on
|
||||
// screen (a legacy app, a detail page) is opened by route, as last
|
||||
// persisted, in the workspace the route was scoped to.
|
||||
const source = edited.target && findMountedOpenInSessionSource(edited.target)
|
||||
if (source) await openSourceInSession(source)
|
||||
else await openPageInSession(lastNavRoute, workspaceParamOf(lastNavRoute))
|
||||
return
|
||||
}
|
||||
/** The sessions page opened on no session of this family: the session to resume on its
|
||||
* page, or in Home's composer for an unsent draft, else a blank draft there. `replace` for
|
||||
* the sessions page's own redirects, where Back must not return to the URL that bounced
|
||||
* here. */
|
||||
export async function resumeAiSessions(opts?: { replace?: boolean }): Promise<void> {
|
||||
const session = resumableSession()
|
||||
if (!session || opensOnHome(session)) {
|
||||
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
|
||||
}
|
||||
|
||||
// Exit session mode: back to the last navigation route (home as a fallback).
|
||||
export async function exitSessionMode(): Promise<void> {
|
||||
let target = lastNavRoute || '/'
|
||||
// The remembered route can carry a stale `?workspace=` — the layout's
|
||||
// onQueryChange re-applies that param, so restoring the route would
|
||||
// silently check the app back out to a workspace the user has since
|
||||
// left. The rest of the route is scoped to that stale workspace too,
|
||||
// so fall back to home rather than rewriting the param.
|
||||
const wsParam = /[?&]workspace=([^&]*)/.exec(target)?.[1]
|
||||
const ws = get(workspaceStore)
|
||||
if (ws && wsParam && decodeURIComponent(wsParam) !== ws) {
|
||||
target = '/'
|
||||
} else if (ws && !(await newItemDraftStillThere(target, ws))) {
|
||||
target = '/'
|
||||
// A plain session starts on Home, and an unsent draft is shown there rather than on a
|
||||
// page of its own. Asking for one puts the composer back on Home if the reader had
|
||||
// unpinned it: there is nowhere else to type it.
|
||||
async function toHome(id: string, opts?: { replace?: boolean; flash?: boolean }): Promise<void> {
|
||||
lastSessionId = id
|
||||
pinHomeComposer()
|
||||
const onHome = typeof window !== 'undefined' && window.location.pathname === '/'
|
||||
// The draft already on screen is focused where it is: rebuilding the composer would fold it
|
||||
// to one line and open it again under the user's eyes.
|
||||
if (onHome && homeComposerContext.holds(id)) {
|
||||
homeComposerContext.focus()
|
||||
if (opts?.flash) homeComposerContext.flash()
|
||||
return
|
||||
}
|
||||
await goto(target)
|
||||
showOnHome(id, { focus: true, flash: opts?.flash })
|
||||
// `goto` has no same-URL short-circuit, so navigating from Home would push a
|
||||
// duplicate history entry; showOnHome already remounts the composer there.
|
||||
if (onHome) return
|
||||
await goto('/', { replaceState: opts?.replace ?? false })
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an editor route on a never-deployed item still has the draft it edits. Such an item
|
||||
* lives only as its `draft_<uuid>` row, which a first deploy discards; `navRouteItemMoved`
|
||||
* follows the deploys this window's session sees, but a low-code app deploys inside its preview
|
||||
* frame, out of sight. Any other route counts as there.
|
||||
*/
|
||||
async function newItemDraftStillThere(url: string, workspace: string): Promise<boolean> {
|
||||
const route = parsePreviewItemRoute(url)
|
||||
if (route?.mode !== 'edit' || !NEW_ITEM_DRAFT_RE.test(route.itemPath.split('/').pop() ?? '')) {
|
||||
return true
|
||||
}
|
||||
const kind = route.kind === 'app' ? (route.raw_app ? 'raw_app' : 'app') : route.kind
|
||||
try {
|
||||
return !!(await DraftService.getOwnDraft({ workspace, kind, path: route.itemPath }))
|
||||
} catch {
|
||||
return true
|
||||
/** New session: Home's composer, blank, focused and outlined for a moment. It acts on the
|
||||
* header's workspace, switched to `workspaceId` first when given. A draft already typed stays
|
||||
* in the list. */
|
||||
export async function openNewSession(workspaceId?: string): Promise<void> {
|
||||
if (workspaceId && workspaceId !== get(workspaceStore)) {
|
||||
// Home's current draft stays where it is: the switch must not take it along.
|
||||
homeDraft.id = undefined
|
||||
syncWorkspaceTo(workspaceId)
|
||||
// Home may be open already, under a URL naming the workspace just left: a reload would
|
||||
// switch back to it and take the new draft along.
|
||||
await fixupUrlAfterWorkspaceSwitch(workspaceId)
|
||||
}
|
||||
await toHome(blankHomeDraft().id, { flash: true })
|
||||
}
|
||||
|
||||
const NEW_ITEM_DRAFT_RE = /^draft_[0-9a-f_]+$/
|
||||
/** An unsent draft, opened in Home's composer. `replace` for a redirect off the sessions
|
||||
* page, where Back must not return to the URL that bounced here. */
|
||||
export async function openDraftOnHome(id: string, opts?: { replace?: boolean }): Promise<void> {
|
||||
await toHome(id, opts)
|
||||
}
|
||||
|
||||
/** Where to go once the session on screen is gone (archived, deleted, not in this browser):
|
||||
* Home, showing whichever draft it would pick anyway. */
|
||||
export async function leaveForHome(opts?: { replace?: boolean }): Promise<void> {
|
||||
homeDraft.id = undefined
|
||||
homeDraft.requests++
|
||||
if (typeof window !== 'undefined' && window.location.pathname === '/') return
|
||||
await goto('/', { replaceState: opts?.replace ?? false })
|
||||
}
|
||||
|
||||
// Open a fresh AI session showing an editor (flow/script/raw_app) in its preview,
|
||||
// then route into session mode. The preview loads the item from its live draft,
|
||||
// then route to its page. The preview loads the item from its live draft,
|
||||
// so the caller MUST persist any unsaved edits first (e.g. save a draft) for the
|
||||
// preview to reflect the live state. `workspaceId` scopes the session to the
|
||||
// editor's workspace (instead of createSession's root default) so it opens the
|
||||
@@ -296,9 +200,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)
|
||||
@@ -334,16 +235,13 @@ 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. `workspace` is the way
|
||||
// out of a read-only session, whose workspace is fixed once it has started.
|
||||
// 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; workspace?: string }
|
||||
opts?: { autoSend?: boolean }
|
||||
): Promise<void> {
|
||||
const session = createSession()
|
||||
if (opts?.workspace) setSessionPendingWorkspace(session.id, opts.workspace)
|
||||
setSessionDraftPrompt(session.id, prompt)
|
||||
// An empty prompt has nothing to send; leave the composer focused instead.
|
||||
if (opts?.autoSend && prompt.trim()) setSessionAutoSend(session.id)
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { get } from 'svelte/store'
|
||||
import {
|
||||
enterSessionMode,
|
||||
enterSessionModeFromNav,
|
||||
exitSessionMode,
|
||||
navRouteItemMoved,
|
||||
noteArrival,
|
||||
openSourceInSession,
|
||||
rememberNavRoute,
|
||||
startSessionWithPrompt,
|
||||
takeNewSessionSeed
|
||||
resumeAiSessions,
|
||||
startSessionWithPrompt
|
||||
} from './sessionSwitch.svelte'
|
||||
import {
|
||||
getSessionAutoSendDomElement,
|
||||
homeDraft,
|
||||
peekSessionAutoSend,
|
||||
sessionState,
|
||||
takeSessionAutoSend,
|
||||
@@ -27,96 +24,78 @@ import { goto } from '$lib/navigation'
|
||||
// monaco (hence that import being dynamic in the first place) and cannot load
|
||||
// under node.
|
||||
vi.mock('./sessionRuntime.svelte', () => ({ resetSessionPreviewTabs: vi.fn() }))
|
||||
import { resetSessionPreviewTabs } from './sessionRuntime.svelte'
|
||||
import { registerMountedOpenInSessionHandoff } from './openInSessionContext'
|
||||
|
||||
function session(over: Partial<Session> = {}): Session {
|
||||
return { id: 's1', name: 'sess', createdAt: 0, ...over }
|
||||
}
|
||||
function ws(id: string, parent?: string): UserWorkspace {
|
||||
return { id, name: id, parent_workspace_id: parent } as unknown as UserWorkspace
|
||||
}
|
||||
|
||||
// Two-family fixture: rootA (with forkA) and rootB. Returns a restore fn.
|
||||
function session(over: Partial<Session> & { id: string }): Session {
|
||||
return { createdAt: 0, ...over }
|
||||
}
|
||||
|
||||
// Two families: rootA (with forkA) and rootB. Returns a restore fn.
|
||||
function withTwoFamilies(activeWorkspace: string): () => void {
|
||||
const prevUsers = get(usersWorkspaceStore)
|
||||
const prevWs = get(workspaceStore)
|
||||
const prevCurrent = sessionState.currentSessionId
|
||||
usersWorkspaceStore.set({
|
||||
email: 't@t',
|
||||
workspaces: [ws('rootA'), ws('forkA', 'rootA'), ws('rootB')]
|
||||
} as never)
|
||||
workspaceStore.set(activeWorkspace)
|
||||
return () => {
|
||||
sessionState.sessions = sessionState.sessions.filter((s) => !s.id.startsWith('sw-'))
|
||||
sessionState.currentSessionId = prevCurrent
|
||||
usersWorkspaceStore.set(prevUsers)
|
||||
workspaceStore.set(prevWs)
|
||||
}
|
||||
}
|
||||
|
||||
describe('enterSessionMode — restore is scoped to the active family', () => {
|
||||
describe('the sessions page resumes the last session opened', () => {
|
||||
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' })
|
||||
)
|
||||
// Not on Home already, so the resume navigates there.
|
||||
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
|
||||
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
|
||||
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)
|
||||
} finally {
|
||||
sessionState.sessions = sessionState.sessions.filter(
|
||||
(s) => s.id !== 'sw-only-foreign' && s.id !== createdId
|
||||
)
|
||||
sessionState.currentSessionId = prevCurrent
|
||||
vi.unstubAllGlobals()
|
||||
homeDraft.id = undefined
|
||||
restore()
|
||||
}
|
||||
})
|
||||
@@ -281,195 +260,3 @@ describe('startSessionWithPrompt', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('takeNewSessionSeed', () => {
|
||||
it('offers the item editor the user came from, once per arrival', () => {
|
||||
rememberNavRoute('/flows/edit/u/me/my_flow?workspace=ws')
|
||||
expect(takeNewSessionSeed()).toEqual({
|
||||
url: '/flows/edit/u/me/my_flow?workspace=ws',
|
||||
kind: 'flow',
|
||||
path: 'u/me/my_flow'
|
||||
})
|
||||
// A dismissed or taken offer is not repeated until the user leaves again.
|
||||
expect(takeNewSessionSeed()).toBeUndefined()
|
||||
rememberNavRoute('/apps_raw/edit/f/team/dashboard?workspace=ws')
|
||||
expect(takeNewSessionSeed()).toMatchObject({ kind: 'app', path: 'f/team/dashboard' })
|
||||
})
|
||||
|
||||
it('offers the pipeline the user came from, named by its folder', () => {
|
||||
rememberNavRoute('/pipeline/crm?workspace=ws')
|
||||
expect(takeNewSessionSeed()).toEqual({
|
||||
url: '/pipeline/crm?workspace=ws',
|
||||
kind: 'pipeline',
|
||||
path: 'f/crm'
|
||||
})
|
||||
})
|
||||
|
||||
it('offers nothing for a non-item page', () => {
|
||||
rememberNavRoute('/runs?workspace=ws')
|
||||
expect(takeNewSessionSeed()).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('enterSessionModeFromNav', () => {
|
||||
const HOUR = 60 * 60 * 1000
|
||||
beforeEach(() => {
|
||||
vi.mocked(goto).mockClear()
|
||||
vi.mocked(resetSessionPreviewTabs).mockClear()
|
||||
})
|
||||
|
||||
// One session in the active family (rootA), as the one the rail would resume.
|
||||
// Restores everything the test touched, the module-level nav route included,
|
||||
// and drops whatever session the call under test created.
|
||||
function withResumable(over: Partial<Session>): { restore: () => void } {
|
||||
const restoreFamilies = withTwoFamilies('rootA')
|
||||
const prevCurrent = sessionState.currentSessionId
|
||||
const before = new Set(sessionState.sessions.map((s) => s.id))
|
||||
const s = session({ workspace_id: 'rootA', ...over })
|
||||
sessionState.sessions.push(s)
|
||||
sessionState.currentSessionId = s.id
|
||||
return {
|
||||
restore: () => {
|
||||
sessionState.sessions = sessionState.sessions.filter((x) => before.has(x.id))
|
||||
sessionState.currentSessionId = prevCurrent
|
||||
rememberNavRoute('/')
|
||||
restoreFamilies()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('resumes a recently active session even when coming from an item', async () => {
|
||||
const { restore } = withResumable({
|
||||
id: 'nav-recent',
|
||||
name: 'session-921',
|
||||
lastActivityAt: Date.now() - HOUR / 2
|
||||
})
|
||||
try {
|
||||
rememberNavRoute('/flows/edit/u/me/f?workspace=rootA')
|
||||
await enterSessionModeFromNav()
|
||||
expect(sessionState.currentSessionId).toBe('nav-recent')
|
||||
expect(resetSessionPreviewTabs).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
it('starts a session on the item, by route, instead of resuming one idle for hours', async () => {
|
||||
const { restore } = withResumable({
|
||||
id: 'nav-stale',
|
||||
name: 'session-922',
|
||||
lastActivityAt: Date.now() - 3 * HOUR
|
||||
})
|
||||
try {
|
||||
rememberNavRoute('/flows/edit/u/me/f?workspace=forkA')
|
||||
await enterSessionModeFromNav()
|
||||
const createdId = sessionState.currentSessionId
|
||||
expect(createdId).not.toBe('nav-stale')
|
||||
expect(resetSessionPreviewTabs).toHaveBeenCalledWith(
|
||||
createdId,
|
||||
'/flows/edit/u/me/f?workspace=forkA'
|
||||
)
|
||||
// The route's workspace, not createSession's pick for the active one.
|
||||
const created = sessionState.sessions.find((s) => s.id === createdId)
|
||||
expect(created?.pending_workspace_id).toBe('forkA')
|
||||
// The arrival opened the item itself, so "New session" does not offer it.
|
||||
expect(takeNewSessionSeed()).toBeUndefined()
|
||||
} finally {
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
// The editor's hand-off is what its own "Open in AI session" button uses: its
|
||||
// beforeOpen persists the draft the preview loads, and it names the item's
|
||||
// workspace. The rail must take it over opening the route as last persisted.
|
||||
it('hands off through the mounted editor of the item, running its beforeOpen first', async () => {
|
||||
const { restore } = withResumable({
|
||||
id: 'nav-stale-editor',
|
||||
name: 'session-924',
|
||||
lastActivityAt: Date.now() - 3 * HOUR
|
||||
})
|
||||
const order: string[] = []
|
||||
vi.mocked(goto).mockImplementation((async () => {
|
||||
order.push('goto')
|
||||
}) as never)
|
||||
// A script editor mounted alongside (a flow's drawer) must not be taken
|
||||
// for the page's own item.
|
||||
const unregisterScript = registerMountedOpenInSessionHandoff({
|
||||
source: () => ({ target: { kind: 'script', path: 'u/me/s' }, workspaceId: 'rootB' })
|
||||
})
|
||||
const unregisterFlow = registerMountedOpenInSessionHandoff({
|
||||
source: () => ({
|
||||
target: { kind: 'flow', path: 'u/me/f' },
|
||||
workspaceId: 'forkA',
|
||||
beforeOpen: () => {
|
||||
order.push('beforeOpen')
|
||||
}
|
||||
})
|
||||
})
|
||||
try {
|
||||
rememberNavRoute('/flows/edit/u/me/f?workspace=rootA')
|
||||
await enterSessionModeFromNav()
|
||||
const createdId = sessionState.currentSessionId
|
||||
expect(createdId).not.toBe('nav-stale-editor')
|
||||
expect(order).toEqual(['beforeOpen', 'goto'])
|
||||
expect(resetSessionPreviewTabs).toHaveBeenCalledWith(
|
||||
createdId,
|
||||
expect.stringMatching(/\/flows\/edit\/u\/me\/f$/)
|
||||
)
|
||||
const created = sessionState.sessions.find((s) => s.id === createdId)
|
||||
expect(created?.pending_workspace_id).toBe('forkA')
|
||||
} finally {
|
||||
unregisterFlow()
|
||||
unregisterScript()
|
||||
vi.mocked(goto).mockReset()
|
||||
vi.mocked(goto).mockResolvedValue(undefined as never)
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
it('resumes a stale session when coming from a non-item page', async () => {
|
||||
const { restore } = withResumable({
|
||||
id: 'nav-stale-runs',
|
||||
name: 'session-923',
|
||||
lastActivityAt: Date.now() - 3 * HOUR
|
||||
})
|
||||
try {
|
||||
rememberNavRoute('/runs?workspace=rootA')
|
||||
await enterSessionModeFromNav()
|
||||
expect(sessionState.currentSessionId).toBe('nav-stale-runs')
|
||||
expect(resetSessionPreviewTabs).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
restore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('exitSessionMode after a first deploy from the session', () => {
|
||||
it('returns to the deployed item, not the draft row the deploy discarded', async () => {
|
||||
const prevWs = get(workspaceStore)
|
||||
workspaceStore.set('w')
|
||||
vi.mocked(goto).mockClear()
|
||||
try {
|
||||
rememberNavRoute('/flows/edit/u/me/draft_ab12_cd34?workspace=w&nodraft=true&new_draft=true')
|
||||
navRouteItemMoved('flow', 'w', 'u/me/draft_ab12_cd34', 'f/ops/sync_invoices')
|
||||
await exitSessionMode()
|
||||
expect(goto).toHaveBeenCalledWith('/flows/edit/f/ops/sync_invoices?workspace=w')
|
||||
} finally {
|
||||
workspaceStore.set(prevWs)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the route when the move happened in a fork of its workspace', async () => {
|
||||
const prevWs = get(workspaceStore)
|
||||
workspaceStore.set('w')
|
||||
vi.mocked(goto).mockClear()
|
||||
try {
|
||||
rememberNavRoute('/flows/edit/f/ops/existing?workspace=w')
|
||||
navRouteItemMoved('flow', 'wm-fork-w', 'f/ops/existing', 'f/ops/fork_only')
|
||||
await exitSessionMode()
|
||||
expect(goto).toHaveBeenCalledWith('/flows/edit/f/ops/existing?workspace=w')
|
||||
} finally {
|
||||
workspaceStore.set(prevWs)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { BROWSER } from 'esm-env'
|
||||
import { fromStore } from 'svelte/store'
|
||||
import { roleCapabilities } from '$lib/stores'
|
||||
import { copilotInfo } from '$lib/aiStore'
|
||||
import {
|
||||
clearSessionsBetaOptOut,
|
||||
isGlobalAiEnabled,
|
||||
sessionsAllowedFor
|
||||
} from '$lib/components/copilot/chat/global/gate'
|
||||
|
||||
const capabilities = fromStore(roleCapabilities)
|
||||
const copilot = fromStore(copilotInfo)
|
||||
// Listing sessions from within a session's preview frame would nest the whole experience.
|
||||
const embedded = BROWSER && window.self !== window.top
|
||||
|
||||
/** Whether the sidebar lists AI sessions. Not in a browser that opted out of them, for a role
|
||||
* /sessions refuses, in a workspace that hid the assistant, nor inside a preview frame. */
|
||||
export function sidebarSessionsShown(): boolean {
|
||||
return (
|
||||
!embedded &&
|
||||
isGlobalAiEnabled() &&
|
||||
sessionsAllowedFor(!capabilities.current.code) &&
|
||||
!copilot.current.workspaceDisabled
|
||||
)
|
||||
}
|
||||
|
||||
/** Turning AI Sessions back on: Home, with the sessions listed in the sidebar. */
|
||||
export function activateAiSessions(): void {
|
||||
clearSessionsBetaOptOut('/')
|
||||
}
|
||||
@@ -1,19 +1,35 @@
|
||||
import { fromStore } from 'svelte/store'
|
||||
import { userWorkspaces } from '$lib/stores'
|
||||
import { fromStore, get } from 'svelte/store'
|
||||
import { userWorkspaces, workspaceStore } from '$lib/stores'
|
||||
import { switchWorkspace } from '$lib/storeUtils'
|
||||
import { useEditRights } from '$lib/operatorWriteRights'
|
||||
import { buildsAnything } from '$lib/editRights'
|
||||
import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy'
|
||||
import { workspaceAIClients } from '$lib/components/copilot/lib'
|
||||
import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl'
|
||||
import type { WorkModeLock } from '../copilot/chat/workMode'
|
||||
import { pickSessionWorkspace } from './SessionWorkspaceBar.svelte'
|
||||
import { useSessionReadOnly } from './sessionPermissions.svelte'
|
||||
import { getEffectiveWorkspaceId, type Session } from './sessionState.svelte'
|
||||
import { startSessionWithPrompt } from './sessionSwitch.svelte'
|
||||
import {
|
||||
getEffectiveWorkspaceId,
|
||||
setSessionPendingWorkspace,
|
||||
type Session
|
||||
} from './sessionState.svelte'
|
||||
import { openNewSession } from './sessionSwitch.svelte'
|
||||
|
||||
// Home's draft acts on the workspace the header names, so there the header moves with the
|
||||
// session, the way the header's own picker switches it.
|
||||
function moveUnsentSession(sessionId: string, id: string, switchesWorkspace: boolean) {
|
||||
setSessionPendingWorkspace(sessionId, id)
|
||||
if (!switchesWorkspace || get(workspaceStore) === id) return
|
||||
workspaceAIClients.init(id)
|
||||
switchWorkspace(id)
|
||||
void fixupUrlAfterWorkspaceSwitch(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* What holds a session's chat in Use, for its mode picker: a protected workspace, whose way
|
||||
* out is its dev workspace, or a role that builds nothing there. `switchesWorkspace` is the
|
||||
* session's workspace bar's: on Home, moving the session to the dev workspace moves the page
|
||||
* too. Reads context and registers an effect: call during component initialisation.
|
||||
* out is its dev workspace, or a role that builds nothing there. `switchesWorkspace` is for
|
||||
* Home: moving its draft to the dev workspace moves the page too. Reads context and registers
|
||||
* an effect: call during component initialisation.
|
||||
*/
|
||||
export function useWorkModeLock(session: () => Session | undefined, switchesWorkspace = false) {
|
||||
const workspace = () => {
|
||||
@@ -37,15 +53,15 @@ export function useWorkModeLock(session: () => Session | undefined, switchesWork
|
||||
return {
|
||||
reason: `This workspace is protected against direct changes. Build in ${label}.`,
|
||||
// Until its first message a session can still change workspace; after it, only a new
|
||||
// one can act elsewhere.
|
||||
// one can act elsewhere: Home's composer, on the dev workspace.
|
||||
escape: s.workspace_id
|
||||
? {
|
||||
label: `New session in ${label}`,
|
||||
action: () => void startSessionWithPrompt('', { workspace: dev.id })
|
||||
action: () => void openNewSession(dev.id)
|
||||
}
|
||||
: {
|
||||
label: `Switch to ${label}`,
|
||||
action: () => pickSessionWorkspace(s.id, dev.id, switchesWorkspace)
|
||||
action: () => moveUnsentSession(s.id, dev.id, switchesWorkspace)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
import { truncate } from '$lib/utils'
|
||||
import { onDestroy, untrack } from 'svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { ArrowRightLeft } from 'lucide-svelte'
|
||||
import { ArrowRightLeft, ExternalLink } from 'lucide-svelte'
|
||||
|
||||
let offboardingUser: string | undefined = $state(undefined)
|
||||
let offboardingReassignOnly = $state(false)
|
||||
@@ -495,6 +495,14 @@
|
||||
description="Add members to your workspace and manage their roles. You can also auto-add users to join your workspace."
|
||||
link="https://www.windmill.dev/docs/core_concepts/roles_and_permissions"
|
||||
/>
|
||||
<!-- Someone looking for a way to share with several people at once lands here, on members, rather
|
||||
than on the Groups page that does it. -->
|
||||
<p class="-mt-4 mb-6 text-xs text-secondary">
|
||||
Sharing items with several members at once? Gather them in a group on the
|
||||
<a href="/groups" target="_blank" class="whitespace-nowrap"
|
||||
>Groups page <ExternalLink size={12} class="inline-block" /></a
|
||||
>, then share with the group.
|
||||
</p>
|
||||
|
||||
{#if isAdminsWorkspaceWithoutEE}
|
||||
<Alert type="info" title="Admins workspace">
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { slide } from 'svelte/transition'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { Bot } from 'lucide-svelte'
|
||||
import SidebarSectionHeader from './SidebarSectionHeader.svelte'
|
||||
import { page } from '$app/state'
|
||||
import { afterNavigate } from '$app/navigation'
|
||||
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
|
||||
import { FlowConversationsService, type FlowConversation } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
|
||||
import { agentOfChatPath } from '$lib/components/flows/conversations/agentEditorChat'
|
||||
import { sidebarClasses } from './MenuButton.svelte'
|
||||
|
||||
// The workspace's flow and agent chats, the ones a flow's or an agent's own page shows: the
|
||||
// editors' test chats stay with the editors.
|
||||
let { isCollapsed = false }: { isCollapsed?: boolean } = $props()
|
||||
|
||||
const sectionCollapsed = useLocalStorageValue(
|
||||
'windmill_ai_chats_section_collapsed',
|
||||
false,
|
||||
'boolean'
|
||||
)
|
||||
|
||||
// Tagged with its workspace: responses are not ordered, and a late one from the workspace
|
||||
// just left must not show here. Not read on the collapsed rail, which shows no chats.
|
||||
const listing = resource(
|
||||
() => [$workspaceStore, isCollapsed] as const,
|
||||
async ([ws, collapsed]) => {
|
||||
if (!ws || collapsed) return undefined
|
||||
const rows = await FlowConversationsService.listFlowConversations({
|
||||
workspace: ws,
|
||||
perPage: 30,
|
||||
kind: 'deployed'
|
||||
})
|
||||
return { ws, rows }
|
||||
}
|
||||
)
|
||||
// A chat is started on its flow's or agent's page, so it lists once the reader leaves one.
|
||||
afterNavigate(({ from, to }) => {
|
||||
const left = from?.url.pathname
|
||||
if (!left || left === to?.url.pathname) return
|
||||
if (left.startsWith('/flows/get/') || left.startsWith('/agents/get/')) listing.refetch()
|
||||
})
|
||||
const rows = $derived(
|
||||
listing.current && listing.current.ws === $workspaceStore ? listing.current.rows : []
|
||||
)
|
||||
|
||||
function target(c: FlowConversation) {
|
||||
const agent = agentOfChatPath(c.flow_path)
|
||||
return {
|
||||
agent: agent !== undefined,
|
||||
path: agent ?? c.flow_path,
|
||||
href: `/${agent !== undefined ? 'agents' : 'flows'}/get/${agent ?? c.flow_path}?conversation=${c.id}`
|
||||
}
|
||||
}
|
||||
|
||||
const openId = $derived(page.url.searchParams.get('conversation'))
|
||||
</script>
|
||||
|
||||
{#if !isCollapsed && rows.length > 0}
|
||||
<div class="flex flex-col gap-1">
|
||||
<SidebarSectionHeader
|
||||
title="AI chats"
|
||||
collapsed={sectionCollapsed.val}
|
||||
onToggle={() => (sectionCollapsed.val = !sectionCollapsed.val)}
|
||||
/>
|
||||
{#if !sectionCollapsed.val}
|
||||
<div
|
||||
transition:slide={{ duration: 180 }}
|
||||
class="flex flex-col gap-0.5 max-h-[40vh] overflow-y-auto"
|
||||
>
|
||||
{#each rows as c (c.id)}
|
||||
{@const t = target(c)}
|
||||
{@const selected = openId === c.id}
|
||||
<a
|
||||
href={t.href}
|
||||
title="{t.agent ? 'Agent' : 'Flow'} {t.path}"
|
||||
class={twMerge(
|
||||
'flex flex-row items-center gap-2 px-2 py-1 rounded text-xs font-normal min-w-0',
|
||||
selected
|
||||
? twMerge(sidebarClasses.selectedBg, sidebarClasses.selectedText)
|
||||
: 'text-secondary hover:bg-surface-hover'
|
||||
)}
|
||||
>
|
||||
{#if t.agent}
|
||||
<Bot size={14} class="shrink-0 text-violet-500" />
|
||||
{:else}
|
||||
<BarsStaggered size={14} class="shrink-0 text-teal-500" />
|
||||
{/if}
|
||||
<span class="truncate">{c.title || 'Untitled chat'}</span>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,97 @@
|
||||
<!--
|
||||
@component
|
||||
The starred items as a sidebar section, turned on from "Customize sidebar" in the settings menu.
|
||||
Hidden in the collapsed rail, like the AI chats.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { slide } from 'svelte/transition'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { Bot, CodeXml, LayoutDashboard, Table2, Trash2 } from 'lucide-svelte'
|
||||
import { page } from '$app/state'
|
||||
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import { globalDbManagerDrawer, workspaceStore } from '$lib/stores'
|
||||
import { parseDbInputFromAssetSyntax } from '$lib/utils'
|
||||
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
|
||||
import SidebarSectionHeader from './SidebarSectionHeader.svelte'
|
||||
import { favoriteManager } from './FavoriteMenu.svelte'
|
||||
import { sidebarClasses } from './MenuButton.svelte'
|
||||
import { sidebarPrefs } from './sidebarPrefs.svelte'
|
||||
|
||||
let { isCollapsed = false }: { isCollapsed?: boolean } = $props()
|
||||
|
||||
const sectionCollapsed = useLocalStorageValue(
|
||||
'windmill_favorites_section_collapsed',
|
||||
false,
|
||||
'boolean'
|
||||
)
|
||||
|
||||
const loaded = $derived(favoriteManager.loadedFor === $workspaceStore)
|
||||
</script>
|
||||
|
||||
{#if sidebarPrefs.favorites.val && !isCollapsed && loaded}
|
||||
<div class="flex flex-col gap-1">
|
||||
<SidebarSectionHeader
|
||||
title="Favorites"
|
||||
collapsed={sectionCollapsed.val}
|
||||
onToggle={() => (sectionCollapsed.val = !sectionCollapsed.val)}
|
||||
/>
|
||||
{#if !sectionCollapsed.val}
|
||||
<div transition:slide={{ duration: 180 }} class="flex flex-col gap-0.5">
|
||||
{#each favoriteManager.current as favorite (`${favorite.kind}:${favorite.path}`)}
|
||||
{@const selected = favorite.href !== '#' && page.url.pathname === favorite.href}
|
||||
<div class="relative group/fav">
|
||||
<!-- An asset's href is `#`: it opens in the database manager instead. -->
|
||||
<a
|
||||
href={favorite.href}
|
||||
title={favorite.path}
|
||||
onclick={(e) => {
|
||||
if (favorite.kind !== 'asset') return
|
||||
e.preventDefault()
|
||||
const dbInput = parseDbInputFromAssetSyntax(favorite.path)
|
||||
if (dbInput) globalDbManagerDrawer.val?.openDrawer(dbInput)
|
||||
}}
|
||||
class={twMerge(
|
||||
'flex flex-row items-center gap-2 px-2 py-1 pr-7 rounded text-xs font-normal min-w-0',
|
||||
selected
|
||||
? twMerge(sidebarClasses.selectedBg, sidebarClasses.selectedText)
|
||||
: 'text-secondary hover:bg-surface-hover'
|
||||
)}
|
||||
>
|
||||
<!-- Kind colors mirror the home-page row icons (RowIcon.svelte). -->
|
||||
{#if favorite.kind == 'script'}
|
||||
<CodeXml size={14} class="shrink-0 text-blue-500" />
|
||||
{:else if favorite.kind == 'flow'}
|
||||
<BarsStaggered size={14} class="shrink-0 text-teal-500" />
|
||||
{:else if favorite.kind == 'app' || favorite.kind == 'raw_app'}
|
||||
<LayoutDashboard size={14} class="shrink-0 text-orange-500" />
|
||||
{:else if favorite.kind == 'agent'}
|
||||
<Bot size={14} class="shrink-0 text-violet-500" />
|
||||
{:else}
|
||||
<Table2 size={14} class="shrink-0 text-primary" />
|
||||
{/if}
|
||||
<span class="truncate">{favorite.label}</span>
|
||||
</a>
|
||||
<div
|
||||
class="absolute right-0.5 top-0 h-full flex items-center opacity-0 group-hover/fav:opacity-100 has-[[aria-expanded=true]]:opacity-100 transition-opacity"
|
||||
>
|
||||
<DropdownV2
|
||||
items={[
|
||||
{
|
||||
displayName: 'Remove from favorites',
|
||||
icon: Trash2,
|
||||
action: () => favoriteManager.unstar(favorite.path, favorite.kind)
|
||||
}
|
||||
]}
|
||||
size="xs"
|
||||
fixedHeight={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="px-2 py-1 text-2xs text-hint">Star an item to list it here.</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -122,11 +122,13 @@
|
||||
{href}
|
||||
data-light-mode={lightMode}
|
||||
class={twMerge(
|
||||
'group flex items-center px-2 py-2 font-light rounded-md gap-2',
|
||||
'group flex items-center px-2 py-1 font-light rounded-md gap-2',
|
||||
compact ? 'w-auto' : 'w-full',
|
||||
sidebarClasses.hoverBg,
|
||||
'transition-all relative',
|
||||
sublabel ? 'h-10' : 'h-8',
|
||||
// Compact rows sit in the page header and keep its height; the nav's are 30px, and
|
||||
// square on the collapsed rail.
|
||||
sublabel ? 'h-10' : compact || isCollapsed ? 'h-8' : 'h-[30px]',
|
||||
classNames,
|
||||
buttonClass
|
||||
)}
|
||||
|
||||
@@ -60,7 +60,9 @@
|
||||
}}
|
||||
{onclick}
|
||||
class={twMerge(
|
||||
'group flex items-center px-2 py-2 text-sm font-light rounded-md h-8 gap-2',
|
||||
'group flex items-center px-2 py-1 text-sm font-light rounded-md gap-2',
|
||||
// Collapsed, the rail's rows are squares, as its footer buttons are.
|
||||
isCollapsed ? 'h-8' : 'h-[30px]',
|
||||
isSelected
|
||||
? sidebarClasses.selectedBg
|
||||
: item
|
||||
|
||||
@@ -19,8 +19,13 @@
|
||||
Gauge,
|
||||
Trash2,
|
||||
KeyRound,
|
||||
GraduationCap
|
||||
GraduationCap,
|
||||
PanelLeft,
|
||||
Star,
|
||||
FolderOpen,
|
||||
Users
|
||||
} from 'lucide-svelte'
|
||||
import { sidebarPrefs } from './sidebarPrefs.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { type Item } from '$lib/utils'
|
||||
import { logout } from '$lib/logoutKit'
|
||||
@@ -149,6 +154,12 @@
|
||||
// Leaving a workspace lives on the workspace settings page, which every member reaches,
|
||||
// not in this menu next to Logout: only a workspace admin can undo a leave.
|
||||
const workspaceInstanceItems = $derived<Item[]>([
|
||||
...($roleCapabilities.visibility.folders
|
||||
? [{ displayName: 'Folders', icon: FolderOpen, href: '/folders' }]
|
||||
: []),
|
||||
...($roleCapabilities.visibility.groups
|
||||
? [{ displayName: 'Groups', icon: Users, href: '/groups' }]
|
||||
: []),
|
||||
// Fork deletion is a global-sidebar action on the active workspace, so keep it
|
||||
// out of the session rail's per-target settings entry (`workspaceSettingsTarget`).
|
||||
...(currentWsIsThrowawayFork && !workspaceSettingsTarget
|
||||
@@ -201,6 +212,18 @@
|
||||
icon: darkMode ? Sun : Moon,
|
||||
action: () => toggleDarkMode()
|
||||
},
|
||||
{
|
||||
displayName: 'Customize sidebar',
|
||||
icon: PanelLeft,
|
||||
submenuItems: [
|
||||
{
|
||||
displayName: 'Favorites section',
|
||||
icon: Star,
|
||||
toggle: sidebarPrefs.favorites.val,
|
||||
action: () => (sidebarPrefs.favorites.val = !sidebarPrefs.favorites.val)
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
// The email is the label itself; the crown icon carries the admin role.
|
||||
displayName: $userStore?.non_member
|
||||
@@ -284,7 +307,7 @@
|
||||
|
||||
<!-- Workers and Logs are full pages (not account/instance actions), so they sit
|
||||
as plain links above the Settings dropdown rather than inside it. -->
|
||||
<div class="flex flex-col gap-1 pb-1">
|
||||
<div class="flex flex-col gap-0.5 mb-0.5">
|
||||
<MenuLink
|
||||
class="!text-xs"
|
||||
label="Workers"
|
||||
@@ -300,15 +323,16 @@
|
||||
items={logsItems}
|
||||
placement="top-start"
|
||||
class="w-full"
|
||||
fixedHeight={false}
|
||||
enableFlyTransition
|
||||
aiId="sidebar-menu-link-logs"
|
||||
aiDescription="Button to open the logs menu (audit logs, service logs, critical alerts)"
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<span
|
||||
class="relative flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-secondary text-xs hover:bg-surface-hover cursor-pointer {isCollapsed
|
||||
? 'justify-center'
|
||||
: ''}"
|
||||
class="relative flex items-center gap-2 w-full px-2 rounded-md text-secondary text-xs hover:bg-surface-hover cursor-pointer {isCollapsed
|
||||
? 'h-8 justify-center'
|
||||
: 'h-[30px]'}"
|
||||
>
|
||||
<Logs size={16} />
|
||||
{#if !isCollapsed}
|
||||
@@ -350,14 +374,15 @@
|
||||
{items}
|
||||
placement="top-start"
|
||||
class="w-full"
|
||||
fixedHeight={false}
|
||||
enableFlyTransition
|
||||
on:close={onChangelogsOpened}
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<span
|
||||
class="relative flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-secondary text-xs hover:bg-surface-hover cursor-pointer {isCollapsed
|
||||
? 'justify-center'
|
||||
: ''}"
|
||||
class="relative flex items-center gap-2 w-full px-2 rounded-md text-secondary text-xs hover:bg-surface-hover cursor-pointer {isCollapsed
|
||||
? 'h-8 justify-center'
|
||||
: 'h-[30px]'}"
|
||||
>
|
||||
<Settings size={16} />
|
||||
{#if !isCollapsed}
|
||||
|
||||
@@ -29,9 +29,7 @@
|
||||
Unplug,
|
||||
AlertCircle,
|
||||
Database,
|
||||
MailIcon,
|
||||
ChevronDown,
|
||||
ChevronRight
|
||||
MailIcon
|
||||
} from 'lucide-svelte'
|
||||
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
|
||||
import { slide } from 'svelte/transition'
|
||||
@@ -59,6 +57,7 @@
|
||||
MeltButton
|
||||
} from '$lib/components/meltComponents'
|
||||
import MenuButton from './MenuButton.svelte'
|
||||
import SidebarSectionHeader from './SidebarSectionHeader.svelte'
|
||||
import GoogleCloudIcon from '../icons/triggers/GoogleCloudIcon.svelte'
|
||||
import AzureIcon from '../icons/triggers/AzureIcon.svelte'
|
||||
import type { VisibilityKey } from '$lib/roleCapabilities'
|
||||
@@ -211,9 +210,7 @@
|
||||
aiId: 'sidebar-menu-link-resources',
|
||||
aiDescription: 'Button to navigate to resources'
|
||||
},
|
||||
Assets: { aiId: 'sidebar-menu-link-assets', aiDescription: 'Button to navigate to assets' },
|
||||
Folders: { aiId: 'sidebar-menu-link-folders', aiDescription: 'Button to navigate to folders' },
|
||||
Groups: { aiId: 'sidebar-menu-link-groups', aiDescription: 'Button to navigate to groups' }
|
||||
Assets: { aiId: 'sidebar-menu-link-assets', aiDescription: 'Button to navigate to assets' }
|
||||
}
|
||||
let mainMenuLinks = $derived(
|
||||
NAV_PAGES.filter((p) => p.label in MAIN_MENU_EXTRAS)
|
||||
@@ -226,6 +223,19 @@
|
||||
}))
|
||||
.filter((l) => !excludeMainLabels.includes(l.label))
|
||||
)
|
||||
// Main-menu pages listed in a collapsible Data section of their own, as Triggers.
|
||||
const DATA_LABELS = ['Variables', 'Resources', 'Assets']
|
||||
let ungroupedMainLinks = $derived(mainMenuLinks.filter((l) => !DATA_LABELS.includes(l.label)))
|
||||
// A disabled MenuLink renders nothing, so its page leaves the section, and a section with no
|
||||
// page left leaves the nav.
|
||||
let dataLinks = $derived(
|
||||
mainMenuLinks.filter((l) => DATA_LABELS.includes(l.label) && !l.disabled)
|
||||
)
|
||||
const dataSectionCollapsed = useLocalStorageValue(
|
||||
'windmill_data_section_collapsed',
|
||||
false,
|
||||
'boolean'
|
||||
)
|
||||
let defaultExtraTriggerLinks = $derived([
|
||||
{
|
||||
label: 'HTTP',
|
||||
@@ -469,81 +479,112 @@
|
||||
])
|
||||
</script>
|
||||
|
||||
<nav class={twMerge('flex flex-col overflow-x-hidden scrollbar-hidden px-2 md:pb-2 gap-2')}>
|
||||
<!-- Expanded, each section opens 10px under the one before, the gap the layout's scroll area puts
|
||||
between this nav and the sections after it; the collapsed rail keeps one pitch instead. -->
|
||||
<nav
|
||||
class={twMerge(
|
||||
'flex flex-col overflow-x-hidden scrollbar-hidden px-2 gap-2',
|
||||
isCollapsed ? 'md:pb-2' : ''
|
||||
)}
|
||||
>
|
||||
<div class={twMerge('flex flex-col')}>
|
||||
{#if showMain}
|
||||
<div class="space-y-1">
|
||||
{#each mainMenuLinks as menuLink (menuLink.href ?? menuLink.label)}
|
||||
<div class="space-y-0.5">
|
||||
{#each ungroupedMainLinks as menuLink (menuLink.href ?? menuLink.label)}
|
||||
<MenuLink class="!text-xs" {...menuLink} {isCollapsed} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if showMain}
|
||||
{#if dataLinks.length > 0}
|
||||
<!-- 8px: the layout's 2px gap above this nav makes it 10 under Runs. -->
|
||||
<div class={isCollapsed ? '' : 'mt-2'}>
|
||||
<!-- Collapsed, no title row: the rail's icons keep one pitch across sections. -->
|
||||
{#if !isCollapsed}
|
||||
<SidebarSectionHeader
|
||||
title="Data"
|
||||
collapsed={dataSectionCollapsed.val}
|
||||
onToggle={() => (dataSectionCollapsed.val = !dataSectionCollapsed.val)}
|
||||
/>
|
||||
{/if}
|
||||
{#if isCollapsed || !dataSectionCollapsed.val}
|
||||
<div transition:slide={{ duration: 180 }} class="flex flex-col gap-0.5">
|
||||
{#each dataLinks as menuLink (menuLink.href)}
|
||||
<MenuLink class="!text-xs" {...menuLink} {isCollapsed} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if showMain && showTriggersGroup}
|
||||
<div class="pt-4">
|
||||
{#if isCollapsed}
|
||||
<div class="text-secondary text-[0.5rem] uppercase transition-opacity opacity-0">
|
||||
Triggers
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (triggersCollapsed.val = !triggersCollapsed.val)}
|
||||
class="text-secondary text-[0.5rem] uppercase flex flex-row items-center gap-1 rounded px-1 -mx-1 py-0.5 hover:bg-surface-hover focus:outline-none"
|
||||
aria-expanded={!triggersCollapsed.val}
|
||||
>
|
||||
Triggers
|
||||
{#if triggersCollapsed.val}
|
||||
<ChevronRight size={10} />
|
||||
{:else}
|
||||
<ChevronDown size={10} />
|
||||
{/if}
|
||||
</button>
|
||||
<!-- Expanded, the + sits at the right of the section's title row, as the AI sessions
|
||||
section's options do; the collapsed rail has no title row, so it ends the list. -->
|
||||
{#snippet addTriggerMenu(createMenu: any, inHeader: boolean)}
|
||||
<Menu {createMenu} usePointerDownOutside placement={inHeader ? 'bottom-end' : undefined}>
|
||||
{#snippet triggr({ trigger })}
|
||||
<MeltButton
|
||||
aiId="sidebar-menu-link-add-trigger"
|
||||
aiDescription="Button to add a new trigger. Can be HTTP, WebSocket, Postgres, Kafka, NATS, SQS, GCP Pub/Sub, or MQTT"
|
||||
class={twMerge(
|
||||
inHeader
|
||||
? 'h-7 w-7 shrink-0 flex items-center justify-center rounded-md text-secondary hover:bg-surface-hover'
|
||||
: 'w-full text-secondary text-2xs flex flex-row gap-1 py-1 items-center px-2 hover:bg-surface-hover rounded',
|
||||
'data-[highlighted]:bg-surface-hover'
|
||||
)}
|
||||
title="Add trigger"
|
||||
meltElement={trigger}
|
||||
>
|
||||
<Plus size={14} />
|
||||
</MeltButton>
|
||||
{/snippet}
|
||||
{#snippet children({ item })}
|
||||
{#each extraTriggerLinks as subItem (subItem.href ?? subItem.label)}
|
||||
<MenuItem
|
||||
aiId={subItem.aiId}
|
||||
aiDescription={subItem.aiDescription}
|
||||
href={subItem.disabled ? '' : subItem.href}
|
||||
class={twMerge(itemClass, subItem.disabled ? 'pointer-events-none opacity-50' : '')}
|
||||
{item}
|
||||
disabled={subItem.disabled}
|
||||
>
|
||||
<div class="flex flex-row items-center gap-2">
|
||||
{#if subItem.icon}
|
||||
<subItem.icon size={16} />
|
||||
{/if}
|
||||
{subItem.label}
|
||||
</div>
|
||||
</MenuItem>
|
||||
{/each}
|
||||
{/snippet}
|
||||
</Menu>
|
||||
{/snippet}
|
||||
<div class={isCollapsed ? 'mt-0.5' : 'mt-2.5'}>
|
||||
<!-- Collapsed, no title row: the rail's icons keep one pitch across sections. -->
|
||||
{#if !isCollapsed}
|
||||
<SidebarSectionHeader
|
||||
title="Triggers"
|
||||
collapsed={triggersCollapsed.val}
|
||||
onToggle={() => (triggersCollapsed.val = !triggersCollapsed.val)}
|
||||
actions={showAddTriggerMenu ? triggerHeaderActions : undefined}
|
||||
/>
|
||||
{#snippet triggerHeaderActions()}
|
||||
<Menubar>
|
||||
{#snippet children({ createMenu })}
|
||||
{@render addTriggerMenu(createMenu, true)}
|
||||
{/snippet}
|
||||
</Menubar>
|
||||
{/snippet}
|
||||
{/if}
|
||||
{#if isCollapsed || !triggersCollapsed.val}
|
||||
<div transition:slide={{ duration: 180 }}>
|
||||
<Menubar class="flex flex-col gap-1">
|
||||
<Menubar class="flex flex-col gap-0.5">
|
||||
{#snippet children({ createMenu })}
|
||||
{#each triggerMenuLinks as menuLink (menuLink.href ?? menuLink.label)}
|
||||
<MenuLink class="!text-xs" {...menuLink} {isCollapsed} />
|
||||
{/each}
|
||||
{#if showAddTriggerMenu}
|
||||
<Menu {createMenu} usePointerDownOutside>
|
||||
{#snippet triggr({ trigger })}
|
||||
<MeltButton
|
||||
aiId="sidebar-menu-link-add-trigger"
|
||||
aiDescription="Button to add a new trigger. Can be HTTP, WebSocket, Postgres, Kafka, NATS, SQS, GCP Pub/Sub, or MQTT"
|
||||
class={twMerge(
|
||||
'w-full text-secondary text-2xs flex flex-row gap-1 py-1 items-center px-2 hover:bg-surface-hover rounded',
|
||||
'data-[highlighted]:bg-surface-hover'
|
||||
)}
|
||||
meltElement={trigger}
|
||||
>
|
||||
<Plus size={14} />
|
||||
</MeltButton>
|
||||
{/snippet}
|
||||
{#snippet children({ item })}
|
||||
{#each extraTriggerLinks as subItem (subItem.href ?? subItem.label)}
|
||||
<MenuItem
|
||||
aiId={subItem.aiId}
|
||||
aiDescription={subItem.aiDescription}
|
||||
href={subItem.disabled ? '' : subItem.href}
|
||||
class={twMerge(
|
||||
itemClass,
|
||||
subItem.disabled ? 'pointer-events-none opacity-50' : ''
|
||||
)}
|
||||
{item}
|
||||
disabled={subItem.disabled}
|
||||
>
|
||||
<div class="flex flex-row items-center gap-2">
|
||||
{#if subItem.icon}
|
||||
<subItem.icon size={16} />
|
||||
{/if}
|
||||
{subItem.label}
|
||||
</div>
|
||||
</MenuItem>
|
||||
{/each}
|
||||
{/snippet}
|
||||
</Menu>
|
||||
{#if showAddTriggerMenu && isCollapsed}
|
||||
{@render addTriggerMenu(createMenu, false)}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Menubar>
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
<div
|
||||
bind:this={viewport}
|
||||
onscroll={measure}
|
||||
class="sidebar-scroll h-full overflow-y-auto overflow-x-hidden scrollbar-hidden flex flex-col gap-3"
|
||||
class="sidebar-scroll h-full overflow-y-auto overflow-x-hidden scrollbar-subtle flex flex-col gap-2.5"
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<!--
|
||||
@component
|
||||
A sidebar section's title row. The title folds the section and fills the row up to its actions;
|
||||
its padding lines the text up with the nav rows' icons and its height matches theirs, so actions
|
||||
are `sm` (h-7) buttons.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
collapsed: boolean
|
||||
onToggle: () => void
|
||||
/** A section with nothing to fold: the title stays, without its chevron. */
|
||||
disabled?: boolean
|
||||
actions?: Snippet
|
||||
}
|
||||
|
||||
let { title, collapsed, onToggle, disabled = false, actions }: Props = $props()
|
||||
|
||||
const titleClasses = 'px-2 text-secondary text-[0.5rem] font-normal uppercase'
|
||||
</script>
|
||||
|
||||
<div class="flex flex-row items-center h-7 gap-0.5">
|
||||
{#if disabled}
|
||||
<!-- A label rather than a disabled Button, which would grey the title out. -->
|
||||
<span class="flex-1 min-w-0 h-7 flex flex-row items-center {titleClasses}">{title}</span>
|
||||
{:else}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
onClick={onToggle}
|
||||
aria-expanded={!collapsed}
|
||||
wrapperClasses="flex-1 min-w-0"
|
||||
btnClasses="justify-start text-left gap-1 {titleClasses}"
|
||||
>
|
||||
{title}
|
||||
{#if collapsed}
|
||||
<ChevronRight size={10} />
|
||||
{:else}
|
||||
<ChevronDown size={10} />
|
||||
{/if}
|
||||
</Button>
|
||||
{/if}
|
||||
{@render actions?.()}
|
||||
</div>
|
||||
@@ -161,7 +161,9 @@
|
||||
// modal carries its own base-workspace picker). Hidden on non-premium cloud,
|
||||
// in the admins workspace, or when forking is disabled.
|
||||
const canForkHere = $derived(
|
||||
(!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && canCreateFork($userStore, $roleCapabilities)
|
||||
(!isCloudHosted() || $maybePremium) &&
|
||||
$workspaceStore !== 'admins' &&
|
||||
canCreateFork($userStore, $roleCapabilities)
|
||||
)
|
||||
// The row mechanics below — which family to expand, which collapsed row carries the tick — key on
|
||||
// a depth-0 row of the list, which `buildWorkspaceHierarchy` puts at the highest workspace the
|
||||
@@ -386,6 +388,7 @@
|
||||
|
||||
<div
|
||||
bind:this={rootEl}
|
||||
data-works-with-composer
|
||||
role="none"
|
||||
onpointermovecapture={keepSearchFocus}
|
||||
onpointerleavecapture={keepSearchFocus}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
|
||||
|
||||
/** What "Customize sidebar" in the settings menu changes, per browser. Module-level so the
|
||||
* menu that flips a choice and the sidebar that reads it share one value. */
|
||||
export const sidebarPrefs = {
|
||||
/** The starred items as a section of their own. */
|
||||
favorites: useLocalStorageValue('windmill_sidebar_show_favorites', false, 'boolean')
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -5,8 +5,7 @@ import { goto } from '$lib/navigation'
|
||||
// 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, 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
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import { DEV_WORKSPACE_LOCK_RULE_NAME } from '$lib/workspaceProtectionRules.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
import { ArrowRight, Plus, Save, Trash2 } from 'lucide-svelte'
|
||||
import GroupsPageLink from '$lib/components/GroupsPageLink.svelte'
|
||||
import { safeSelectItems } from '$lib/components/select/utils.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
|
||||
@@ -306,6 +307,9 @@
|
||||
class="flex flex-col gap-4"
|
||||
>
|
||||
<Label label="Groups">
|
||||
{#snippet action()}
|
||||
<GroupsPageLink />
|
||||
{/snippet}
|
||||
<MultiSelect
|
||||
bind:value={selectedGroups}
|
||||
items={safeSelectItems(availableGroups)}
|
||||
|
||||
@@ -17,18 +17,14 @@ vi.mock('./localDraftHints.svelte', () => ({
|
||||
setLocalDraftHint: vi.fn(),
|
||||
getLocalDraftHint: () => hints.value
|
||||
}))
|
||||
// `stripNewDraftFlag` rewrites the URL through SvelteKit's `replaceState` and
|
||||
// refreshes the 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())
|
||||
// `stripNewDraftFlag` rewrites the URL through SvelteKit's `replaceState`. Mock it
|
||||
// so the strip is observable via `window.location.href` (mirroring jsdom).
|
||||
vi.mock('$app/navigation', () => ({
|
||||
replaceState: (url: URL | string, _state: unknown) => {
|
||||
window.location.href = new URL(url, window.location.href).toString()
|
||||
}
|
||||
}))
|
||||
vi.mock('$app/state', () => ({ page: { state: {} } }))
|
||||
vi.mock('$lib/components/sessions/sessionSwitch.svelte', () => ({ rememberNavRoute }))
|
||||
|
||||
import { UserDraftDbSyncer } from './userDraftDbSyncer.svelte'
|
||||
import { stripNewDraftFlagOnSave, shouldSeedNewDraft } from './newDraftFlag'
|
||||
@@ -120,9 +116,6 @@ describe('stripNewDraftFlagOnSave', () => {
|
||||
expect(window.location.href).not.toContain('new_draft')
|
||||
// Sibling seeding params are preserved.
|
||||
expect(window.location.href).toContain('template=foo')
|
||||
// The 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')
|
||||
})
|
||||
|
||||
it('does not strip on a delete save', async () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { page } from '$app/state'
|
||||
import { replaceState } from '$app/navigation'
|
||||
import { rememberNavRoute } from '$lib/components/sessions/sessionSwitch.svelte'
|
||||
import { UserDraftDbSyncer, type UserDraftLastSyncQuery } from '$lib/userDraftDbSyncer.svelte'
|
||||
import { getLocalDraftHint } from '$lib/localDraftHints.svelte'
|
||||
import type { UserDraftItemKind } from '$lib/gen'
|
||||
@@ -11,17 +10,13 @@ import type { UserDraftItemKind } from '$lib/gen'
|
||||
*
|
||||
* Uses SvelteKit's `replaceState` (not raw `history.replaceState`, which the
|
||||
* router warns conflicts with it) so the history entry keeps the router's
|
||||
* bookkeeping and `page.state`. Also refreshes the remembered nav route:
|
||||
* `afterNavigate` never observes this in-place rewrite, so without it
|
||||
* `exitSessionMode` would restore the pre-strip URL — still carrying
|
||||
* `?new_draft=true` — and re-enter the seed-empty branch. */
|
||||
* bookkeeping and `page.state`. */
|
||||
export function stripNewDraftFlag(): void {
|
||||
if (typeof window === 'undefined') return
|
||||
const url = new URL(window.location.href)
|
||||
if (url.searchParams.get('new_draft') !== 'true') return
|
||||
url.searchParams.delete('new_draft')
|
||||
replaceState(url, page.state)
|
||||
rememberNavRoute(url.pathname + url.search)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,9 +25,10 @@ export function stripNewDraftFlag(): void {
|
||||
* The `/{scripts,flows,apps,apps_raw}/add` redirect lands the editor on
|
||||
* `u/<user>/draft_<uuid>?new_draft=true`; the seed branch bootstraps an empty
|
||||
* (or template/hub/fork-seeded) editor instead of fetching a row that doesn't
|
||||
* exist yet. But the flag can outlive the seed: exiting an AI session restores
|
||||
* the remembered nav route (still `?new_draft=true`) even though the draft was
|
||||
* already materialized — by the first autosave, or by "Open in AI session"'s
|
||||
* exist yet. But the flag can outlive the seed: a return to the editor's URL
|
||||
* (Back, 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
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
import SettingsMenu from '$lib/components/sidebar/SettingsMenu.svelte'
|
||||
import SidebarUsage from '$lib/components/sidebar/SidebarUsage.svelte'
|
||||
import SidebarScrollArea from '$lib/components/sidebar/SidebarScrollArea.svelte'
|
||||
import AiChatsSection from '$lib/components/sidebar/AiChatsSection.svelte'
|
||||
import FavoritesSection from '$lib/components/sidebar/FavoritesSection.svelte'
|
||||
import AccountSetupBanner from '$lib/components/sidebar/AccountSetupBanner.svelte'
|
||||
import FinishAccountSetup from '$lib/components/sidebar/FinishAccountSetup.svelte'
|
||||
import { accountSetup } from '$lib/components/sidebar/accountSetup.svelte'
|
||||
@@ -58,15 +60,14 @@
|
||||
type UserWorkspace
|
||||
} from '$lib/stores'
|
||||
import CenteredModal from '$lib/components/CenteredModal.svelte'
|
||||
import { afterNavigate, beforeNavigate, onNavigate } from '$app/navigation'
|
||||
import { recordComposerFocus } from '$lib/components/sessions/homeComposerFocus'
|
||||
import { afterNavigate, beforeNavigate } from '$app/navigation'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte'
|
||||
import type UserSettings from '$lib/components/UserSettings.svelte'
|
||||
import type SuperadminSettings from '$lib/components/SuperadminSettings.svelte'
|
||||
import WindmillIcon from '$lib/components/icons/WindmillIcon.svelte'
|
||||
import { page } from '$app/state'
|
||||
import FavoriteMenu, {
|
||||
import {
|
||||
favoriteManager,
|
||||
getFavoriteHref,
|
||||
getFavoriteLabel
|
||||
@@ -109,11 +110,10 @@
|
||||
import InstanceUiSync from '$lib/components/InstanceUiSync.svelte'
|
||||
import { onDestroy, setContext, untrack } from 'svelte'
|
||||
import { cubicOut } from 'svelte/easing'
|
||||
import { Menubar, Tooltip } from '$lib/components/meltComponents'
|
||||
import { Tooltip } from '$lib/components/meltComponents'
|
||||
import { aiChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
|
||||
import AiChatLayout from '$lib/components/copilot/chat/AiChatLayout.svelte'
|
||||
import SessionPicker from '$lib/components/sessions/SessionPicker.svelte'
|
||||
import SessionModeSwitch from '$lib/components/sessions/SessionModeSwitch.svelte'
|
||||
import { isGlobalAiEnabled, sessionsAllowedFor } from '$lib/components/copilot/chat/global/gate'
|
||||
import { copilotInfo } from '$lib/aiStore'
|
||||
import {
|
||||
@@ -121,7 +121,8 @@
|
||||
parsePreviewItemRoute,
|
||||
barePath
|
||||
} from '$lib/components/sessions/previewPaths'
|
||||
import { rememberNavRoute } from '$lib/components/sessions/sessionSwitch.svelte'
|
||||
import { sidebarSessionsShown } 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'
|
||||
@@ -154,10 +155,6 @@
|
||||
})
|
||||
)
|
||||
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.
|
||||
let preserveMenuOnNextNav = false
|
||||
let globalSearchModal: GlobalSearchModal | undefined = $state(undefined)
|
||||
// Persisted nav-rail collapse preference. A deliberate collapse writes to it —
|
||||
// the manual toggle and a drag past the collapse threshold. The contextual
|
||||
@@ -301,38 +298,29 @@
|
||||
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.
|
||||
// An operator without the opt-in (`gate.ts`) is refused by /sessions, so their sidebar lists
|
||||
// no sessions 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 session's preview iframe, whose rail keeps the workspace nav and no switch.
|
||||
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 sidebar's session section 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.
|
||||
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)
|
||||
// points: the session section and the legacy Ask-AI button.
|
||||
const sessionsShown = $derived(sidebarSessionsShown())
|
||||
const askAiShown = $derived(
|
||||
(!globalAiEnabled || !sessionsAllowed) && !$copilotInfo.workspaceDisabled
|
||||
)
|
||||
@@ -449,14 +437,8 @@
|
||||
return kind ? { kind, path: route.itemPath } : undefined
|
||||
}
|
||||
|
||||
onNavigate(recordComposerFocus)
|
||||
|
||||
beforeNavigate((navigation) => {
|
||||
if (preserveMenuOnNextNav) {
|
||||
preserveMenuOnNextNav = false
|
||||
} else {
|
||||
menuOpen = false
|
||||
}
|
||||
menuOpen = false
|
||||
|
||||
// Inside a sessions-preview iframe, hand an editor-route navigation up to the
|
||||
// parent so it mounts the in-process editor (sharing the session runtime)
|
||||
@@ -793,13 +775,9 @@
|
||||
$usedTriggerKinds = usedKinds
|
||||
}
|
||||
|
||||
// Not inside a preview iframe: it opens no session page of its own.
|
||||
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`).
|
||||
@@ -1140,19 +1118,9 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
<meta name="apple-mobile-web-app-title" content="Windmill" />
|
||||
</svelte:head>
|
||||
|
||||
<!-- Home + Runs lifted to the top of the workspace nav, sitting with Favorites
|
||||
and Search as the primary quick-access cluster. Excluded from SidebarContent
|
||||
(via excludeMainLabels) so they aren't rendered twice. -->
|
||||
<!-- Runs lifted to the top of the workspace nav. Excluded from SidebarContent (via
|
||||
excludeMainLabels), as Home is, so neither is rendered twice. -->
|
||||
{#snippet quickLinks(collapsed: boolean)}
|
||||
<MenuLink
|
||||
class="!text-xs"
|
||||
label="Home"
|
||||
href="/"
|
||||
icon={Home}
|
||||
isCollapsed={collapsed}
|
||||
aiId="sidebar-menu-link-home"
|
||||
aiDescription="Button to navigate to home which contains all the user's scripts, flows and apps"
|
||||
/>
|
||||
<MenuLink
|
||||
class="!text-xs"
|
||||
label="Runs"
|
||||
@@ -1170,7 +1138,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
<!-- In the rail's pinned footer, right above the plan usage, in both rails and both modes:
|
||||
<!-- In the rail's pinned footer, right above the plan usage, in both rails:
|
||||
an account with no credentials of its own needs to see this wherever it is on the
|
||||
page and however far the nav has scrolled, and the footer is where the rail already
|
||||
keeps what is about the account rather than the workspace. -->
|
||||
@@ -1217,11 +1185,9 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<!-- Settings / instance section. Shared by both sidebar surfaces and both modes
|
||||
(in nav mode it's the last section inside the unified scroll area; in session
|
||||
mode it stays pinned under the session list). -->
|
||||
<!-- Settings / instance section: the last section inside the nav's unified scroll area. -->
|
||||
{#snippet settingsMenu(collapsed: boolean)}
|
||||
<div class="px-2 pb-1">
|
||||
<div class="px-2">
|
||||
<SettingsMenu
|
||||
isCollapsed={collapsed}
|
||||
workspaceSettingsTarget={sessionSettingsWorkspace}
|
||||
@@ -1262,96 +1228,111 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
onpointerdown={startSidebarResize}
|
||||
></div>
|
||||
{/if}
|
||||
<!-- Top row: the workspace ⇄ sessions switch, level with the page header's own
|
||||
row so the two read as one band. The workspace picker itself lives in that
|
||||
header, which is why nothing names the workspace here. -->
|
||||
{#if switchRowShown}
|
||||
<div
|
||||
class="flex-shrink-0 px-2 gap-1 flex {collapsed
|
||||
? 'flex-col items-center py-2'
|
||||
: 'h-12 items-center'}"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<SessionModeSwitch
|
||||
mode={sessionMode ? 'session' : 'nav'}
|
||||
isCollapsed={collapsed}
|
||||
onToggle={panel ? () => (preserveMenuOnNextNav = true) : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if sessionMode}
|
||||
<!-- Session mode: the session list owns the column. Workspace nav moves
|
||||
into the preview side panel (the iframe renders its own nav). -->
|
||||
<div class="px-2 py-2 flex flex-col gap-1 flex-1 min-h-0 overflow-y-auto">
|
||||
<SessionPicker isCollapsed={collapsed} embedded collapsible={false} />
|
||||
</div>
|
||||
{@render settingsMenu(collapsed)}
|
||||
{:else}
|
||||
<!-- Navigation mode: Home → Settings scroll as ONE block with an
|
||||
overflow fade hint. The three sections (Home/Runs + Favorites +
|
||||
Search / workspace items / instance settings) are spaced by the
|
||||
scroll area's gap rather than each scrolling on its own. -->
|
||||
<SidebarScrollArea color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
|
||||
<!-- Section 1: Home/Runs + Favorites + Search. Without the switch row above,
|
||||
Home is the top row and pt-2 centers its h-8 in the page header's h-12
|
||||
beside the docked rail. -->
|
||||
<div class="px-2 flex flex-col gap-1 {switchRowShown ? 'pt-1' : 'pt-2'}">
|
||||
{@render quickLinks(collapsed)}
|
||||
<Menubar class="flex flex-col gap-1">
|
||||
{#snippet children({ createMenu })}
|
||||
<FavoriteMenu
|
||||
{createMenu}
|
||||
favoriteLinks={favoriteManager.current}
|
||||
isCollapsed={collapsed}
|
||||
/>
|
||||
{/snippet}
|
||||
</Menubar>
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={() => openSearchModal()}
|
||||
isCollapsed={collapsed}
|
||||
icon={Search}
|
||||
label="Search"
|
||||
class="!text-xs"
|
||||
shortcut={`${getModifierKey()}k`}
|
||||
/>
|
||||
{#if askAiShown}
|
||||
<!-- Legacy Ask-AI pane, shown only when the user opted out of the
|
||||
AI Sessions beta (otherwise SessionModeSwitch replaces it). -->
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={() => aiChatManager.toggleOpen()}
|
||||
isCollapsed={collapsed}
|
||||
icon={WandSparkles}
|
||||
iconProps={{ forceDarkMode: true }}
|
||||
label="Ask AI"
|
||||
class="!text-xs"
|
||||
iconClasses="!text-ai"
|
||||
shortcut={`${getModifierKey()}L`}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Section 2: workspace items -->
|
||||
<SidebarContent
|
||||
<!-- Top row: Home, level with the page header's own row so the two read as one band.
|
||||
Home is one page for workspace and sessions alike. The workspace picker itself lives in that header,
|
||||
which is why nothing names the workspace here. -->
|
||||
<div class="flex-shrink-0 px-2 h-12 flex flex-row items-center gap-0.5">
|
||||
<div class="flex-1 min-w-0">
|
||||
<MenuLink
|
||||
class="!text-xs"
|
||||
label="Home"
|
||||
href="/"
|
||||
icon={Home}
|
||||
isCollapsed={collapsed}
|
||||
showSecondary={false}
|
||||
excludeMainLabels={['Home', 'Runs']}
|
||||
numUnacknowledgedCriticalAlerts={isCriticalAlertsUiMuted
|
||||
? 0
|
||||
: numUnacknowledgedCriticalAlerts}
|
||||
aiId="sidebar-menu-link-home"
|
||||
aiDescription="Button to navigate to home which contains all the user's scripts, flows and apps"
|
||||
/>
|
||||
</div>
|
||||
<!-- Expanded, Search shares Home's row; the collapsed rail keeps it in the nav below. -->
|
||||
{#if !collapsed}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Search }}
|
||||
title="Search"
|
||||
aria-label="Search"
|
||||
btnClasses="text-secondary gap-1 px-1.5"
|
||||
onClick={() => openSearchModal()}
|
||||
>
|
||||
<span class="text-2xs text-hint font-normal">{getModifierKey()}K</span>
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Pulled up into the Home band's slack under its centred row (48px band; rows 30px, 32px
|
||||
on the rail), so the next row sits 2px under Home, as the nav's rows sit apart. Kept
|
||||
outside the scroll area: a negative margin inside it would clip that row. -->
|
||||
<div class={twMerge('flex flex-col flex-1 min-h-0', collapsed ? '-mt-1.5' : '-mt-[7px]')}>
|
||||
<!-- The workspace nav: Runs → Settings scroll as ONE block with an
|
||||
overflow fade hint. The sections (Runs + workspace items / AI sessions /
|
||||
instance settings) are spaced by the scroll area's
|
||||
gap rather than each scrolling on its own. -->
|
||||
<SidebarScrollArea color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
|
||||
<!-- Section 1: Search (collapsed) + Runs, then the workspace items, spaced as one list. -->
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<div class="px-2 flex flex-col gap-0.5">
|
||||
<!-- Collapsed, Search stays right under Home, where it sits beside it expanded. -->
|
||||
{#if collapsed}
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={() => openSearchModal()}
|
||||
isCollapsed={collapsed}
|
||||
icon={Search}
|
||||
label="Search"
|
||||
class="!text-xs"
|
||||
shortcut={`${getModifierKey()}k`}
|
||||
/>
|
||||
{/if}
|
||||
{@render quickLinks(collapsed)}
|
||||
{#if askAiShown}
|
||||
<!-- Legacy Ask-AI pane, shown only when the user opted out of the
|
||||
AI Sessions beta (otherwise the AI sessions section replaces it). -->
|
||||
<MenuButton
|
||||
stopPropagationOnClick={true}
|
||||
on:click={() => aiChatManager.toggleOpen()}
|
||||
isCollapsed={collapsed}
|
||||
icon={WandSparkles}
|
||||
iconProps={{ forceDarkMode: true }}
|
||||
label="Ask AI"
|
||||
class="!text-xs"
|
||||
iconClasses="!text-ai"
|
||||
shortcut={`${getModifierKey()}L`}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<SidebarContent
|
||||
isCollapsed={collapsed}
|
||||
showSecondary={false}
|
||||
excludeMainLabels={['Home', 'Runs']}
|
||||
numUnacknowledgedCriticalAlerts={isCriticalAlertsUiMuted
|
||||
? 0
|
||||
: numUnacknowledgedCriticalAlerts}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Section 3: instance settings — mt-auto drops it to the bottom
|
||||
when the column has spare room, and collapses back to the normal
|
||||
inter-section gap once the content overflows and scrolls. -->
|
||||
<div class="mt-auto">
|
||||
{@render settingsMenu(collapsed)}
|
||||
<!-- The starred items, when "Customize sidebar" turns them on; hidden in the rail. -->
|
||||
<div class="px-2 empty:hidden">
|
||||
<FavoritesSection isCollapsed={collapsed} />
|
||||
</div>
|
||||
|
||||
<!-- Section 2: AI sessions, one row each; collapsed, a menu of them. -->
|
||||
{#if sessionsShown}
|
||||
<div class="px-2">
|
||||
<SessionPicker isCollapsed={collapsed} embedded />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- The flow and agent chats stored in the workspace; hidden in the collapsed rail. -->
|
||||
<div class="px-2 empty:hidden">
|
||||
<AiChatsSection isCollapsed={collapsed} />
|
||||
</div>
|
||||
</SidebarScrollArea>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Section 3: instance settings, pinned under the scrolled lists: inside them, long
|
||||
session and chat lists pushed it out of view under the bottom fade. -->
|
||||
<div class="flex-shrink-0 pt-2">
|
||||
{@render settingsMenu(collapsed)}
|
||||
</div>
|
||||
|
||||
<div class="flex-shrink-0">
|
||||
{@render accountSetupBanner(collapsed)}
|
||||
@@ -1359,12 +1340,12 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex-shrink-0 flex pt-3 pb-3.5 {collapsed
|
||||
? 'flex-col items-center gap-3'
|
||||
: 'items-center justify-between px-4'}"
|
||||
class="flex-shrink-0 flex pb-3.5 {collapsed
|
||||
? 'flex-col items-center gap-1 pt-4'
|
||||
: 'items-center justify-between px-4 pt-1'}"
|
||||
>
|
||||
{@render brandMark(collapsed)}
|
||||
<div class="flex {collapsed ? 'flex-col gap-3' : 'gap-3'}">
|
||||
<div class="flex {collapsed ? 'flex-col gap-1' : 'gap-3'}">
|
||||
{#if !panel || navDetached.val}
|
||||
{@render sidebarToggle()}
|
||||
{/if}
|
||||
@@ -1583,8 +1564,8 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
<AiChatLayout
|
||||
{children}
|
||||
noPadding={devOnly || menuHidden}
|
||||
disableAi={globalAiEnabled && sessionsAllowed ? true : sessionMode}
|
||||
loadAiConfig={!sessionMode}
|
||||
disableAi={globalAiEnabled && sessionsAllowed ? true : onSessionsPage}
|
||||
loadAiConfig={!onSessionsPage}
|
||||
showSessionsBetaBanner={sessionsAllowed}
|
||||
sidebarWidth={railWidth}
|
||||
transitionClass={sidebarTransitionClass}
|
||||
|
||||
@@ -98,6 +98,8 @@
|
||||
// the mount animation below never covers. Replay it by hand instead of keying the page on the
|
||||
// workspace: a remount would drop the list's own state and refetch what it is already loading.
|
||||
let pageEl: HTMLDivElement | undefined = $state(undefined)
|
||||
// Height of the composer's column, which stays at the top while the composer is open.
|
||||
let pinnedHeight = $state(0)
|
||||
|
||||
const reducedMotion = useReducedMotion()
|
||||
let animatedWorkspace = $workspaceStore
|
||||
@@ -287,8 +289,9 @@
|
||||
|
||||
<div
|
||||
bind:this={pageEl}
|
||||
class="wm-page-in flex flex-col w-full h-full overflow-y-auto items-center"
|
||||
class="wm-page-in group/home flex flex-col w-full h-full overflow-y-auto items-center"
|
||||
style="scrollbar-gutter: stable both-edges;"
|
||||
style:--home-pinned="{pinnedHeight}px"
|
||||
>
|
||||
<!-- Where edits to this workspace are made is a fact about the workspace, so it sits in the
|
||||
header with the workspace's own name rather than above the list. -->
|
||||
@@ -296,7 +299,14 @@
|
||||
|
||||
<ForkWorkspaceBanner />
|
||||
<WorkspaceDraftsBanner />
|
||||
<div class="{HOME_COLUMN_WIDTH} px-4 sm:px-8 md:px-8 h-fit w-full mb-6 shrink-0">
|
||||
<!-- While the composer is open this column stays at the top and the lists scroll under it. It
|
||||
is the scroller's own child because a sticky element holds only inside its parent; its
|
||||
background covers what passes under it, and the items' search bar sticks below it
|
||||
(`--home-pinned`, ItemsList) rather than behind it. -->
|
||||
<div
|
||||
bind:clientHeight={pinnedHeight}
|
||||
class="{HOME_COLUMN_WIDTH} px-4 sm:px-8 md:px-8 h-fit w-full pb-6 shrink-0 bg-surface group-has-[[data-composer-open]]/home:sticky group-has-[[data-composer-open]]/home:top-0 group-has-[[data-composer-open]]/home:z-20"
|
||||
>
|
||||
<!-- HomeAIChat carries both the AI composer and the AI-independent CLI/MCP connect row,
|
||||
so it shows whenever the sessions beta is on; the composer itself is gated on the
|
||||
workspace inside the component, which owns its own vertical spacing
|
||||
|
||||
@@ -6,5 +6,9 @@
|
||||
|
||||
<!-- Keyed: the route is reused across agents, and the page holds the form's args. -->
|
||||
{#key `${$workspaceStore}:${page.params.path}`}
|
||||
<AgentDetailPage path={page.params.path ?? ''} workspace={$workspaceStore} />
|
||||
<AgentDetailPage
|
||||
path={page.params.path ?? ''}
|
||||
workspace={$workspaceStore}
|
||||
openConversation={page.url.searchParams.get('conversation') ?? undefined}
|
||||
/>
|
||||
{/key}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount, tick, untrack } from 'svelte'
|
||||
import { onDestroy, onMount, untrack } from 'svelte'
|
||||
import { SvelteSet } from 'svelte/reactivity'
|
||||
import { page } from '$app/state'
|
||||
import {
|
||||
@@ -40,10 +40,9 @@
|
||||
import type PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte'
|
||||
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
|
||||
import {
|
||||
createSession,
|
||||
findEmptyLandingSession,
|
||||
getEffectiveWorkspaceId,
|
||||
isTearingDownOpenSession,
|
||||
opensOnHome,
|
||||
selectSession,
|
||||
sessionInCurrentFamily,
|
||||
sessionPageHref,
|
||||
@@ -51,7 +50,8 @@
|
||||
type SessionPreviewTab
|
||||
} from '$lib/components/sessions/sessionState.svelte'
|
||||
import { withWorkspaceParam } from '$lib/components/sessions/sessionMode.svelte'
|
||||
import { enterSessionMode } from '$lib/components/sessions/sessionSwitch.svelte'
|
||||
import { openDraftOnHome, resumeAiSessions } from '$lib/components/sessions/sessionSwitch.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
|
||||
import {
|
||||
roleCapabilities,
|
||||
@@ -65,12 +65,8 @@
|
||||
listRuntimes
|
||||
} from '$lib/components/sessions/sessionRuntime.svelte'
|
||||
import { markSessionSeen } from '$lib/components/sessions/sessionUnread.svelte'
|
||||
import { markSessionRecovered } from '$lib/components/sessions/sessionRecoveryNotice.svelte'
|
||||
import {
|
||||
isGlobalAiEnabled,
|
||||
clearSessionsBetaOptOut,
|
||||
sessionsAllowedFor
|
||||
} from '$lib/components/copilot/chat/global/gate'
|
||||
import { isGlobalAiEnabled, sessionsAllowedFor } from '$lib/components/copilot/chat/global/gate'
|
||||
import { activateAiSessions } from '$lib/components/sessions/sidebarList.svelte'
|
||||
import { setToolCompletionListener } from '$lib/components/copilot/chat/shared'
|
||||
import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte'
|
||||
import { previewTargetForSessionTarget } from '$lib/components/sessions/sessionPreviewTabs.svelte'
|
||||
@@ -94,7 +90,8 @@
|
||||
tabsToReload,
|
||||
viewerTabsToReload
|
||||
} from '$lib/components/sessions/previewReload'
|
||||
import { isPreviewListPath, barePath, agentPagePath } from '$lib/components/sessions/previewPaths'
|
||||
import { onPreviewFrameMessage } from '$lib/components/sessions/previewFrameMessages'
|
||||
import { agentPagePath } from '$lib/components/sessions/previewPaths'
|
||||
import { listWorkspaceAgents } from '$lib/components/sessions/workspaceAgents'
|
||||
import {
|
||||
leafKeyFor,
|
||||
@@ -117,14 +114,14 @@
|
||||
const embedded = typeof window !== 'undefined' && window.self !== window.top
|
||||
|
||||
// Warm the lazily-loaded editor views (see PreviewTabHost) once the page is
|
||||
// idle: entering session mode stays instant, and by the time the user opens
|
||||
// idle: opening a session stays instant, and by the time the user opens
|
||||
// an editor tab its chunk is usually already cached. Sequential so the
|
||||
// prefetch trickles instead of fanning out four heavy graphs at once.
|
||||
$effect(() => {
|
||||
if (embedded || !globalEnabled) return
|
||||
// Once the chain has started, cancelling the idle handle no longer helps —
|
||||
// the disposed check between imports is what stops a user who left session
|
||||
// mode from pulling the remaining graphs on whatever page they went to.
|
||||
// the disposed check between imports is what stops a user who left the
|
||||
// session from pulling the remaining graphs on whatever page they went to.
|
||||
// (An import already in flight can't be aborted; only the tail is skipped.)
|
||||
let disposed = false
|
||||
const prefetch = async () => {
|
||||
@@ -178,11 +175,10 @@
|
||||
})
|
||||
|
||||
// Family reconcile: a workspace switch can land this page with no session
|
||||
// selected or with another family's session in the URL (the sidebar picker's
|
||||
// selected or with another family's session in the URL (the workspace menu's
|
||||
// link navigation keeps the route), and a chat must not bleed across
|
||||
// families. Re-enter session mode scoped to the active family: keep the open
|
||||
// chat when it belongs there, else its most recent active session, else a
|
||||
// fresh one. A `session` that resolves to nothing is left to the
|
||||
// families. Both resume the last session opened, within the active family.
|
||||
// A `session` that resolves to nothing is left to the
|
||||
// recovery effect below.
|
||||
$effect(() => {
|
||||
if (embedded || !sessionState.hydrated) return
|
||||
@@ -195,15 +191,14 @@
|
||||
$workspaceStore
|
||||
$userWorkspaces
|
||||
const current = activeSession
|
||||
const shouldReenter = current ? !sessionInCurrentFamily(current) : !requestsSession
|
||||
if (!shouldReenter) return
|
||||
untrack(() => void enterSessionMode({ replace: true }))
|
||||
const leaves = current ? !sessionInCurrentFamily(current) : !requestsSession
|
||||
if (!leaves) return
|
||||
untrack(() => void resumeAiSessions({ replace: true }))
|
||||
})
|
||||
|
||||
// Held across the swap so the session layout mounts once, after the navigation
|
||||
// settles: mounting the panes mid-navigation makes Splitpanes miss the collapsed
|
||||
// pane's `maxSize: 0` and leave it open.
|
||||
let recovering = $state(false)
|
||||
// Set once this page is on its way to Home, so no session layout mounts for the
|
||||
// moment it is still on screen.
|
||||
let leaving = $state(false)
|
||||
|
||||
// Bounds the wait for the workspace list the guard above needs. The list can
|
||||
// fail to arrive for good, and a spinner that never resolves is a worse
|
||||
@@ -215,20 +210,24 @@
|
||||
return () => clearTimeout(handle)
|
||||
})
|
||||
|
||||
// The URL names a session this browser doesn't hold. Land on an empty one,
|
||||
// never the most recent: an existing conversation would read as a successful
|
||||
// load. `recovering` also guards re-entry: recovery mutates the session list
|
||||
// this effect tracks, while the URL that would stop it only updates on `goto`.
|
||||
// The URL names a session this browser doesn't hold. Say so and go to Home rather
|
||||
// than open another session in its place, which would read as a successful load.
|
||||
// The toast names no cause: deleted, another browser, cleared site data and a
|
||||
// damaged link are indistinguishable from here.
|
||||
$effect(() => {
|
||||
if (embedded || !globalEnabled || !sessionsAllowedFor(!$roleCapabilities.code)) return
|
||||
if (!sessionState.hydrated || recovering) return
|
||||
if (!sessionState.hydrated || leaving) return
|
||||
// A deliberate delete removes the open session ahead of its own navigation.
|
||||
// Claiming that gap would take over the URL and tell the user the session
|
||||
// they just deleted couldn't be found.
|
||||
if (isTearingDownOpenSession()) return
|
||||
if ($usersWorkspaceStore === undefined && !workspaceListOverdue) return
|
||||
if (!requestsSession || activeSession) return
|
||||
untrack(() => void recoverToNewSession())
|
||||
untrack(() => {
|
||||
leaving = true
|
||||
sendUserToast("We couldn't find that session")
|
||||
void goto('/', { replaceState: true })
|
||||
})
|
||||
})
|
||||
|
||||
// Touch the runtime for the active session so it gets created on first visit
|
||||
@@ -249,6 +248,13 @@
|
||||
if (lastArrivedSessionId === session.id) return
|
||||
lastArrivedSessionId = session.id
|
||||
untrack(() => {
|
||||
// Judged once, on arrival: a hand-off's draft is unsent until its first send
|
||||
// commits, a moment after it has claimed its auto-send.
|
||||
if (opensOnHome(session)) {
|
||||
leaving = true
|
||||
void openDraftOnHome(session.id, { replace: true })
|
||||
return
|
||||
}
|
||||
// Keep currentSessionId in sync with the URL so consumers react to
|
||||
// deep links the same way they react to picker clicks.
|
||||
selectSession(session.id)
|
||||
@@ -308,25 +314,6 @@
|
||||
untrack(() => markSessionSeen(id, count))
|
||||
})
|
||||
|
||||
async function recoverToNewSession() {
|
||||
recovering = true
|
||||
try {
|
||||
// Prefer an existing empty session over stacking another blank onto the
|
||||
// sidebar: createSession reuses only its own in-memory drafts, so one
|
||||
// persisted by any other touch (a workspace pick, a preview tab) would
|
||||
// be passed over.
|
||||
const target = findEmptyLandingSession() ?? createSession()
|
||||
selectSession(target.id)
|
||||
markSessionRecovered(target.id)
|
||||
await goto(sessionPageHref(target.id), {
|
||||
replaceState: true
|
||||
})
|
||||
await tick()
|
||||
} finally {
|
||||
recovering = false
|
||||
}
|
||||
}
|
||||
|
||||
// Preview panel: a tiny tabbed browser over Windmill. Every tab stays mounted
|
||||
// (stacked, visibility-toggled, like the warm chat sessions) so switching
|
||||
// preserves each previewed page's scroll/edit state. The tab model lives on
|
||||
@@ -974,42 +961,7 @@
|
||||
// Retarget the active tab — the navigating frame is the visible one the user
|
||||
// just clicked in — which flips its seam from iframe → live editor.
|
||||
$effect(() => {
|
||||
function onMessage(e: MessageEvent) {
|
||||
if (e.origin !== window.location.origin) return
|
||||
const d = e.data
|
||||
if (!d) return
|
||||
// A preview frame navigating to an editor route: re-point the active tab to
|
||||
// the live in-process editor instead of booting a second one in the frame.
|
||||
if (d.type === 'wm.session.openEditor') {
|
||||
if (d.kind !== 'script' && d.kind !== 'flow' && d.kind !== 'raw_app') return
|
||||
if (typeof d.path !== 'string') return
|
||||
const item: WorkspaceItem =
|
||||
d.kind === 'raw_app'
|
||||
? { kind: 'app', raw_app: true, path: d.path, summary: '' }
|
||||
: { kind: d.kind, path: d.path, summary: '' }
|
||||
owner?.navigate({ type: 'item', item })
|
||||
return
|
||||
}
|
||||
// A preview frame navigating to a list page: re-point the active tab to the list
|
||||
// mounted in process, whose rows open as tabs of their own.
|
||||
if (d.type === 'wm.session.openList') {
|
||||
if (typeof d.href !== 'string' || !isPreviewListPath(barePath(d.href))) return
|
||||
owner?.navigate({ type: 'page', href: d.href, label: previewLocationLabel(d.href) })
|
||||
return
|
||||
}
|
||||
// A job clicked inside a preview tab: open the run detail in a NEW tab so the
|
||||
// originating page (e.g. Runs) stays put. open() focuses an existing tab for
|
||||
// the same run rather than duplicating it.
|
||||
if (d.type === 'wm.session.openRun') {
|
||||
if (typeof d.href !== 'string') return
|
||||
owner?.open({
|
||||
type: 'page',
|
||||
href: d.href,
|
||||
label: typeof d.label === 'string' ? d.label : 'Run'
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
const onMessage = (e: MessageEvent) => onPreviewFrameMessage(e, owner)
|
||||
window.addEventListener('message', onMessage)
|
||||
return () => window.removeEventListener('message', onMessage)
|
||||
})
|
||||
@@ -1112,22 +1064,18 @@
|
||||
<div class="p-8 flex flex-col items-start gap-3 text-secondary text-sm">
|
||||
<p class="text-primary font-medium">AI Sessions are deactivated</p>
|
||||
<p>You switched back to the legacy chat. Activate AI Sessions (beta) to open this page.</p>
|
||||
<Button unifiedSize="sm" onclick={() => clearSessionsBetaOptOut('/sessions')}>
|
||||
Activate AI Sessions
|
||||
</Button>
|
||||
<Button unifiedSize="sm" onclick={activateAiSessions}>Activate AI Sessions</Button>
|
||||
</div>
|
||||
{:else if !sessionState.hydrated}
|
||||
<!-- Sessions hydrate from IndexedDB after the user resolves; until then an
|
||||
empty list means "loading", so recovery below must not fire and strand
|
||||
the user in a new session while their own is still arriving. -->
|
||||
empty list means "loading", so recovery must not fire and send the user
|
||||
to Home while their session is still arriving. -->
|
||||
<div class="flex-1 flex items-center justify-center">
|
||||
<Loader2 class="animate-spin" />
|
||||
</div>
|
||||
{:else if !requestsSession}
|
||||
<div class="p-8 text-secondary">No session selected — pick one in the sidebar.</div>
|
||||
{:else if !activeSession || recovering}
|
||||
<!-- A tick while recovery swaps in an empty session, or the length of a
|
||||
fork teardown's HTTP round trip while a delete holds recovery off. -->
|
||||
{:else if !requestsSession || !activeSession || leaving}
|
||||
<!-- On the way to Home, or the length of a fork teardown's HTTP round trip
|
||||
while a delete holds recovery off. -->
|
||||
<div class="flex-1 flex items-center justify-center">
|
||||
<Loader2 class="animate-spin" />
|
||||
</div>
|
||||
@@ -1349,7 +1297,7 @@
|
||||
<Loader2 class="animate-spin" />
|
||||
</div>
|
||||
{:else if aiHiddenVerdict}
|
||||
<!-- The workspace hid the assistant, and the sidebar switch with it, so only a
|
||||
<!-- The workspace hid the assistant, and the sidebar's sessions with it, so only a
|
||||
direct URL or a session acting on such a workspace lands here. -->
|
||||
<!-- Centred like the loader above: the page header overlays this pane's top edge. -->
|
||||
<div
|
||||
|
||||
Reference in New Issue
Block a user