feat: home's ai side opens its composer, lists sessions, previews items

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-26 03:15:24 -07:00
co-authored by Claude Opus 5.5
parent 1ba8d1f294
commit 4df09f0220
14 changed files with 407 additions and 76 deletions
@@ -590,8 +590,7 @@
let composerEl: HTMLDivElement | undefined = $state()
let composerOpened = $state(false)
// 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.
@@ -605,7 +604,7 @@
const composerCollapsed = $derived(
starterLayout &&
!disabled &&
!starter?.fewItems &&
!starter?.restsOpen &&
!composerOpened &&
(aiChatInput ? aiChatInput.isDraftEmpty() : seededDraftEmpty)
)
@@ -145,5 +145,5 @@ async function fetchItemCount(workspace: string): Promise<number> {
}
/** What turns an empty chat into Home's block that starts a session, collapsed to one line at
* rest unless `fewItems`. */
export type ChatStarter = { suggestions: ComposerSuggestion[]; fewItems: boolean }
* rest unless `restsOpen`. */
export type ChatStarter = { suggestions: ComposerSuggestion[]; restsOpen: boolean }
@@ -112,6 +112,10 @@
)
let hero = $derived(showComposer && !removed)
// Beside the session list Home is the AI side's page: the composer rests open there. Beside
// the workspace nav it rests on one line.
const sessionsListed = $derived(homeSidebarList.val === 'sessions')
</script>
<div class="w-full {hero ? 'mt-2' : 'mb-1'}">
@@ -141,7 +145,9 @@
<HomeSessionStarter
onShown={() => (shownForRoot = $currentWorkspaceRootId)}
{placeholder}
onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)}
onSettled={(height) =>
rememberComposerHeight($workspaceStore ?? undefined, sessionsListed, height)}
restsOpen={sessionsListed}
/>
{/key}
</div>
@@ -153,7 +159,7 @@
</div>
{#snippet placeholder()}
<HomeComposerSkeleton height={composerHeight($workspaceStore ?? undefined)} />
<HomeComposerSkeleton height={composerHeight($workspaceStore ?? undefined, sessionsListed)} />
{/snippet}
<HomeConnectDrawer bind:this={homeConnectDrawer} />
@@ -10,14 +10,30 @@
const SUGGESTIONS_ROW = 36
const OPEN_BOX_MIN = 78
/** The height Home's composer took when it last appeared in this workspace. */
export function composerHeight(workspace: string | undefined): number | undefined {
const stored = workspace ? Number(getLocalSetting(HEIGHT_SETTING + workspace)) : NaN
// The composer rests open beside the session list and on one line beside the workspace nav,
// so each side of the sidebar switch keeps its own height.
function heightSetting(workspace: string, sessionsListed: boolean): string {
return HEIGHT_SETTING + workspace + (sessionsListed ? ':sessions' : '')
}
/** The height Home's composer took when it last appeared in this workspace, beside this list. */
export function composerHeight(
workspace: string | undefined,
sessionsListed: boolean
): number | undefined {
const stored = workspace
? Number(getLocalSetting(heightSetting(workspace, sessionsListed)))
: NaN
return Number.isFinite(stored) && stored > 0 ? stored : undefined
}
export function rememberComposerHeight(workspace: string | undefined, height: number) {
if (workspace && height > 0) storeLocalSetting(HEIGHT_SETTING + workspace, String(height))
export function rememberComposerHeight(
workspace: string | undefined,
sessionsListed: boolean,
height: number
) {
if (workspace && height > 0)
storeLocalSetting(heightSetting(workspace, sessionsListed), String(height))
}
</script>
@@ -0,0 +1,177 @@
<script module lang="ts">
import { preloadComponent } from '$lib/utils/preloadComponent.svelte'
// A tab renders a whole item through most of AIChat's code, monaco among it, which Home's
// static imports may not reach.
const previewTabHostComponent = preloadComponent(
() => import('$lib/components/sessions/PreviewTabHost.svelte')
)
</script>
<script lang="ts">
import { MonitorPlay, PanelRightClose, PanelRightOpen } from 'lucide-svelte'
import { SvelteSet } from 'svelte/reactivity'
import { goto } from '$lib/navigation'
import { Button } from '$lib/components/common'
import DraggableTabs, { type TabItem } from '$lib/components/common/tabs/DraggableTabs.svelte'
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
import { homeComposerContext } from '$lib/components/sessions/homeComposerContext.svelte'
import { onPreviewFrameMessage } from '$lib/components/sessions/previewFrameMessages'
import { previewLocationLabel } from '$lib/components/sessions/previewRouter'
import { withWorkspaceParam } from '$lib/components/sessions/sessionMode.svelte'
import {
sessionState,
type SessionPreviewTab
} from '$lib/components/sessions/sessionState.svelte'
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
import type { WorkspaceItem } from '$lib/components/workspacePicker'
import { workspaceStore } from '$lib/stores'
// Home's side of the session page's preview panel: the tabs of the draft in Home's composer,
// so a send hands them to the session page with the rest of the draft. Kept to tabs, close
// and collapse; the pickers and full screen are the session page's.
const runtime = $derived(homeComposerContext.runtime)
const owner: SessionPreviewTabs | undefined = $derived(runtime?.previewTabs)
const session = $derived(sessionState.sessions.find((s) => s.id === runtime?.sessionId))
const shown = $derived(!!owner && !owner.collapsed)
const isDarkMode = useIsDarkMode()
// The active tab's content is mounted, and so are the last few left through the strip: each
// is a whole Windmill page or editor.
const MAX_MOUNTED_TABS = 5
const shownTabIds = new SvelteSet<string>()
function noteShown(id: string) {
shownTabIds.delete(id)
shownTabIds.add(id)
while (shownTabIds.size > MAX_MOUNTED_TABS) {
const oldest = shownTabIds.values().next().value
if (oldest === undefined || oldest === id) break
shownTabIds.delete(oldest)
}
}
function label(tab: SessionPreviewTab): string {
return tab.friendlyLabel ?? previewLocationLabel(tab.loc || tab.url)
}
const tabItems = $derived<TabItem[]>(
(owner?.tabs ?? []).map((t) => ({ id: t.id, label: label(t), title: label(t) }))
)
function selectTab(id: string) {
if (owner?.activeId) noteShown(owner.activeId)
owner?.select(id)
}
function closeTab(id: string) {
owner?.close(id)
shownTabIds.delete(id)
}
function navigateEditorTo(item: WorkspaceItem) {
// A drag-and-drop app has no preview wrapper: it opens in its own editor.
if (item.kind === 'app' && !item.raw_app) {
void goto(withWorkspaceParam(`/apps/edit/${item.path}`, $workspaceStore ?? undefined))
return
}
owner?.navigate({ type: 'item', item })
}
function observeLocation(tab: SessionPreviewTab, frame: HTMLIFrameElement) {
try {
const win = frame.contentWindow
if (!win) return
const observe = () => {
try {
owner?.observeLocation(
tab.id,
win.location.pathname + win.location.search + win.location.hash
)
} catch {
// Mid-navigation the location can throw; the tab keeps its last one.
}
}
observe()
win.addEventListener('hashchange', observe)
win.addEventListener('popstate', observe)
} catch {
// Same as above.
}
}
</script>
<svelte:window onmessage={(e) => shown && onPreviewFrameMessage(e, owner)} />
{#if owner && !shown}
<PageHeaderContent actions={openButton} />
{/if}
{#snippet openButton()}
<Button
variant="subtle"
unifiedSize="sm"
startIcon={{ icon: PanelRightOpen }}
title="Open side panel"
onclick={() => owner?.setCollapsed(false)}
>
Open side panel
</Button>
{/snippet}
{#if owner && shown}
<div class="w-[45%] min-w-80 shrink-0 h-full p-2 pl-0 flex flex-col min-h-0">
<div
class="flex flex-col flex-1 min-h-0 overflow-hidden relative bg-surface rounded-md border border-light"
>
<button
type="button"
onclick={() => owner?.setCollapsed(true)}
title="Collapse preview"
aria-label="Collapse preview"
class="absolute top-1 left-1 z-30 inline-flex items-center justify-center w-6 h-6 rounded text-tertiary hover:text-primary hover:bg-surface-hover"
>
<PanelRightClose size={14} />
</button>
<DraggableTabs
tabs={tabItems}
activeId={owner.activeId}
onSelect={selectTab}
onClose={closeTab}
onReorder={(next) => owner?.reorder(next.map((t) => t.id))}
size="sm"
class="session-preview-tab-strip h-8 border-b border-light bg-surface-secondary/50 pl-9 pr-2"
/>
<div class="relative flex-1 min-h-0">
{#if previewTabHostComponent.current}
{@const TabHost = previewTabHostComponent.current}
{#each owner.tabs as tab (tab.id)}
{@const active = tab.id === owner.activeId}
<TabHost
{tab}
{session}
{runtime}
{active}
mounted={active || shownTabIds.has(tab.id)}
label={label(tab)}
darkMode={isDarkMode.val}
onNavigate={navigateEditorTo}
onSeeDetails={(item) => owner?.open({ type: 'item', item, mode: 'view' })}
onLoad={(frame) => observeLocation(tab, frame)}
/>
{/each}
{/if}
{#if owner.tabs.length === 0}
<div
class="absolute inset-0 flex flex-col items-center justify-center gap-2 text-center px-6 bg-surface"
>
<MonitorPlay size={28} class="text-tertiary" />
<span class="text-sm font-medium text-secondary">No preview open</span>
<span class="text-xs text-tertiary max-w-xs">
Click a script, flow or app on Home to preview it here.
</span>
</div>
{/if}
</div>
</div>
</div>
{/if}
@@ -10,6 +10,7 @@
GitFork,
LayoutGrid,
List,
MessagesSquare,
Pen,
Star as StarIcon,
StarOff,
@@ -39,6 +40,14 @@
import HomeSectionLabel from './HomeSectionLabel.svelte'
import HomeSectionCount from './HomeSectionCount.svelte'
import { QUICK_ACCESS_ROWS, homeQuickAccessSettings } from './homeQuickAccessSettings.svelte'
import { homeSidebarList } from '$lib/components/sessions/sidebarList.svelte'
import {
getEffectiveWorkspaceId,
homeDraft,
sessionLastActivityAt,
sessionState
} from '$lib/components/sessions/sessionState.svelte'
import { openSession } from '$lib/components/sessions/sessionSwitch.svelte'
interface Props {
workspace: string
@@ -188,6 +197,25 @@
]
}
// Beside the session list the workspace's last sessions take the favorites' place: sent ones
// and drafts with text, not Home's own draft, which is the composer above.
const sessionsSide = $derived(homeSidebarList.val === 'sessions')
const showFavorites = $derived(homeQuickAccessSettings.showFavorites && !sessionsSide)
let recentSessions = $derived(
sessionsSide
? sessionState.sessions
.filter(
(s) =>
!s.archived &&
s.id !== homeDraft.id &&
(!!s.workspace_id || !!s.draftPrompt?.trim()) &&
getEffectiveWorkspaceId(s) === workspace
)
.sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))
.slice(0, RECENT_COUNT)
: []
)
// Assets are favorites too, but they open in the database manager rather than at a page,
// so they stay in the sidebar's menu.
let favorites: Entry[] = $derived(
@@ -198,7 +226,7 @@
// Favorites first, then what was opened lately; a starred item is listed once, as a favorite.
// With the favorites turned off, a starred item opened lately shows among the recent ones.
let recentAll: Entry[] = $derived.by(() => {
const { showFavorites, showRecent } = homeQuickAccessSettings
const { showRecent } = homeQuickAccessSettings
const starred = new Set(
showFavorites ? favorites.map((f) => `${asStarKind(f.kind)}/${f.path}`) : []
)
@@ -217,7 +245,7 @@
let recentLimit = $state(RECENT_COUNT)
let recentMore = $derived(Math.max(0, recentAll.length - recentLimit))
let entries: { item: Entry; favorite: boolean }[] = $derived([
...(homeQuickAccessSettings.showFavorites ? favorites : []).map((item) => ({
...(showFavorites ? favorites : []).map((item) => ({
item,
favorite: true
})),
@@ -228,7 +256,8 @@
// (the only way to turn the list back on) would leave with it.
let emptiedBySettings = $derived(
entries.length === 0 &&
((!homeQuickAccessSettings.showFavorites && favorites.length > 0) ||
recentSessions.length === 0 &&
((!showFavorites && favorites.length > 0) ||
(!homeQuickAccessSettings.showRecent && recentItems.list(workspace).length > 0))
)
@@ -251,7 +280,7 @@
}
// Everything the lists hold, the recent ones not loaded yet included.
let favoriteCount = $derived(homeQuickAccessSettings.showFavorites ? favorites.length : 0)
let favoriteCount = $derived(showFavorites ? favorites.length : 0)
let recentCount = $derived(recentAll.length)
// The cards fill one screen at a time, row by row, and the next screen scrolls in from the
@@ -259,7 +288,7 @@
// whole columns. The column counts follow the `auto-cols` breakpoints below.
let innerWidth = $state(1280)
let cols = $derived(innerWidth >= 1024 ? 3 : innerWidth >= 640 ? 2 : 1)
let cellCount = $derived(entries.length + (recentMore > 0 ? 1 : 0))
let cellCount = $derived(recentSessions.length + entries.length + (recentMore > 0 ? 1 : 0))
// Fewer rows when there aren't enough cards to fill a screen.
let rows = $derived(Math.min(homeQuickAccessSettings.rows, Math.ceil(cellCount / cols)))
@@ -403,11 +432,17 @@
<!-- Held back until the favorites are in: the recent cards are ready first, and the favorites
landing in front of them would push every card over. -->
{#if favoriteManager.loadedFor === workspace && (entries.length > 0 || emptiedBySettings) && !hidden}
{#if favoriteManager.loadedFor === workspace && (entries.length > 0 || recentSessions.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]">
<div class="flex items-center gap-1 -my-1">
<HomeSectionLabel>
{#if recentSessions.length > 0}
Sessions <HomeSectionCount count={recentSessions.length} />
{/if}
{#if recentSessions.length > 0 && (favoriteCount > 0 || recentCount > 0)}
<span class="text-hint">·</span>
{/if}
{#if favoriteCount > 0}
Favorites <HomeSectionCount count={favoriteCount} />
{/if}
@@ -422,9 +457,9 @@
<DropdownV2 items={sectionMenu} size="xs" fixedHeight={false} />
</div>
</div>
{#if entries.length === 0}
{#if entries.length === 0 && recentSessions.length === 0}
<p class="text-2xs text-hint">
{homeQuickAccessSettings.showFavorites
{showFavorites
? 'No favorites yet. Star a script, flow or app to keep it here.'
: 'Nothing opened lately in this browser.'}
</p>
@@ -441,15 +476,37 @@
class="grid gap-2 overflow-x-auto no-scrollbar px-px -mx-px auto-cols-[85%] sm:auto-cols-[calc((100%_-_0.5rem)/2)] lg:auto-cols-[calc((100%_-_1rem)/3)]"
style:grid-template-rows="repeat({rows}, auto)"
>
{#each entries as { item, favorite }, i (item.kind + '/' + item.path)}
{#each recentSessions as session, i (session.id)}
{@const at = cellPosition(i)}
<div class="min-w-0" style:grid-row={at.row} style:grid-column={at.column}>
<button
type="button"
class="w-full flex items-center gap-2 rounded-md border border-light bg-surface-tertiary hover:bg-surface-hover transition-colors min-w-0 px-2.5 py-2 text-left"
onclick={() => openSession(session)}
>
<MessagesSquare size={14} class="shrink-0 text-ai" />
<span class="flex-1 text-2xs font-normal text-primary truncate"
>{session.summary ?? 'Untitled session'}</span
>
<span class="shrink-0 text-2xs text-secondary">
<TimeAgo
date={new Date(sessionLastActivityAt(session)).toISOString()}
compact
noSeconds
/>
</span>
</button>
</div>
{/each}
{#each entries as { item, favorite }, i (item.kind + '/' + item.path)}
{@const at = cellPosition(recentSessions.length + i)}
<div class="min-w-0" style:grid-row={at.row} style:grid-column={at.column}>
{@render card(item, favorite)}
</div>
{/each}
{#if recentMore > 0}
{@const next = Math.min(recentMore, RECENT_COUNT)}
{@const at = cellPosition(entries.length)}
{@const at = cellPosition(recentSessions.length + entries.length)}
<div class="min-w-0" style:grid-row={at.row} style:grid-column={at.column}>
<Button
variant="subtle"
@@ -66,6 +66,7 @@
import BulkActionsBar from './BulkActionsBar.svelte'
import { HomeSelection, setHomeSelection, toBulkItem } from './homeSelection.svelte'
import HomeQuickAccess from './HomeQuickAccess.svelte'
import { homeSidebarList } from '../sessions/sidebarList.svelte'
const editRights = useEditRights()
@@ -1982,7 +1983,8 @@
<!-- Same gate the old create actions used: hidden from operators and in workspaces
whose direct-deploy protection cleared showEditButtons (NoDirectDeployAlert), since
the menu itself does no permission check. -->
{#if canCreateHere}
<!-- Beside the session list items are made by asking the composer above. -->
{#if canCreateHere && homeSidebarList.val !== 'sessions'}
<!-- No hub entry where the instance has the hub turned off: the same setting the
script and flow hub pickers observe. Nor for a builder: a hub project brings
scripts and apps along. -->
@@ -27,13 +27,20 @@
// 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. `restsOpen` keeps the composer open
// at rest whatever the workspace holds; a workspace small enough that the composer is the
// page's main way in keeps it open anyway.
let {
onShown,
placeholder,
onSettled
}: { onShown?: () => void; placeholder?: Snippet; onSettled?: (height: number) => void } =
$props()
onSettled,
restsOpen = false
}: {
onShown?: () => void
placeholder?: Snippet
onSettled?: (height: number) => void
restsOpen?: boolean
} = $props()
const initialSession = homeStarterSession()
const sessionId = initialSession.id
@@ -76,8 +83,12 @@
onShown?.()
// 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({
attach: async (element) => {
await aiChat?.attachContext(element)
},
focus: () => aiChat?.focusInput(),
runtime
})
})
</script>
@@ -97,7 +108,10 @@
onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)}
initialAttachments={getSessionDraftAttachments(sessionId)}
onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)}
starter={{ suggestions: starterPrompts.suggestions, fewItems: starterPrompts.fewItems }}
starter={{
suggestions: starterPrompts.suggestions,
restsOpen: restsOpen || starterPrompts.fewItems
}}
viewTransitionNames
{onSent}
/>
@@ -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,10 @@ 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 = { attach: Attach; focus: () => 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 +38,25 @@ 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)
},
focus(): void {
registered?.focus()
},
/** 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
}
}
}
@@ -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'
})
}
}
@@ -1169,9 +1169,9 @@ function newTransientSession(pending: string | undefined): Session {
/** Whether a session opens in Home's composer rather than on a page of its own: unsent, and
* neither about an item (it carries preview tabs, which need the session page's panel) nor
* armed to send itself on arrival. */
* armed to send itself on arrival. Tabs opened from Home's own panel keep its draft there. */
export function opensOnHome(s: Session): boolean {
return !s.workspace_id && !s.previewTabs?.length && !autoSendIsFresh(s)
return !s.workspace_id && (!s.previewTabs?.length || s.id === homeDraft.id) && !autoSendIsFresh(s)
}
/** The unsent session Home's composer shows: the one Home last held, else the family's
@@ -23,6 +23,7 @@ import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte'
import { homeSidebarList, type SidebarList } from './sidebarList.svelte'
import { hrefAfterWorkspaceSwitch } 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'
@@ -60,6 +61,9 @@ export function noteArrival(url: URL): void {
export function swapHomeList(list: SidebarList, homeHref: string): void {
homeSidebarList.val = list
if (list === 'workspace') rememberWorkspacePage(homeHref)
// The AI side of Home is its composer: going there puts the caret in it. After the click
// has played out, or the switch button it landed on takes focus back.
else setTimeout(() => homeComposerContext.focus(), 0)
}
// The session last opened, else the family's most recently used one. Scoped to the
@@ -121,6 +125,13 @@ export async function openNewSession(workspaceId?: string): Promise<void> {
await toHome(blankHomeDraft().id)
}
/** A session picked from a list: an unsent draft in Home's composer, any other on its page. */
export async function openSession(session: Session): Promise<void> {
if (opensOnHome(session)) return openDraftOnHome(session.id)
selectSession(session.id)
await goto(sessionPageHref(session.id))
}
/** An unsent draft, opened in Home's composer. `replace` for a redirect off the sessions
* page, where Back must not return to the URL that bounced here. */
export async function openDraftOnHome(id: string, opts?: { replace?: boolean }): Promise<void> {
@@ -29,6 +29,10 @@
import { useSearchParams } from '$lib/svelte5UtilsKit.svelte'
import { z } from 'zod'
import HomeAIChat from '$lib/components/home/HomeAIChat.svelte'
import HomePreviewPanel from '$lib/components/home/HomePreviewPanel.svelte'
import { homeSidebarList } from '$lib/components/sessions/sidebarList.svelte'
import { homeComposerContext } from '$lib/components/sessions/homeComposerContext.svelte'
import { parsePreviewItemRoute } from '$lib/components/sessions/previewPaths'
import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate'
import { onMount, untrack } from 'svelte'
import OperatorTour from '$lib/components/tutorials/OperatorTour.svelte'
@@ -150,6 +154,24 @@
if (await hasSeenOperatorTour()) return
startTour()
})
// Beside the session list, a script, flow or app opens in the preview beside Home, as the
// draft's own tab, instead of taking Home's place. A modified click still opens it as a page.
function openItemInPreview(e: MouseEvent) {
if (homeSidebarList.val !== 'sessions') return
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
const owner = homeComposerContext.runtime?.previewTabs
const href = (e.target as Element | null)?.closest('a[href]')?.getAttribute('href')
const route = href ? parsePreviewItemRoute(href) : null
if (!owner || !route) return
e.preventDefault()
e.stopPropagation()
owner.open({
type: 'item',
item: { kind: route.kind, raw_app: route.raw_app, path: route.itemPath, summary: '' },
mode: route.mode
})
}
</script>
<Drawer bind:this={codeViewer} size="900px">
@@ -290,10 +312,12 @@
<NoDirectDeployAlert onUpdateCanEditStatus={(v) => (showCreateButtons = v)} />
{/snippet}
<div class="flex flex-row w-full h-full min-h-0">
<div
bind:this={pageEl}
class="{fadeIn ? 'wm-page-in' : ''} flex flex-col w-full h-full overflow-y-auto items-center"
class="{fadeIn ? 'wm-page-in' : ''} flex flex-col flex-1 min-w-0 h-full overflow-y-auto items-center"
style="scrollbar-gutter: stable both-edges;"
onclickcapture={openItemInPreview}
>
<!-- 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. -->
@@ -397,6 +421,10 @@
<ItemsList bind:subtab showEditButtons={showCreateButtons} />
{/if}
</div>
{#if homeSidebarList.val === 'sessions'}
<HomePreviewPanel />
{/if}
</div>
{#if !$roleCapabilities.code}
<OperatorTour bind:this={operatorTour} />
@@ -94,7 +94,7 @@
tabsToReload,
viewerTabsToReload
} from '$lib/components/sessions/previewReload'
import { isPreviewListPath, barePath } from '$lib/components/sessions/previewPaths'
import { onPreviewFrameMessage } from '$lib/components/sessions/previewFrameMessages'
import {
leafKeyFor,
loadKind,
@@ -894,42 +894,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)
})