feat: redesign home composer and items list

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-19 02:02:22 -07:00
co-authored by Claude Opus 5.5
parent 6fe331a396
commit 08ae81da4c
46 changed files with 1343 additions and 763 deletions
+27 -6
View File
@@ -427,21 +427,42 @@ input[type='time']::-webkit-calendar-picker-indicator {
z-index: -10;
}
/* Row actions shown only for the row being used: hovered, tabbed into, keyboard-selected, or
with one of its menus open. Opacity rather than visibility, so Tab still reaches them. Focus
only when visible: a menu hands focus back to its trigger on close, and a mouse user would
otherwise keep that row's actions up after leaving it. */
/* A list whose rows are not ruled off from each other (Home's items). Rows mark themselves
with `data-list-row`; their own `border-b` stays for every other list. */
[data-unruled] [data-list-row] {
border-bottom-width: 0 !important;
border-radius: 0.375rem !important;
}
[data-hover-actions] [data-list-row] [data-row-actions] {
opacity: 0;
transition: opacity 100ms;
}
[data-hover-actions] [data-list-row]:hover [data-row-actions],
[data-hover-actions] [data-list-row]:has(:focus-visible) [data-row-actions],
[data-hover-actions] [data-list-row][data-row-keyboard-selected] [data-row-actions],
[data-hover-actions] [data-row-actions]:has([aria-expanded='true']) {
opacity: 1;
}
/* The composer's glide, defined once: the Home ↔ AI Sessions view transition below and the
in-page move on a session's first message (the spacer under AIChatDisplay's composer) both
read it. */
:root {
--composer-glide-duration: 200ms;
--composer-glide-easing: cubic-bezier(0.2, 0, 0, 1);
--composer-glide-duration: 380ms;
--composer-glide-easing: cubic-bezier(0.2, 0.8, 0.2, 1);
}
/* Home ↔ AI Sessions (homeSessionsTransition.svelte.ts). The session heading and composer
glide from where they were to where they land; everything else, Home's list included, is
/* Home ↔ AI Sessions (homeSessionsTransition.svelte.ts). The composer glides from where it
was to where it lands; everything else, Home's list and the session's greeting included, is
the page cross-fading, kept short. The pseudo-elements hang off :root itself, so no space
before `::view-transition-*`: with one, the selector looks for a descendant and never
matches. */
:root[data-home-sessions-transition]::view-transition-group(session-heading),
:root[data-home-sessions-transition]::view-transition-group(session-composer) {
:root[data-home-sessions-transition]::view-transition-group(composer) {
animation-duration: var(--composer-glide-duration);
animation-timing-function: var(--composer-glide-easing);
}
@@ -801,14 +801,18 @@
<div class="py-1 p-2 overflow-y-auto" onmousedown={(e) => e.stopPropagation()}>
{#if !currentTag || !schema[currentTag]}
{#if presets.length}
<div class="text-xs px-2 my-2 font-bold">Presets</div>
<div class="text-2xs uppercase tracking-wide font-semibold text-secondary px-2 my-2">
Presets
</div>
<div class="mb-3 px-2 flex gap-2 flex-wrap max-h-24 overflow-y-auto">
{#each presets as preset}
{@render presetTag(preset)}
{/each}
</div>
{/if}
<div class="text-xs px-2 my-2 font-bold">Filters</div>
<div class="text-2xs uppercase tracking-wide font-semibold text-secondary px-2 my-2">
Filters
</div>
{#each menuItems as item, index}
{#if item.type === 'filter' && item.filterSchema}
{@render menuItem({
@@ -947,18 +951,18 @@
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class={twMerge(
'py-1.5 px-2 rounded-md hover:bg-surface-hover cursor-pointer text-sm flex items-center gap-3',
'py-1.5 px-2 rounded-md hover:bg-surface-hover cursor-pointer text-xs text-primary flex items-center gap-2',
highlighted && 'bg-surface-hover'
)}
onclick={onClick}
>
{#if Icon}
<Icon size={16} class="inline" />
<Icon size={14} class="inline shrink-0" />
{/if}
<div class="inline flex-1 relative min-w-0">
<div class="text-sm ellipsize">{label}</div>
<div class="ellipsize">{label}</div>
{#if description}
<div class="text-xs text-hint">{description}</div>
<div class="text-2xs text-hint">{description}</div>
{/if}
</div>
{#if onNegativeClick}
@@ -1,32 +1,31 @@
<script lang="ts">
import Badge from './common/badge/Badge.svelte'
import LabelBadge from './common/badge/LabelBadge.svelte'
import type { BadgeColor } from './common/badge/model'
import { Folder } from 'lucide-svelte'
interface Props {
labels: string[] | undefined
max?: number
color?: BadgeColor
}
let { labels, max = 3 }: Props = $props()
let { labels, max = 3, color = 'gray' }: Props = $props()
</script>
{#if labels?.length}
<div class="flex items-center gap-0.5">
{#each labels.slice(0, max) as label (label)}
<Badge color="gray" small class="px-1" title="Label inherited from folder: {label}">
<Folder size={10} class="mr-0.5 shrink-0" />
<LabelBadge {color} icon={Folder} title="Label inherited from folder: {label}">
{label}
</Badge>
</LabelBadge>
{/each}
{#if labels.length > max}
<Badge
color="gray"
small
class="px-1"
<LabelBadge
{color}
title={labels
.slice(max)
.map((l) => 'Label inherited from folder: ' + l)
.join('\n')}>+{labels.length - max}</Badge
.join('\n')}>+{labels.length - max}</LabelBadge
>
{/if}
</div>
+5 -2
View File
@@ -10,9 +10,10 @@
summary?: string
workspaceId?: string
size?: number
class?: string
}
let { path, kind, workspaceId, summary, size = 16 }: Props = $props()
let { path, kind, workspaceId, summary, size = 16, class: className = 'p-1' }: Props = $props()
let buttonHover = $state(false)
let starred = $derived(favoriteManager.isStarred(path, kind))
@@ -28,7 +29,9 @@
onclick={preventDefault(onClick)}
onmouseenter={() => (buttonHover = true)}
onmouseleave={() => (buttonHover = false)}
class="p-1"
class={className}
data-starred={starred || undefined}
title={starred ? 'Remove from favorites' : 'Add to favorites'}
>
{#if starred}
{#if buttonHover}
@@ -65,7 +65,8 @@
['dark-indigo']: 'bg-indigo-500 text-indigo-100 dark:bg-indigo-600 dark:text-indigo-200',
['dark-orange']: 'bg-orange-500 text-orange-100 dark:bg-orange-600 dark:text-orange-200',
['dark-violet']: 'bg-violet-500 text-violet-100 dark:bg-violet-600 dark:text-violet-200',
transparent: 'bg-transparent border'
transparent: 'bg-transparent border',
subtle: 'bg-transparent'
}
const selectedColors: Record<BadgeColor, string> = {
@@ -86,7 +87,8 @@
['dark-orange']: 'bg-orange-700 text-orange-100 dark:bg-orange-800 dark:text-orange-200',
['dark-violet']: 'bg-violet-700 text-violet-100 dark:bg-violet-800 dark:text-violet-200',
// Keeps the unselected chip's border, so selecting one does not change its height.
transparent: 'bg-surface-accent-selected text-accent border border-surface-accent-selected'
transparent: 'bg-surface-accent-selected text-accent border border-surface-accent-selected',
subtle: 'bg-surface-accent-selected text-accent'
}
const hovers: Partial<Record<BadgeColor, string>> = {
@@ -106,7 +108,8 @@
['dark-indigo']: 'hover:bg-indigo-600 dark:hover:bg-indigo-700',
['dark-orange']: 'hover:bg-orange-600 dark:hover:bg-orange-700',
['dark-violet']: 'hover:bg-violet-600 dark:hover:bg-violet-700',
transparent: 'hover:bg-surface-hover dark:hover:border-gray-500'
transparent: 'hover:bg-surface-hover dark:hover:border-gray-500',
subtle: 'hover:bg-surface-hover'
}
let badgeClass = $derived(
@@ -0,0 +1,36 @@
<script lang="ts">
import type { Snippet } from 'svelte'
import Badge from './Badge.svelte'
import type { BadgeColor, BadgeIconProps } from './model'
/**
* How a label, an owner or a folder reads wherever an item is tagged with it: the row's own
* labels and Home's quick filters both draw it, so the two cannot drift apart.
*/
interface Props {
icon?: BadgeIconProps['icon']
color?: BadgeColor
title?: string
/** Makes it a filter: clickable, and marked with × once selected. */
onclick?: (event: MouseEvent) => void
selected?: boolean
children?: Snippet
}
let { icon: Icon, color = 'subtle', title, onclick, selected = false, children }: Props = $props()
</script>
<Badge
{color}
{title}
{onclick}
clickable={!!onclick}
{selected}
class="inline-flex items-center gap-1 px-1.5 align-middle"
>
{#if Icon}
<Icon size={12} class="shrink-0" />
{/if}
{@render children?.()}
{#if selected}&cross;{/if}
</Badge>
@@ -1,6 +1,11 @@
type BaseColor = 'blue' | 'gray' | 'red' | 'green' | 'yellow' | 'indigo' | 'orange' | 'violet'
export const ColorModifier = 'dark-'
export type BadgeColor = BaseColor | 'transparent' | `${typeof ColorModifier}${BaseColor}`
/** `transparent` is outlined; `subtle` has neither fill nor border. */
export type BadgeColor =
| BaseColor
| 'transparent'
| 'subtle'
| `${typeof ColorModifier}${BaseColor}`
export interface BadgeIconProps {
position?: 'left' | 'right'
@@ -16,7 +16,7 @@
import MSSqlServerIcon from '$lib/components/icons/MSSqlServerIcon.svelte'
import BunIcon from '$lib/components/icons/BunIcon.svelte'
import DenoIcon from '$lib/components/icons/DenoIcon.svelte'
import type { Script } from '$lib/gen'
import { languageLabel } from './languageLabels'
import PHPIcon from '$lib/components/icons/PHPIcon.svelte'
import RustIcon from '$lib/components/icons/RustIcon.svelte'
import AnsibleIcon from '$lib/components/icons/AnsibleIcon.svelte'
@@ -52,40 +52,6 @@
let { lang, width = 30, height = 30, scale = 1, size = undefined, ...rest }: Props = $props()
const languageLabel: Record<
Script['language'] | 'bunnative' | 'claudesandbox' | 'pisandbox',
String
> = {
python3: 'Python',
deno: 'TypeScript',
go: 'Go',
bash: 'Bash',
powershell: 'PowerShell',
nativets: 'HTTP',
bunnative: 'HTTP',
graphql: 'GraphQL',
postgresql: 'Postgresql',
bigquery: 'BigQuery',
oracledb: 'Oracle Database',
duckdb: 'DuckDB',
snowflake: 'Snowflake',
mysql: 'MySQL',
mssql: 'MS SQL Server',
bun: 'TypeScript',
php: 'PHP',
rust: 'Rust',
ansible: 'Ansible',
csharp: 'C#',
nu: 'Nu',
java: 'Java',
ruby: 'Ruby',
rlang: 'R',
dbt: 'dbt',
claudesandbox: 'Claude Sandbox',
pisandbox: 'Pi Sandbox'
// for related places search: ADD_NEW_LANG
}
const langToComponent: Record<
| SupportedLanguage
| 'pgsql'
@@ -0,0 +1,11 @@
<script lang="ts">
import { languageLabel, languageShortLabel, type LabelledLanguage } from './languageLabels'
let { lang }: { lang: LabelledLanguage } = $props()
</script>
<!-- Quiet on purpose: it sits beside a title, and the title is what the eye is reading. -->
<span
class="shrink-0 text-3xs font-medium text-hint tracking-wide"
title={languageLabel[lang] ?? lang}>{languageShortLabel[lang] ?? lang}</span
>
@@ -0,0 +1,68 @@
import type { Script } from '$lib/gen'
export type LabelledLanguage = Script['language'] | 'bunnative' | 'claudesandbox' | 'pisandbox'
/** A language's name, as a tooltip or anywhere the full word fits. */
export const languageLabel: Record<LabelledLanguage, string> = {
python3: 'Python',
deno: 'TypeScript',
go: 'Go',
bash: 'Bash',
powershell: 'PowerShell',
nativets: 'HTTP',
bunnative: 'HTTP',
graphql: 'GraphQL',
postgresql: 'Postgresql',
bigquery: 'BigQuery',
oracledb: 'Oracle Database',
duckdb: 'DuckDB',
snowflake: 'Snowflake',
mysql: 'MySQL',
mssql: 'MS SQL Server',
bun: 'TypeScript',
php: 'PHP',
rust: 'Rust',
ansible: 'Ansible',
csharp: 'C#',
nu: 'Nu',
java: 'Java',
ruby: 'Ruby',
rlang: 'R',
dbt: 'dbt',
claudesandbox: 'Claude Sandbox',
pisandbox: 'Pi Sandbox'
// for related places search: ADD_NEW_LANG
}
/** A few letters for a list row, where a logo per row is more than the eye needs. Every SQL
* dialect reads "SQL": which one is the tooltip's job (`languageLabel`). */
export const languageShortLabel: Record<LabelledLanguage, string> = {
python3: 'Py',
deno: 'TS',
bun: 'TS',
go: 'Go',
bash: 'Sh',
powershell: 'PS',
nativets: 'Rest',
bunnative: 'Rest',
graphql: 'GQL',
postgresql: 'SQL',
bigquery: 'SQL',
oracledb: 'SQL',
duckdb: 'SQL',
snowflake: 'SQL',
mysql: 'SQL',
mssql: 'SQL',
php: 'PHP',
rust: 'Rs',
ansible: 'Ans',
csharp: 'C#',
nu: 'Nu',
java: 'Java',
ruby: 'Rb',
rlang: 'R',
dbt: 'dbt',
claudesandbox: 'AI',
pisandbox: 'AI'
// for related places search: ADD_NEW_LANG
}
@@ -84,6 +84,7 @@
>
{#snippet badges()}
<SharedBadge canWrite={agent.canWrite} extraPerms={agent.extra_perms} />
<InheritedLabels labels={agent.inherited_labels} max={1} color="subtle" />
<DraftBadge
is_draft={agent.is_draft}
draft_only={agent.draft_only}
@@ -93,24 +94,18 @@
path={agent.path}
onMigrated={() => dispatch('change')}
/>
<InheritedLabels labels={agent.inherited_labels} />
{/snippet}
{#snippet actions()}
{#if agent.canWrite}
<span class="hidden md:inline-flex">
<Button
variant="subtle"
wrapperClasses="w-20"
unifiedSize="md"
startIcon={{ icon: Pen }}
href={editHref}
>
<Button variant="subtle" unifiedSize="sm" startIcon={{ icon: Pen }} href={editHref}>
Edit
</Button>
</span>
{/if}
<Dropdown
size="sm"
items={async () => [
...selectMenuItems(rowSelection),
...agentMenuItems({
@@ -13,6 +13,8 @@
import Row from './Row.svelte'
import { selectMenuItems, type RowSelection } from './rowSelection'
import InheritedLabels from '$lib/components/InheritedLabels.svelte'
import RowLabels from './RowLabels.svelte'
import AskAiRowButton from './AskAiRowButton.svelte'
import Badge from '../badge/Badge.svelte'
import {
ExternalLink,
@@ -127,6 +129,8 @@
<Badge small icon={{ icon: FileJson }}>Raw</Badge>
{/if}
<SharedBadge canWrite={app.canWrite} extraPerms={app.extra_perms} />
<RowLabels labels={app.labels} />
<InheritedLabels labels={app.inherited_labels} max={1} color="subtle" />
<DraftBadge
is_draft={app.is_draft}
draft_only={app.draft_only}
@@ -137,36 +141,17 @@
path={app.path}
onMigrated={() => dispatch('change')}
/>
{#if app.labels?.length}
<div class="flex items-center gap-0.5">
{#each app.labels.slice(0, 3) as label}
<Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge>
{/each}
{#if app.labels.length > 3}
<Badge
color="blue"
small
class="px-1"
title={app.labels
.slice(3)
.map((l) => 'Label: ' + l)
.join('\n')}>+{app.labels.length - 3}</Badge
>
{/if}
</div>
{/if}
<InheritedLabels labels={app.inherited_labels} />
<div class="w-8 center-center"></div>
{/snippet}
{#snippet actions()}
<span class="hidden md:inline-flex gap-x-1">
<span class="hidden md:inline-flex">
<AskAiRowButton kind="app" path={app.path} summary={app.summary} rawApp={!!app.raw_app} />
{#if showEditButton && app.canWrite}
<div>
<Button
aiId={`edit-app-button-${app.summary?.length > 0 ? app.summary : app.path}`}
aiDescription={`Edits the app ${app.summary?.length > 0 ? app.summary : app.path}`}
variant="subtle"
wrapperClasses="w-20"
unifiedSize="sm"
startIcon={{ icon: Pen }}
href="/apps{app.raw_app ? '_raw' : ''}/edit/{app.path}"
>
@@ -179,6 +164,7 @@
{/if}
</span>
<Dropdown
size="sm"
aiId={`app-row-dropdown-${app.summary?.length > 0 ? app.summary : app.path}`}
aiDescription={`Open dropdown for app ${app.summary?.length > 0 ? app.summary : app.path} options`}
items={async () => {
@@ -0,0 +1,30 @@
<script lang="ts">
import { WandSparkles } from 'lucide-svelte'
import Button from '../button/Button.svelte'
import {
homeComposerContext,
itemContextElement
} from '$lib/components/sessions/homeComposerContext.svelte'
let {
kind,
path,
summary,
rawApp
}: { kind: string; path: string; summary?: string; rawApp?: boolean } = $props()
let element = $derived(itemContextElement({ kind, path, summary: summary || undefined, rawApp }))
</script>
{#if element && homeComposerContext.available}
<Button
variant="subtle"
unifiedSize="sm"
btnClasses="!text-ai"
startIcon={{ icon: WandSparkles }}
title="Add to the chat above"
onClick={() => element && homeComposerContext.attach(element)}
>
Ask AI
</Button>
{/if}
@@ -35,7 +35,7 @@
<Button
variant="subtle"
wrapperClasses="max-w-56"
unifiedSize="md"
unifiedSize="sm"
startIcon={{ icon: Pen }}
{href}
onClick={(e) => onEditInForkClick(e, itemType, path, { hasHref: true })}
@@ -37,6 +37,8 @@
import FlowHistory from '$lib/components/flows/FlowHistory.svelte'
import ChatFlowBadge from '$lib/components/flows/ChatFlowBadge.svelte'
import InheritedLabels from '$lib/components/InheritedLabels.svelte'
import RowLabels from './RowLabels.svelte'
import AskAiRowButton from './AskAiRowButton.svelte'
import { getDeployUiSettings } from '$lib/components/home/deploy_ui'
import { editInForkAllowed, editInForkLabel, onEditInForkClick } from '$lib/utils/editInFork'
import EditInForkButton from './EditInForkButton.svelte'
@@ -159,6 +161,8 @@
<Badge color="red" baseClass="border">archived</Badge>
{/if}
<SharedBadge canWrite={flow.canWrite} extraPerms={flow.extra_perms} />
<RowLabels labels={flow.labels} />
<InheritedLabels labels={flow.inherited_labels} max={1} color="subtle" />
<DraftBadge
is_draft={flow.is_draft}
draft_only={flow.draft_only}
@@ -169,35 +173,15 @@
path={flow.path}
onMigrated={() => dispatch('change')}
/>
{#if flow.labels?.length}
<div class="flex items-center gap-0.5">
{#each flow.labels.slice(0, 3) as label}
<Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge>
{/each}
{#if flow.labels.length > 3}
<Badge
color="blue"
small
class="px-1"
title={flow.labels
.slice(3)
.map((l) => 'Label: ' + l)
.join('\n')}>+{flow.labels.length - 3}</Badge
>
{/if}
</div>
{/if}
<InheritedLabels labels={flow.inherited_labels} />
<div class="w-8 center-center"></div>
{/snippet}
{#snippet actions()}
<span class="hidden md:inline-flex gap-x-1">
<span class="hidden md:inline-flex">
<AskAiRowButton kind="flow" path={flow.path} summary={flow.summary} />
{#if !hideForOperator && showEditButton && flow.canWrite && !flow.archived}
<div>
<Button
variant="subtle"
wrapperClasses="w-20"
unifiedSize="md"
unifiedSize="sm"
startIcon={{ icon: Pen }}
href="/flows/edit/{flow.path}"
aiId={`edit-flow-button-${flow.summary?.length > 0 ? flow.summary : flow.path}`}
@@ -214,6 +198,7 @@
</span>
<Dropdown
size="sm"
aiId={`flow-row-dropdown-${flow.summary?.length > 0 ? flow.summary : flow.path}`}
aiDescription={`Open dropdown for flow ${flow.summary?.length > 0 ? flow.summary : flow.path} options`}
items={async () => {
@@ -177,6 +177,7 @@
with its sibling folder at the same depth. -->
<div
bind:this={rowEl}
data-list-row
data-row-selection-key={rowSelection?.key}
data-row-keyboard-selected={keyboardSelected ? 'true' : undefined}
class={twMerge(
@@ -255,20 +256,12 @@
{/if}
{#if badges}
<div class="hidden lg:flex flex-row gap-4 items-center">
<div class="hidden lg:flex shrink-0 flex-row gap-4 items-center">
{@render badges?.()}
</div>
{/if}
{#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow' || kind == 'agent')}
<div class="center-center h-full text-xs font-semibold text-secondary w-9 shrink-0">
<Star {kind} {path} {workspaceId} {summary} />
</div>
{:else}
<div class="w-9 shrink-0"></div>
{/if}
<div data-row-actions class="flex gap-1 items-center justify-end pr-2">
<div data-row-actions class="flex shrink-0 items-center justify-end">
{@render actions?.()}
</div>
</div>
@@ -280,7 +273,7 @@
</div>
{/if}
<div class="grow min-w-0">
<div class="text-emphasis flex items-center gap-2 text-left text-xs font-semibold">
<div class="text-emphasis flex items-center gap-1.5 text-left text-xs font-semibold">
{#if customSummary}
<div class="min-w-0">{@render customSummary()}</div>
{:else}
@@ -295,6 +288,18 @@
{#if titleBadge}
<span class="shrink-0">{@render titleBadge()}</span>
{/if}
{#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow' || kind == 'agent')}
<!-- Beside the title it marks: a star already set stays, an unset one shows on the
row's hover only, so a list of titles doesn't read as a column of outlines. -->
<Star
{kind}
{path}
{workspaceId}
{summary}
size={13}
class="inline-flex shrink-0 p-px text-yellow-500 invisible data-[starred]:visible group-hover/row:visible focus-visible:visible"
/>
{/if}
</div>
<div class="text-hint text-3xs truncate text-left font-normal" title={path}>
{#if pathDisplay}
@@ -0,0 +1,25 @@
<script lang="ts">
import { Tag } from 'lucide-svelte'
import LabelBadge from '../badge/LabelBadge.svelte'
let { labels }: { labels: string[] | undefined | null } = $props()
// A row has little room beside its title; the rest are counted, and named in the tooltip.
const SHOWN = 1
</script>
{#if labels?.length}
<div class="flex items-center gap-0.5">
{#each labels.slice(0, SHOWN) as label}
<LabelBadge icon={Tag} title="Label: {label}">{label}</LabelBadge>
{/each}
{#if labels.length > SHOWN}
<LabelBadge
title={labels
.slice(SHOWN)
.map((l) => 'Label: ' + l)
.join('\n')}>+{labels.length - SHOWN}</LabelBadge
>
{/if}
</div>
{/if}
@@ -28,7 +28,7 @@
import { isDeployable } from '$lib/utils_deployable'
import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte'
import { LanguageIcon } from '../languageIcons'
import LanguageTag from '../languageIcons/LanguageTag.svelte'
import {
Archive,
Calendar,
@@ -51,6 +51,8 @@
import { Drawer, DrawerContent } from '..'
import NoMainFuncBadge from '$lib/components/NoMainFuncBadge.svelte'
import InheritedLabels from '$lib/components/InheritedLabels.svelte'
import RowLabels from './RowLabels.svelte'
import AskAiRowButton from './AskAiRowButton.svelte'
import Popover from '$lib/components/Popover.svelte'
import Tooltip from '$lib/components/Tooltip.svelte'
import { getDeployUiSettings } from '$lib/components/home/deploy_ui'
@@ -207,6 +209,9 @@
>
{/if}
<SharedBadge canWrite={script.canWrite} extraPerms={script.extra_perms} />
<RowLabels labels={script.labels} />
<InheritedLabels labels={script.inherited_labels} max={1} color="subtle" />
<!-- Last, so the draft badges line up down the list whatever labels each row has. -->
<DraftBadge
is_draft={script.is_draft}
draft_only={script.draft_only}
@@ -217,32 +222,15 @@
path={script.path}
onMigrated={() => dispatch('change')}
/>
{#if script.labels?.length}
<div class="flex items-center gap-0.5">
{#each script.labels.slice(0, 3) as label}
<Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge>
{/each}
{#if script.labels.length > 3}
<Badge
color="blue"
small
class="px-1"
title={script.labels
.slice(3)
.map((l) => 'Label: ' + l)
.join('\n')}>+{script.labels.length - 3}</Badge
>
{/if}
</div>
{/if}
<InheritedLabels labels={script.inherited_labels} />
<div class="w-8 center-center">
<LanguageIcon lang={script.language} width={16} height={16} />
</div>
{/snippet}
{#snippet titleBadge()}
<LanguageTag lang={script.language} />
{/snippet}
{#snippet actions()}
<span class="hidden md:inline-flex gap-x-1">
<span class="hidden md:inline-flex">
<AskAiRowButton kind="script" path={script.path} summary={script.summary} />
{#if !$userStore?.operator}
{#if showEditButton}
{#if script.use_codebase}
@@ -257,8 +245,7 @@
aiId={`edit-script-button-${script.summary?.length > 0 ? script.summary : script.path}`}
aiDescription={`Edits the script ${script.summary?.length > 0 ? script.summary : script.path}`}
variant="subtle"
wrapperClasses="w-20"
unifiedSize="md"
unifiedSize="sm"
startIcon={{ icon: Pen }}
href="/scripts/edit/{script.path}"
>
@@ -273,6 +260,7 @@
{/if}
</span>
<Dropdown
size="sm"
aiId={`script-row-dropdown-${script.summary?.length > 0 ? script.summary : script.path}`}
aiDescription={`Open dropdown for script ${script.summary?.length > 0 ? script.summary : script.path} options`}
items={async () => {
@@ -98,7 +98,12 @@
title={config.readOnly ? config.readOnlyReason : config.title}
>
<span class="flex items-center gap-1 min-w-0">
<span class="truncate">{config.label}</span>
{#if config.shortLabel}
<span class="truncate hidden xl:inline">{config.label}</span>
<span class="truncate xl:hidden">{config.shortLabel}</span>
{:else}
<span class="truncate">{config.label}</span>
{/if}
{#if effortLabel}
<span class="shrink-0 text-tertiary">· {effortLabel}</span>
{/if}
@@ -22,6 +22,7 @@
viewTransitionNames = false,
onSent = undefined,
inputPreface,
actingOn,
initialInstructions = undefined,
onDraftChange = undefined,
initialAttachments = undefined,
@@ -44,6 +45,8 @@
viewTransitionNames?: boolean
onSent?: () => void
inputPreface?: import('svelte').Snippet
/** Forwarded to AIChatDisplay: where the session acts, first among the controls. */
actingOn?: import('svelte').Snippet
// Seed / observe the composer's draft (forwarded to AIChatDisplay).
initialInstructions?: string
onDraftChange?: (text: string) => void
@@ -120,6 +123,10 @@
aiChatDisplay?.focusInput()
}
export async function attachContext(element: import('./context').ContextElement) {
await aiChatDisplay?.attachContext(element)
}
const historyManager = aiChatManager.historyManager
let aiChatDisplay: AIChatDisplay | undefined = $state(undefined)
@@ -212,6 +219,7 @@
{viewTransitionNames}
{onSent}
{inputPreface}
{actingOn}
{initialInstructions}
{onDraftChange}
{initialAttachments}
@@ -69,11 +69,14 @@
import Alert from '$lib/components/common/alert/Alert.svelte'
import { copilotInfo } from '$lib/aiStore'
import SessionGreeting from './starter/SessionGreeting.svelte'
import StarterPromptChips from './starter/StarterPromptChips.svelte'
import ComposerSuggestions from './starter/ComposerSuggestions.svelte'
import type { DraftAttachments } from './messageDraft.svelte'
import { RotatingPlaceholder, type ChatStarter } from './starter/starterPrompts.svelte'
import type { ChatStarter } from './starter/starterPrompts.svelte'
import { composerCollapses, isComposerOverlay } from './starter/composerCollapse'
import { smoothHeight } from './starter/smoothHeight'
const MAX_YOLO_TOOLTIP_TOOLS = 8
const STARTER_PLACEHOLDER = 'Ask about this workspace, or describe what to build…'
const chatHost = getChatViewHost()
// The skill and MCP menus take an AIChatManager itself, which the seam deliberately
// doesn't carry. They render only under GLOBAL, which a non-copilot host never sets.
@@ -114,6 +117,7 @@
viewTransitionNames = false,
onSent = undefined,
inputPreface,
actingOn,
footerSettings,
initialInstructions = undefined,
onDraftChange = undefined,
@@ -151,14 +155,16 @@
* both mount it, so the two are one entry point rather than look-alikes. Replaces
* `emptyHint`. */
starter?: ChatStarter
/** Names the block for the view transition between Home and AI Sessions. Only one
* chat on the page may carry the names: a duplicate makes the browser skip the
* transition. Named only while the chat is empty: the glide carries Home's draft to
* the same draft's page and back, and a session already under way just cross-fades. */
/** Names the composer for the view transition between Home and AI Sessions, so it
* glides between its two places, a send from Home included: that lands it under the
* session's first message. Only one chat on the page may carry the name: a duplicate
* makes the browser skip the transition. */
viewTransitionNames?: boolean
/** After the composer hands a new turn to the host. */
onSent?: () => void
inputPreface?: Snippet
/** Where the session acts: first among the controls after the attach button. */
actingOn?: Snippet
/** The settings control at the footer's right edge, where the copilot puts its
* model picker. A host that configures its turn elsewhere replaces it here. */
footerSettings?: Snippet
@@ -306,6 +312,14 @@
aiChatInput?.focusInput()
}
/** Mention a workspace item in the draft, as "+" → Mention file does, and hand the user
* the caret after it. Focusing is what opens Home's one-line composer. */
export async function attachContext(element: ContextElement) {
void aiChatInput?.addContextToSelection(element)
await aiChatInput?.insertMention(element.title)
aiChatInput?.focusInput()
}
$effect(() => {
const input = aiChatInput
if (!input) return
@@ -571,21 +585,43 @@
// A step name hangs its icon in the column's left padding (see AssistantMessage), so a
// transcript carrying one widens the padding, on both sides to keep the column centred.
const agentGutter = $derived(messages.some((m) => m.role === 'assistant' && m.stepName))
// The block's layout holds while the chat is empty, usable or not; only the rotating
// placeholder, the taller box and the prompts need a composer that can send.
// The block's layout holds while the chat is empty, usable or not; only the taller box
// and the suggestions need a composer that can send.
const starterLayout = $derived(!!starter && messages.length === 0)
const starterHero = $derived(starterLayout && !disabled)
// Home is a page, not a pane: nothing there to centre in.
const centreComposer = $derived(starterLayout && starter?.where === 'session')
const starterPlaceholder = new RotatingPlaceholder(
() => (starter?.prompts ?? []).map((p) => p.prompt),
() => starterHero
)
// 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
// clearing the text later cannot fold it up under the caret. Opened by the field rather
// than any focus inside: the one-line row's model button would otherwise unmount under the
// menu it is opening.
let composerEl: HTMLDivElement | undefined = $state()
let composerOpened = $state(false)
const composerCollapsed = $derived(
composerCollapses({
onHome: starterLayout && starter?.where === 'home',
usable: !disabled,
fewItems: starter?.fewItems ?? false,
opened: composerOpened,
draftEmpty: aiChatInput?.isDraftEmpty() ?? true
})
)
function closeComposer() {
if (aiChatInput?.isDraftEmpty() ?? true) composerOpened = false
}
function onComposerPointerDown(e: PointerEvent) {
if (!composerOpened || composerEl?.contains(e.target as Node)) return
if (!isComposerOverlay(e.target)) closeComposer()
}
// Home's composer is one block of the page and takes the page's column as it is.
const columnClass = $derived(
wideLayout
? `w-full max-w-3xl mx-auto ${agentGutter ? 'px-8' : 'px-7'}`
: `w-full max-w-2xl mx-auto ${agentGutter ? 'px-8' : 'px-3'}`
starter?.where === 'home'
? 'w-full'
: wideLayout
? `w-full max-w-3xl mx-auto ${agentGutter ? 'px-8' : 'px-7'}`
: `w-full max-w-2xl mx-auto ${agentGutter ? 'px-8' : 'px-3'}`
)
const waitingForUserAction = $derived(chatHost.loading && !!pendingUserAction(messages))
@@ -641,6 +677,7 @@
const showFooterLeftControls = $derived(
!footerMessageShown &&
(canAttachFiles ||
!!actingOn ||
attachmentsOffReason !== undefined ||
showContextPicker ||
showAutonomyModeSelector ||
@@ -686,6 +723,8 @@
</div>
{/snippet}
<svelte:document onpointerdown={onComposerPointerDown} />
<!-- 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
@@ -799,17 +838,16 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/if}
{#if messages.length === 0}
{#if starter}
<!-- In a session 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. -->
<div class={centreComposer ? 'flex-1 min-h-0 flex flex-col justify-end' : ''}>
<div
class={columnClass}
style:view-transition-name={viewTransitionNames ? 'session-heading' : undefined}
>
<SessionGreeting />
<!-- 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>
</div>
{/if}
{:else if emptyHint}
{@render emptyHint()}
{:else}
@@ -931,12 +969,26 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
<!-- Same horizontal padding as the transcript above: the composer's edges line up with
the messages rather than sitting closer to the panel edge. -->
<!-- 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 -->
<div
data-session-composer
role="group"
aria-label="Message composer"
bind:this={composerEl}
class="relative {columnClass} pb-2"
style:view-transition-name={viewTransitionNames && starterLayout
? 'session-composer'
: undefined}
style:view-transition-name={viewTransitionNames ? 'composer' : undefined}
onfocusin={(e) => {
if (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 (!composerOpened || starter?.where !== 'home') return
closeComposer()
if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur()
}}
>
{#if showFlowPendingActionControls}
<div class="absolute -top-10 w-full flex flex-row justify-center gap-2">
@@ -990,7 +1042,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
bind:this={aiChatInput}
bind:selectedContext
{availableContext}
{placeholder}
placeholder={starterLayout ? STARTER_PLACEHOLDER : placeholder}
{initialInstructions}
{onDraftChange}
{initialAttachments}
@@ -1000,9 +1052,15 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{pendingQuestionToolCallId}
isFirstMessage={messages.length === 0}
hero={starterLayout}
fadingPlaceholder={starterHero ? starterPlaceholder : undefined}
collapsed={composerCollapsed}
chatIcon={starterLayout && starter?.where === 'home'}
{onSent}
>
{#snippet collapsedControls()}
{#if chatHost.supportsModelSettings}
<AIChatModelSettings promptSettings={false} />
{/if}
{/snippet}
{#snippet toolbar()}
<div
class="flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1"
@@ -1197,6 +1255,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
onchange={onFolderInputChange}
/>
{/if}
{@render actingOn?.()}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
@@ -1319,31 +1378,19 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/snippet}
</AIChatInput>
</div>
{#if starterLayout && starter}
{#if showFreeTierUsage}
<div
class="mt-2 flex flex-row items-center justify-end gap-1 text-2xs text-hint tabular-nums"
>
{freeTierUsedPct}% of free AI used ·
<Button
variant="subtle"
unifiedSize="2xs"
btnClasses="!text-2xs !text-hint !px-0 underline"
href="/workspace_settings?tab=ai"
>
Configure API key
</Button>
</div>
{/if}
{#if starter.chips && !disabled}
<div class="mt-3">
<StarterPromptChips
prompts={starter.prompts}
onPick={(prompt) => aiChatInput?.setText(prompt)}
/>
</div>
{/if}
{/if}
<!-- Opens and closes with the box, so the page under it slides rather than jumps. -->
<div use:smoothHeight={{ enabled: starterLayout, key: composerCollapsed }}>
<div>
{#if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0}
<div class="pt-2">
<ComposerSuggestions
suggestions={starter.suggestions}
onPick={(prompt) => aiChatInput?.setText(prompt)}
/>
</div>
{/if}
</div>
</div>
{#if (chatHost.mode === AIMode.NAVIGATOR || chatHost.mode === AIMode.ASK) && suggestions.length > 0 && messages.filter((m) => m.role === 'user').length === 0 && !disabled}
<div class="px-2 mt-4">
<div class="flex flex-col gap-2">
@@ -17,8 +17,9 @@
// The send button sits in the toolbar row, not over the field, so the text needs no
// room reserved on its right, and the row right below it stands in for most of its
// bottom padding.
const FIELD_PADDING_WITH_TOOLBAR = '!pr-3 !pb-1'
// bottom padding. The top padding is the one-line row's, so the text holds still as Home's
// composer opens.
const FIELD_PADDING_WITH_TOOLBAR = '!pl-4 !pr-4 !pt-3 !pb-1'
import { formatMention, hasMention, removeMentionFromText } from './mention'
import { twMerge } from 'tailwind-merge'
import { tick, untrack, type Snippet } from 'svelte'
@@ -108,7 +109,12 @@
* the controls sit under the box and the send button floats over the field's corner, as a
* chat under way reads more clearly. */
hero?: boolean
fadingPlaceholder?: { text: string; visible: boolean }
/** With `hero`: one row, the field then `collapsedControls` and the send button, in
* place of the toolbar. */
collapsed?: boolean
collapsedControls?: Snippet
/** A chat mark before the field, where the box alone doesn't say it is the assistant's. */
chatIcon?: boolean
/** After a new turn is handed to the host — not an edit, a queued message or an answer. */
onSent?: () => void
/** The composer's controls. */
@@ -142,9 +148,12 @@
onSent = undefined,
toolbar = undefined,
hero = false,
fadingPlaceholder = undefined
collapsed = false,
collapsedControls = undefined,
chatIcon = false
}: Props = $props()
const oneLine = $derived(hero && collapsed)
const toolbarInBox = $derived(!!toolbar && hero)
// GLOBAL-mode suggestion pool. We pick one at mount-time so each new
@@ -660,10 +669,12 @@
* auto-remove items when the user deletes them. No-op when the same
* standalone mention is already present, so picking the same item
* again doesn't leave duplicate tokens. */
export function insertMention(title: string) {
/** Resolves once the caret sits after the mention, so mentions inserted one after another
* land in that order. */
export async function insertMention(title: string) {
if (hasMention(draft.text, title)) return
if (contextTextareaComponent) {
void contextTextareaComponent.insertMention(title)
await contextTextareaComponent.insertMention(title)
return
}
const sep = draft.text.length === 0 || /\s$/.test(draft.text) ? '' : ' '
@@ -690,6 +701,11 @@
focusInput()
}
/** Whether nothing would ship with a send: no text and no attachment. */
export function isDraftEmpty(): boolean {
return draft.isEmpty
}
export function focusInput() {
if (isContextEnabledMode) {
contextTextareaComponent?.focus()
@@ -1263,10 +1279,15 @@
</script>
{#snippet toolbarRow()}
{#if toolbarInBox}
{#if oneLine}
<div class="flex flex-row items-center gap-1 pr-3 shrink-0">
{@render collapsedControls?.()}
{@render sendStopButton('sm')}
</div>
{:else if toolbarInBox}
<!-- The send button sets the row's height and the smaller controls centre on it, which
already puts them a few pixels further from the box's bottom edge than the padding. -->
<div class="flex flex-row items-center gap-1.5 px-1.5 pb-1">
<div class="flex flex-row items-center gap-1.5 px-3 pb-1.5">
<div class="flex-1 min-w-0">{@render toolbar?.()}</div>
{@render sendStopButton('sm')}
</div>
@@ -1471,9 +1492,8 @@
{selectedContext}
placeholder={modePlaceholder}
hero={hero && !disabled}
fadingPlaceholder={isFirstMessage && !chatHost.runHeldElsewhere
? fadingPlaceholder
: undefined}
{oneLine}
{chatIcon}
onAddContext={(contextElement) => void addContextToSelection(contextElement)}
onRemoveContext={(element) => {
selectedContext = selectedContext?.filter((c) => !isSameContextElement(c, element))
@@ -1486,7 +1506,10 @@
}}
{disabled}
{onKeyDown}
className={toolbarInBox ? FIELD_PADDING_WITH_TOOLBAR : ''}
className={twMerge(
oneLine ? '!pl-4 !pr-2 !py-3' : toolbarInBox ? FIELD_PADDING_WITH_TOOLBAR : '',
chatIcon && '!pl-2'
)}
>
{#snippet leading()}
{@render badgeRow()}
@@ -240,6 +240,9 @@
const config = $derived<ChatModelSettingsConfig>({
label: providerModel.model,
// "claude-sonnet-4-6" → "sonnet": the family is what tells Claude models apart at a
// glance. Other providers' names have no such word, so they stay whole.
shortLabel: /^claude-([a-z]+)-/.exec(providerModel.model)?.[1],
title: 'Model & reasoning settings',
badge: freeTier && !freeTier.exhausted ? { text: 'Free', warn: freeRunningLow } : undefined,
// Off in a session: the assistant settings modal's Instructions section owns the
@@ -1,6 +1,7 @@
<script lang="ts">
import { composerBoxClass, COMPOSER_FIELD_RESET } from './composerBox'
import { PLACEHOLDER_FADE_CLASS } from './starter/starterPrompts.svelte'
import { composerBoxClass, COMPOSER_FIELD_RESET, HERO_BOX_CLASS } from './composerBox'
import { smoothHeight } from './starter/smoothHeight'
import { MessagesSquare } from 'lucide-svelte'
import autosize from '$lib/autosize'
import { tick, type Snippet } from 'svelte'
import type { ContextElement } from './context'
@@ -55,8 +56,10 @@
trailing?: Snippet
/** The taller box that opens a session, matching Home's composer. */
hero?: boolean
/** Replaces `placeholder` with one drawn over the field, so it can fade between prompts. */
fadingPlaceholder?: { text: string; visible: boolean }
/** One row: the field and `trailing` side by side, for Home's composer at rest. */
oneLine?: boolean
/** The assistant's chat mark before the field. */
chatIcon?: boolean
}
let {
@@ -76,15 +79,12 @@
leading,
trailing,
hero = false,
fadingPlaceholder
oneLine = false,
chatIcon = false
}: Props = $props()
const aiChatManager = getAiChatManager()
const placeholderClass = $derived(
`text-hint ${PLACEHOLDER_FADE_CLASS} ${fadingPlaceholder?.visible ? 'opacity-100' : 'opacity-0'}`
)
// Titles currently appearing as `@title` mentions in the textarea. Compared
// against the previous snapshot in a $effect (NOT inside handleInput —
// the picker mutates `value` programmatically via `updateInstructionsWithContext`,
@@ -803,11 +803,31 @@
}
</script>
<div class={twMerge(composerBoxClass(disabled), hero && !disabled && 'shadow-sm')}>
<!-- Context chips live inside the input box, above the textarea. The snippet
<!-- The box that opens a session grows and shrinks between its one-line and full shapes. -->
<div
class={twMerge(composerBoxClass(disabled), hero && !disabled && HERO_BOX_CLASS)}
use:smoothHeight={{ enabled: hero && !disabled, key: oneLine }}
>
<div class={oneLine ? 'flex flex-row items-center' : ''}>
<!-- Context chips live inside the input box, above the textarea. The snippet
self-guards (renders nothing when empty) so no blank row appears. -->
{@render leading?.()}
<div class="relative w-full">
{@render leading?.()}
{#if chatIcon}
<!-- The same mark as the "open in chat" buttons. On the field's first line: centred on the
one-line box, level with the first line of text once it opens. -->
<div class="flex {oneLine ? 'flex-1 min-w-0 items-center' : 'items-start'}">
<MessagesSquare size={16} class="shrink-0 ml-4 text-ai {oneLine ? '' : 'mt-3.5'}" />
{@render field()}
</div>
{:else}
{@render field()}
{/if}
{@render trailing?.()}
</div>
</div>
{#snippet field()}
<div class="relative w-full {oneLine ? 'flex-1 min-w-0' : ''}">
<div
class={twMerge(
'textarea-input absolute inset-0 overflow-hidden pointer-events-none',
@@ -816,22 +836,16 @@
)}
>
<div style="transform: translateY({-scrollTop}px)" use:chipClickDelegate>
<!-- The placeholder replaces the (empty) highlight rather than following it: this box is
`pre-wrap`, so whitespace between the two would indent its first line. -->
{#if fadingPlaceholder && !value}
<span aria-hidden="true" class={placeholderClass}>{fadingPlaceholder.text}</span>
{:else}
<span class="break-words">
{@html getHighlightedText(value)}
</span>
{/if}
<span class="break-words">
{@html getHighlightedText(value)}
</span>
</div>
</div>
<textarea
bind:this={textarea}
onkeydown={handleKeyDown}
bind:value
use:autosize={{ maxHeight: '40vh', minHeight: hero ? 56 : undefined }}
use:autosize={hero && !oneLine ? { maxHeight: 160, minHeight: 56 } : { maxHeight: '40vh' }}
rows={1}
oninput={handleInput}
onpaste={handlePaste}
@@ -855,8 +869,7 @@
showCommandTooltip = false
}, 200)
}}
placeholder={fadingPlaceholder ? '' : placeholder}
aria-label={fadingPlaceholder ? 'Describe what you want to do' : undefined}
{placeholder}
class={twMerge(
'textarea-input resize-none caret-black dark:caret-white overflow-clip',
COMPOSER_FIELD_RESET,
@@ -867,8 +880,7 @@
{disabled}
></textarea>
</div>
{@render trailing?.()}
</div>
{/snippet}
{#if showContextTooltip || showCommandTooltip}
<Portal target="body">
@@ -22,6 +22,10 @@ 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 = 'bg-surface-tertiary rounded-[10px]'
/** Applied to the field inside the box; without it the field draws a second border. */
export const COMPOSER_FIELD_RESET =
'!border-transparent !bg-transparent !shadow-none focus:!border-transparent focus:!ring-0 disabled:cursor-not-allowed disabled:placeholder:text-disabled'
@@ -42,6 +42,7 @@ export function readOnlyChatViewHost(options: {
sendRequest: async () => false,
cancel: noop,
setAiChatInput: noop,
releaseAiChatInput: noop,
queuedMessage: '',
queuedContext: undefined,
queuedImages: [],
@@ -0,0 +1,32 @@
<script lang="ts">
import { Pencil, Play } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import type { ComposerSuggestion } from './starterPrompts.svelte'
let {
suggestions,
onPick
}: {
suggestions: ComposerSuggestion[]
onPick: (prompt: string) => void
} = $props()
</script>
<!-- One row whatever the width: it scrolls sideways and fades out at its end rather than
wrapping, so the page under the composer does not move with the window width. -->
<div
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
variant="default"
unifiedSize="sm"
btnClasses="!rounded-full !text-xs !text-secondary !font-normal shrink-0"
title={suggestion.mode === 'use' ? 'Use: look, ask or run' : 'Build: create or change'}
startIcon={{ icon: suggestion.mode === 'use' ? Play : Pencil, classes: 'text-hint' }}
onClick={() => onPick(suggestion.prompt)}
>
{suggestion.label}
</Button>
{/each}
</div>
@@ -1,25 +0,0 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import type { StarterPrompt } from '$lib/onboardingProfile'
let {
prompts,
onPick
}: {
prompts: StarterPrompt[]
onPick: (prompt: string) => void
} = $props()
</script>
<div class="flex flex-row flex-wrap items-center gap-1.5">
{#each prompts as example (example.label)}
<Button
variant="default"
unifiedSize="xs"
btnClasses="!rounded-full !text-2xs !text-hint"
onClick={() => onPick(example.prompt)}
>
{example.label}
</Button>
{/each}
</div>
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { composerCollapses } from './composerCollapse'
const atRest = { onHome: true, usable: true, fewItems: false, opened: false, draftEmpty: true }
describe('composerCollapses', () => {
it('collapses only on Home, at rest, in a workspace that is not small', () => {
expect(composerCollapses(atRest)).toBe(true)
expect(composerCollapses({ ...atRest, onHome: false })).toBe(false)
expect(composerCollapses({ ...atRest, fewItems: true })).toBe(false)
expect(composerCollapses({ ...atRest, usable: false })).toBe(false)
})
it('stays open while the user is in it or has a draft', () => {
expect(composerCollapses({ ...atRest, opened: true })).toBe(false)
expect(composerCollapses({ ...atRest, draftEmpty: false })).toBe(false)
})
})
@@ -0,0 +1,24 @@
/** Whether Home's composer rests as one line. 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. */
export function composerCollapses(s: {
onHome: boolean
usable: boolean
fewItems: boolean
opened: boolean
draftEmpty: boolean
}): boolean {
return s.onHome && s.usable && !s.fewItems && !s.opened && s.draftEmpty
}
// 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"]'
/** 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
}
@@ -0,0 +1,58 @@
type SmoothHeightParams = {
/** Off: the element takes its natural height and nothing is animated. */
enabled: boolean
/** The state whose change should animate. Height changes at any other time follow the
* content at once: animating every line the user types would clip the caret's line. */
key: unknown
}
const DURATION_MS = 200
const EASING = 'cubic-bezier(0.2, 0.8, 0.2, 1)'
/**
* Sizes `node` to its first child and animates that height when `key` changes, so a block
* that changes shape grows and shrinks instead of jumping. The child is measured, not the
* node: the node's own height is the one being set. `node` clips while it animates, so a
* focus ring belongs on `node` itself (box-shadow is not clipped by its own overflow).
*/
export function smoothHeight(node: HTMLElement, params: SmoothHeightParams) {
let { enabled, key } = params
let animateUntil = 0
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)')
const apply = () => {
const inner = node.firstElementChild as HTMLElement | null
if (!enabled || !inner) {
node.style.height = ''
node.style.overflow = ''
node.style.transition = ''
return
}
const borders = node.offsetHeight - node.clientHeight
const animate = performance.now() < animateUntil && !reducedMotion.matches
node.style.overflow = 'hidden'
node.style.transition = animate ? `height ${DURATION_MS}ms ${EASING}` : 'none'
node.style.height = `${inner.offsetHeight + borders}px`
}
const ro = new ResizeObserver(apply)
const observe = () => {
ro.disconnect()
const inner = node.firstElementChild
if (inner) ro.observe(inner)
}
observe()
apply()
return {
update(next: SmoothHeightParams) {
if (next.key !== key) animateUntil = performance.now() + DURATION_MS
;({ enabled, key } = next)
observe()
apply()
},
destroy() {
ro.disconnect()
}
}
}
@@ -1,155 +1,154 @@
import { onboardingProfile, type StarterPrompt } from '$lib/onboardingProfile'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
import { userStore } from '$lib/stores'
import { fromStore } from 'svelte/store'
import { resource } from 'runed'
import { ScriptService } from '$lib/gen'
/** Example prompts: the short `label` is shown as a clickable tag under the composer,
* the `prompt` is what rotates through the placeholder / gets dropped into the input. */
export const defaultStarterPrompts: StarterPrompt[] = [
/** A prompt offered under the composer: `label` is the pill, `prompt` what it puts in the
* box. `use` looks at, asks about or runs what exists; `build` creates or changes things. */
export type ComposerSuggestion = StarterPrompt & { mode: 'use' | 'build' }
const USE_EXAMPLES: ComposerSuggestion[] = [
{
mode: 'use',
label: 'What failed today?',
prompt: 'Which runs failed in this workspace today, and why?'
},
{
mode: 'use',
label: 'Which schedules run the most?',
prompt:
'Which schedules ran the most today, and does any of them run more often than it should?'
}
]
const BUILD_EXAMPLES: ComposerSuggestion[] = [
{
mode: 'build',
label: 'Sync Salesforce',
prompt: 'Sync new Salesforce leads into a postgres table every hour'
},
{
mode: 'build',
label: 'Weekly Slack report',
prompt: 'Generate a weekly sales report from postgres and post it to Slack every Monday'
},
{
mode: 'build',
label: 'Ban Discord users',
prompt:
'Build a workflow that triggers on a Discord message, checks for offensive language using an LLM, and possibly block them'
},
{
label: 'Weekly Slack report',
prompt: 'Generate a weekly sales report from postgres and post it to Slack every Monday'
}
]
/** An operator's session can run what is deployed, read runs and call MCP servers, but
* cannot author scripts or apps. It composes flows only where the workspace grants
* `operator_settings.builder_flows`, so none of these asks it to build anything. */
export const operatorStarterPrompts: StarterPrompt[] = [
{
label: 'Run a flow',
prompt: 'Find the flow that onboards a new employee and run it for Jane Doe, starting Monday'
},
* cannot author scripts or apps, so none of these asks it to build anything. */
const OPERATOR_EXAMPLES: ComposerSuggestion[] = [
USE_EXAMPLES[0],
{
mode: 'use',
label: 'Rerun failed jobs',
prompt: 'List the jobs that failed today, tell me why, and rerun the ones that timed out'
},
{
mode: 'use',
label: 'Run a flow',
prompt: 'Find the flow that onboards a new employee and run it for Jane Doe, starting Monday'
},
{
mode: 'use',
label: 'Summarize GitHub issues',
prompt: "Read this week's open GitHub issues and summarize the ones that mention billing"
}
]
/** The stock examples for the reader's role, unless the invite that brought this person here
* wrote prompts for them — those replace the set outright rather than joining it, since a
* prompt written for someone's own stack next to "Ban Discord users" reads as the generic one. */
/** From this many items on, Home's composer rests collapsed: below it the workspace is new
* enough that the composer is the page's main way in. */
const FEW_ITEMS = 10
/** The suggestions for the reader's role and the workspace the session acts on, and whether
* that workspace is still small. An invite that wrote prompts for this person replaces the
* examples outright: a prompt written for someone's own stack next to "Ban Discord users"
* reads as the generic one. */
export class StarterPrompts {
#invite = $state<StarterPrompt[]>()
#user = fromStore(userStore)
readonly list = $derived(
this.#invite ?? (this.#user.current?.operator ? operatorStarterPrompts : defaultStarterPrompts)
)
#hasItems: { readonly current: boolean | undefined }
#workspace: () => string | undefined
#itemCount: { readonly current: number | undefined }
/** `workspace`: where the session acts, which decides whether the chips are offered. */
/** `workspace`: where the session acts. */
constructor(workspace: () => string | undefined) {
this.#workspace = workspace
void onboardingProfile().then((p) => {
if (p?.starter_prompts?.length) this.#invite = p.starter_prompts
})
this.#hasItems = resource(workspace, async (ws) => (ws ? workspaceHasItems(ws) : undefined))
this.#itemCount = resource(workspace, async (ws) => (ws ? workspaceItemCount(ws) : undefined))
}
/** The example chips are for a workspace with nothing in it yet: next to someone's own
* scripts and flows, "Ban Discord users" is noise. Withheld until the workspace is known
* to be empty, so they never show and then vanish. The examples still rotate through the
* placeholder either way. */
get chipsOffered(): boolean {
return this.#hasItems.current === false
/** At most `FEW_ITEMS`; undefined until the workspace has answered. A count already read
* this page load stands in while it is asked again, so a remount does not wait on it. */
get #count(): number | undefined {
const ws = this.#workspace()
return this.#itemCount.current ?? (ws ? itemCounts.get(ws) : undefined)
}
/** Up to four: two Use then two Build. An empty workspace has nothing to ask about yet. */
readonly suggestions: ComposerSuggestion[] = $derived.by(() => {
if (this.#invite) return this.#invite.map((p) => ({ ...p, mode: 'build' as const }))
if (this.#user.current?.operator) return OPERATOR_EXAMPLES
if (this.#count === 0) return BUILD_EXAMPLES
return [...USE_EXAMPLES, ...BUILD_EXAMPLES.slice(0, 2)]
})
/** Whether the workspace holds fewer than `FEW_ITEMS`; undefined until known. */
get fewItems(): boolean | undefined {
const count = this.#count
return count === undefined ? undefined : count < FEW_ITEMS
}
}
// Workspaces known to hold something, for the page load. An empty answer is not kept: the
// next mount asks again, so the chips go once the user has created their first item.
const workspacesWithItems = new Set<string>()
const itemCounts = new Map<string, number>()
const itemCountRequests = new Map<string, Promise<number>>()
async function workspaceHasItems(workspace: string): Promise<boolean> {
if (workspacesWithItems.has(workspace)) return true
/** Starts the count for a page about to mount the starter; the starter then takes this
* request rather than sending its own. */
export function prefetchItemCount(workspace: string): void {
void workspaceItemCount(workspace)
}
function workspaceItemCount(workspace: string): Promise<number> {
let request = itemCountRequests.get(workspace)
if (!request) {
request = fetchItemCount(workspace).finally(() => itemCountRequests.delete(workspace))
itemCountRequests.set(workspace, request)
}
return request
}
async function fetchItemCount(workspace: string): Promise<number> {
let count = FEW_ITEMS
try {
// What Home's list counts: library scripts and the user's own drafts included.
const res = await ScriptService.listRunnables({
workspace,
includeWithoutMain: true,
includeDraftOnly: true,
perPage: 1
perPage: FEW_ITEMS
})
const has = (res.items?.length ?? 0) > 0
if (has) workspacesWithItems.add(workspace)
return has
count = res.items?.length ?? 0
} catch (e) {
// Unknown reads as "has items": no chips is the quieter mistake.
console.error(`Could not check whether workspace ${workspace} has items:`, e)
return true
// Unknown reads as a full workspace: a collapsed composer is the quieter mistake.
console.error(`Could not count the items of workspace ${workspace}:`, e)
}
itemCounts.set(workspace, count)
return count
}
/** What turns an empty chat into the block that starts a session. */
export type ChatStarter = {
/** The page the block is on: an empty session centres it in the pane, Home does not. */
/** The page the block is on. An empty session centres it in the pane under a greeting;
* Home shows it alone, collapsed to one line at rest unless `fewItems`. */
where: 'home' | 'session'
/** Rotated through the placeholder. */
prompts: StarterPrompt[]
/** Also offered as chips under the box. */
chips: boolean
}
const CYCLE_MS = 7_000
/** Must match the `duration-*` class on the placeholder overlay: the swap happens once the
* fade-out has finished, and Tailwind only emits classes it finds written out in full. */
export const PLACEHOLDER_FADE_CLASS = 'transition-opacity duration-[600ms] ease-in-out'
const FADE_MS = 600
/**
* Rotates a placeholder through `prompts` every CYCLE_MS: fade out, swap, fade back in.
* Only while `active` — otherwise it would loop forever driving an unrendered input — and
* not under reduced motion, where the first prompt simply stays put. The index survives
* `active` going false, so the rotation resumes from the prompt currently displayed.
*
* Shown as an overlay rather than the field's `placeholder`: WebKit and Gecko do not run
* transitions on `::placeholder`, so the fade would be a hard cut there.
*/
export class RotatingPlaceholder {
#index = $state(0)
#prompts: () => string[]
visible = $state(true)
get text(): string {
const list = this.#prompts()
return list.length ? list[this.#index % list.length] : ''
}
constructor(prompts: () => string[], active: () => boolean) {
this.#prompts = prompts
const reducedMotion = useReducedMotion()
$effect(() => {
if (!active() || reducedMotion.val) return
let timer: ReturnType<typeof setTimeout>
const next = () => {
this.visible = false
timer = setTimeout(() => {
this.#index = (this.#index + 1) % Math.max(prompts().length, 1)
this.visible = true
timer = setTimeout(next, CYCLE_MS)
}, FADE_MS)
}
timer = setTimeout(next, CYCLE_MS)
return () => {
clearTimeout(timer)
// Torn down mid-fade, the input would otherwise remount with an invisible placeholder.
this.visible = true
}
})
}
suggestions: ComposerSuggestion[]
fewItems: boolean
}
@@ -41,6 +41,8 @@ export type ChoiceSection = {
export type ChatModelSettingsConfig = {
/** The trigger's main text: the chosen model, or an invitation to choose one. */
label: string
/** Shown instead of `label` on windows narrower than 1280px. */
shortLabel?: string
title?: string
/** Trailing pill on the trigger, e.g. the free-tier grant this chat is spending. */
badge?: { text: string; warn?: boolean }
@@ -12,7 +12,19 @@
import { sendUserToast } from '$lib/toast'
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte'
import { Archive, ArchiveRestore, FolderInput, MoreHorizontal, Trash, X } from 'lucide-svelte'
import {
Archive,
ArchiveRestore,
FolderInput,
MoreHorizontal,
Trash,
WandSparkles,
X
} from 'lucide-svelte'
import {
homeComposerContext,
itemContextElement
} from '$lib/components/sessions/homeComposerContext.svelte'
import { fly } from 'svelte/transition'
import {
blockedReason,
@@ -49,6 +61,17 @@
})
let items = $derived(selection.items.length > 0 ? selection.items : lastNonEmpty)
// What of the selection the composer can take as context; the rest has no context element.
let askAiElements = $derived(
items.flatMap((i) => itemContextElement({ ...i, summary: i.summary || undefined }) ?? [])
)
// The selection was the way to gather them; once they are in the composer it is done.
async function askAi() {
const elements = askAiElements
selection.exit()
for (const element of elements) await homeComposerContext.attach(element)
}
let reducedMotion = useReducedMotion()
const plural = (n: number) => (n === 1 ? '' : 's')
@@ -184,6 +207,20 @@
{items.length} selected
</span>
<div class="h-4 border-l"></div>
{#if homeComposerContext.available && askAiElements.length > 0}
<Button
variant="subtle"
unifiedSize="sm"
btnClasses="!text-ai"
startIcon={{ icon: WandSparkles }}
title={askAiElements.length < items.length
? `Add the ${askAiElements.length} scripts, flows and code apps of the selection to the chat above`
: 'Add the selection to the chat above'}
on:click={askAi}
>
Ask AI{askAiElements.length < items.length ? ` (${askAiElements.length})` : ''}
</Button>
{/if}
<Button
variant="subtle"
unifiedSize="sm"
@@ -11,7 +11,7 @@
</script>
<script lang="ts">
import { ExternalLink, Globe2, PlugZap, WandSparkles } from 'lucide-svelte'
import { ExternalLink, Globe2, PinOff, PlugZap, WandSparkles } from 'lucide-svelte'
import Button from '../common/button/Button.svelte'
import CloseButton from '../common/CloseButton.svelte'
import { logFeatureUsage } from '$lib/utils/featureUsage'
@@ -30,6 +30,7 @@
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
import { prefetchItemCount } from '../copilot/chat/starter/starterPrompts.svelte'
const COLLAPSED_SETTING = 'home-ai-composer-collapsed'
@@ -42,20 +43,21 @@
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
// How much of the home page this reader wants the composer to take, so it lives per browser
// rather than per workspace or account.
let collapsed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true')
function setCollapsed(next: boolean) {
collapsed = next
// Whether this reader wants the composer on the home page at all, so it lives per browser
// rather than per workspace or account. The setting's name predates the composer's own
// one-line state, which is unrelated.
let removed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true')
function setRemoved(next: boolean) {
removed = next
storeLocalSetting(COLLAPSED_SETTING, next ? 'true' : undefined)
}
// 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
// the hero collapses in the middle of the page.
// the composer leaves the page.
//
// A keyframe animation, not a transition: this mounts in the same flush that collapses the
// hero, so the frame that would paint it at rest is the frame it is already told to leave, and
// A keyframe animation, not a transition: this mounts in the same flush that removes the
// composer, so the frame that would paint it at rest is the frame it is already told to leave, and
// one `requestAnimationFrame` is not reliably past that paint. The flash then goes straight to
// invisible without ever being drawn. Mounted only while pulsing, so each removal replays it.
const PULSE_MS = 1000
@@ -65,7 +67,7 @@
function removeComposer() {
logFeatureUsage('home', 'ai_hero_remove', { key: 'close' })
setCollapsed(true)
setRemoved(true)
if (reducedMotion.val) return
clearTimeout(pulseEndTimer)
pulsing = true
@@ -90,7 +92,10 @@
let shownForRoot = $state<string>()
let HomeSessionStarter = $state(loadedStarter)
if (!HomeSessionStarter) void loadStarter().then((c) => (HomeSessionStarter = c))
if (!loadedStarter) void loadStarter().then((c) => (HomeSessionStarter = c))
// The starter waits on the workspace's item count before it mounts; asked alongside its code
// rather than once the code has loaded, it is no extra wait.
if ($workspaceStore) prefetchItemCount($workspaceStore)
// Whether Home's own workspace hides the assistant, read for that workspace directly: the
// shared copilot config follows whichever workspace loaded last, and once the block shows
@@ -119,19 +124,21 @@
prefersSessionHandoff($userStore?.operator) && !runOnlyWorkspace && !homeAiHidden.current
)
// The hero's margins and centered column are for the full block. The lone button row left
// by a collapsed, opted-out, run-only or hidden-assistant view is a hint line and should
// cost the page almost nothing: no top margin, and the content column's full width so it
// hugs the right edge instead of floating centered in empty space.
let hero = $derived(showComposer && !collapsed)
let outerSpacing = $derived(hero ? 'mt-20 mb-16' : 'mt-0 mb-1')
let hero = $derived(showComposer && !removed)
</script>
<div class="w-full flex justify-center {outerSpacing}">
<div class="{hero ? 'max-w-3xl' : ''} grow relative group">
<div class="w-full {hero ? 'mt-2' : 'mb-1'}">
<div class="relative group/composer">
{#if hero}
<div class="absolute right-0 top-0 z-20">
<CloseButton small noBg title="Remove session chat" onClick={removeComposer} />
<!-- In the page's side padding, clear of the composer's own controls at its right end,
and centred on the composer's first row: the one-line box's middle, and where that
row stays once the box opens downward. Shown on hover only where there is hover
(from the `sm` width up); the container starts at the composer's edge so the
pointer reaches the cross without leaving the hovered zone. -->
<div
class="absolute right-0 -top-6 sm:top-4 sm:right-auto sm:left-full sm:pl-1 z-20 transition-opacity sm:opacity-0 sm:group-hover/composer:opacity-100 sm:focus-within:opacity-100"
>
<CloseButton small noBg Icon={PinOff} title="Unpin from Home" onClick={removeComposer} />
</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
@@ -192,7 +199,7 @@
<!-- No menu while the hero is on the page and its side trips are in the bar: the hero's own
cross removes it, so an ellipsis holding a second way to do that is a button whose only
item is a duplicate. -->
{#if !sideTripsInBar || (showComposer && collapsed)}
{#if !sideTripsInBar || (showComposer && removed)}
<!-- The flash rides the ellipsis itself, not the row: with the side trips beside it the
row is three controls wide, and marking all three names none of them. -->
<span class="relative inline-flex">
@@ -209,14 +216,14 @@
placement="bottom-end"
size="sm"
items={[
...(showComposer && collapsed
...(showComposer && removed
? [
{
displayName: 'Pin session hero to homepage',
icon: WandSparkles,
action: () => {
logFeatureUsage('home', 'ai_hero_pin')
setCollapsed(false)
setRemoved(false)
}
}
]
+340 -278
View File
@@ -2,7 +2,6 @@
import CenteredPage from '$lib/components/CenteredPage.svelte'
import { PIPELINE_DRAFT_KIND, pipelineFolderFromBundlePath } from '$lib/pipelinePaths'
import { Button, Skeleton } from '$lib/components/common'
import Toggle from '$lib/components/Toggle.svelte'
import {
AssetService,
FolderService,
@@ -23,16 +22,20 @@
import {
ArrowDownUp,
Bot,
ChevronDown,
ChevronsDownUp,
ChevronsUpDown,
Code2,
LayoutDashboard,
List,
ListTree,
MoreHorizontal,
Tag
} from 'lucide-svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import CreateActionsMenu from './CreateActionsMenu.svelte'
import ContentSearchInner from '$lib/components/ContentSearchInner.svelte'
import type { Item as MenuItem } from '$lib/utils'
import type { IconType, Item as MenuItem } from '$lib/utils'
import { HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts'
@@ -46,9 +49,11 @@
import HubProjectPickerModal from './HubProjectPickerModal.svelte'
import type { HubProjectPick } from '$lib/hubProject'
import ListFilters from './ListFilters.svelte'
import LabelBadge from '../common/badge/LabelBadge.svelte'
import { clampRows } from './clampRows'
import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte'
import FlowIcon from './FlowIcon.svelte'
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
import { getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils'
import { sendUserToast } from '$lib/toast'
import Drawer from '../common/drawer/Drawer.svelte'
@@ -183,7 +188,7 @@
// (which carries only path + content), so the row-list filters can't
// apply to it. When it's active we restrict the searchbar to just the content filter,
// clear any other filters so they don't linger as ignored chips, and hide the row-list
// controls (kind toggle, tree view) that no longer drive anything.
// controls (kind filter, tree view) that no longer drive anything.
let contentActive = $derived(!!filterValues.val.content)
let searchbarSchema = $derived(
contentActive ? { content: searchFilterSchema.content } : searchFilterSchema
@@ -777,11 +782,11 @@
const SORT_SETTING_NAME = 'homeSort'
// `short` labels the trigger button next to the sort icon (the button is icon-only
// only while searching, when sorting is disabled — see below).
const sortOptions: { value: SortOrder; label: string; short: string }[] = [
{ value: 'updated_desc', label: 'Recently updated', short: 'Recent' },
{ value: 'updated_asc', label: 'Oldest updated', short: 'Oldest' },
{ value: 'name_asc', label: 'Name (A-Z)', short: 'A-Z' },
{ value: 'name_desc', label: 'Name (Z-A)', short: 'Z-A' }
const sortOptions: { value: SortOrder; label: string }[] = [
{ value: 'updated_desc', label: 'Recently updated' },
{ value: 'updated_asc', label: 'Oldest updated' },
{ value: 'name_asc', label: 'Name (A-Z)' },
{ value: 'name_desc', label: 'Name (Z-A)' }
]
let sortOrder = $state<SortOrder>(
sortOptions.find((o) => o.value === getLocalSetting(SORT_SETTING_NAME))?.value ?? 'updated_desc'
@@ -860,6 +865,9 @@
}
}
let toolbarHeight = $state(0)
let chipsExpanded = $state(false)
const TREE_VIEW_SETTING_NAME = 'treeView'
let treeView = $state(getLocalSetting(TREE_VIEW_SETTING_NAME) == 'true')
@@ -1018,6 +1026,39 @@
}
)
let ownerCounts = $derived(ownerCountsRes.current)
type KindOption = {
value: 'all' | 'script' | 'flow' | 'app' | 'agent'
label: string
icon?: IconType
}
const kindOptions: KindOption[] = [
{ value: 'all', label: 'All kinds' },
{ value: 'script', label: 'Scripts', icon: Code2 },
...(HOME_SEARCH_SHOW_FLOW
? [{ value: 'flow', label: 'Flows', icon: BarsStaggered } satisfies KindOption]
: []),
{ value: 'app', label: 'Apps', icon: LayoutDashboard },
{ value: 'agent', label: 'Agents', icon: Bot }
]
function setItemKind(v: KindOption['value']) {
// itemKind is derived from the shared filter object (which URL-syncs itself); `all`
// clears the kind filter (delete, not null, so it doesn't linger as a `kind: null` chip).
if (v === 'all') {
delete filterValues.val.kind
} else {
filterValues.val.kind = v
subtab = v
}
}
let kindItems = $derived(
kindOptions.map((o) => ({
displayName: o.label,
icon: o.icon,
selected: itemKind === o.value,
action: () => setItemKind(o.value)
}))
)
// The counts decide which owners the tree renders, so drawing it before they land
// would show every workspace folder and then prune it away. Hold the skeleton
// until the first response instead — it is fetched in parallel with the listing,
@@ -1795,273 +1836,271 @@
</DrawerContent>
</Drawer>
<CenteredPage wrapperClasses="w-full" handleOverflow={false}>
<div
class="flex flex-wrap gap-2 items-center justify-between w-full"
use:triggerableByAI={{
id: 'home-items-list',
description: 'Lists of scripts, flows, and apps'
}}
>
{#if !contentActive}
<!-- Kept mounted, not hidden, so the toolbar doesn't reflow the moment the first item
lands; `inert` takes it out of the tab order and off the pointer meanwhile. A
workspace with nothing but archived items reaches them from its own placeholder,
so these controls are not the way there — but only where that placeholder
renders, which is what `placeholderTakesOver` tracks. -->
<div class="flex justify-start" class:opacity-40={placeholderTakesOver} inert={toolbarInert}>
<ToggleButtonGroup
selected={itemKind}
onSelected={(v) => {
// itemKind is derived from the shared filter object (which URL-syncs itself);
// `all` clears the kind filter (delete, not null, so it doesn't linger as a
// `kind: null` chip).
if (v === 'all') {
delete filterValues.val.kind
} else {
filterValues.val.kind = v
subtab = v
}
}}
>
{#snippet children({ item })}
<ToggleButton value="all" label="All" size="md" {item} />
<ToggleButton value="script" icon={Code2} label="Scripts" size="md" {item} />
{#if HOME_SEARCH_SHOW_FLOW}
<!-- The width of Home's column above it (the composer), so the page reads as one column. -->
<CenteredPage wrapperClasses="w-full pb-6" class="max-w-[1120px] sm:px-8" handleOverflow={false}>
<!-- One card for the items section: its controls, its filters and its rows, the way the
composer above is one box for the chat. The rows run edge to edge inside it. No
`overflow-hidden` on it: the page scrolls, and that would stop the controls sticking. -->
<div class="flex flex-col">
<div
bind:clientHeight={toolbarHeight}
class="sticky top-0 z-10 bg-surface flex flex-wrap gap-2 items-center justify-between px-4 sm:-mx-4 py-3 shrink-0"
use:triggerableByAI={{
id: 'home-items-list',
description: 'Lists of scripts, flows, and apps'
}}
>
{#if !loading && !contentActive && !workspaceEmpty}
<!-- List controls, before the searchbar: list or tree, expand/collapse (tree only),
sort. Nothing to group or order on an empty workspace, so the whole row goes. -->
<div class="flex items-center gap-2">
<ToggleButtonGroup
selected={treeView ? 'tree' : 'list'}
onSelected={(v) => (treeView = v === 'tree')}
>
{#snippet children({ item })}
<ToggleButton
value="flow"
label="Flows"
icon={FlowIcon}
selectedColor="#14b8a6"
size="md"
value="list"
icon={List}
label="List"
iconOnly
tooltip="List view"
size="sm"
{item}
/>
{/if}
<ToggleButton
value="app"
label="Apps"
icon={LayoutDashboard}
selectedColor="#fb923c"
size="md"
{item}
/>
<ToggleButton
value="agent"
label="Agents"
icon={Bot}
selectedColor="#8b5cf6"
size="md"
{item}
/>
{/snippet}
</ToggleButtonGroup>
</div>
{/if}
{#if !loading && !contentActive && !workspaceEmpty}
<!-- List controls, between the kind toggle and the searchbar: tree view,
expand/collapse (tree only), sort. Nothing to group or order on an empty
workspace, so the whole row goes. -->
<div class="flex items-center gap-2">
<Toggle size="xs" bind:checked={treeView} options={{ right: 'Tree view' }} />
{#if treeView}
<Button
unifiedSize="sm"
variant="subtle"
on:click={() => (collapseAll = !collapseAll)}
startIcon={{ icon: collapseAll ? ChevronsUpDown : ChevronsDownUp }}
<ToggleButton
value="tree"
icon={ListTree}
label="Tree"
iconOnly
tooltip="Tree view"
size="sm"
{item}
/>
{/snippet}
</ToggleButtonGroup>
<!-- Icon only: the order's name is in the tooltip and the menu, so next to the
search and the kind filter the list's own controls stay out of the way. -->
<DropdownV2
items={sortItems}
disabled={filter !== ''}
placement="bottom-start"
fixedHeight={false}
>
{#if collapseAll}
Expand all
{:else}
Collapse all
{/if}
</Button>
{/if}
<DropdownV2
items={sortItems}
disabled={filter !== ''}
placement="bottom-end"
fixedHeight={false}
>
{#snippet buttonReplacement()}
{@const active = sortOptions.find((o) => o.value === sortOrder)}
{@const short = filter !== '' ? '' : (active?.short ?? '')}
{#snippet buttonReplacement()}
{@const active = sortOptions.find((o) => o.value === sortOrder)}
<Button
nonCaptureEvent
disabled={filter !== ''}
iconOnly
unifiedSize="sm"
variant="default"
startIcon={{ icon: ArrowDownUp }}
title={filter !== ''
? 'Sorting is disabled while searching (results are ranked by relevance)'
: `Sort: ${active?.label ?? ''}`}
/>
{/snippet}
</DropdownV2>
{#if treeView}
<Button
nonCaptureEvent
disabled={filter !== ''}
iconOnly={short === ''}
unifiedSize="xs"
unifiedSize="sm"
variant="default"
startIcon={{ icon: ArrowDownUp }}
title={filter !== ''
? 'Sorting is disabled while searching (results are ranked by relevance)'
: `Sort: ${active?.label ?? ''}`}
>
{#if short !== ''}{short}{/if}
</Button>
{/snippet}
</DropdownV2>
</div>
{/if}
iconOnly
title={collapseAll ? 'Expand all' : 'Collapse all'}
on:click={() => (collapseAll = !collapseAll)}
startIcon={{ icon: collapseAll ? ChevronsUpDown : ChevronsDownUp }}
/>
{/if}
</div>
{/if}
<div class="flex grow items-center justify-end gap-2 min-w-0">
<div
class="relative text-primary w-full min-w-[200px] max-w-[26rem]"
class:opacity-40={placeholderTakesOver}
inert={toolbarInert}
>
<FilterSearchbar
schema={searchbarSchema}
bind:value={filterValues.val}
placeholder={HOME_SEARCH_PLACEHOLDER}
presets={contentActive ? [] : searchPresets}
autofocus
hideDropdownOnFreeText
inputId="home-search-input"
onDropdownVisibleChange={(v) => (searchbarDropdownOpen = v)}
/>
</div>
<!-- Same gate the old create actions used: hidden from operators and in workspaces
<!-- basis-64: the toolbar fits Home's column on one line; narrower, this group wraps
under the heading as a whole. -->
<div class="flex grow basis-64 items-center justify-end gap-2 min-w-0">
<div
class="relative text-primary w-full min-w-[200px] max-w-[22rem]"
class:opacity-40={placeholderTakesOver}
inert={toolbarInert}
>
<FilterSearchbar
schema={searchbarSchema}
bind:value={filterValues.val}
placeholder={HOME_SEARCH_PLACEHOLDER}
presets={contentActive ? [] : searchPresets}
autofocus
hideDropdownOnFreeText
inputId="home-search-input"
onDropdownVisibleChange={(v) => (searchbarDropdownOpen = v)}
/>
</div>
{#if !contentActive}
<!-- Kept mounted, not hidden, so the toolbar doesn't reflow the moment the first
item lands; `inert` takes it out of the tab order and off the pointer meanwhile.
A workspace with nothing but archived items reaches them from its own
placeholder, so this is not the way there — but only where that placeholder
renders, which is what `placeholderTakesOver` tracks. -->
<div class="shrink-0" class:opacity-40={placeholderTakesOver} inert={toolbarInert}>
<DropdownV2 items={kindItems} placement="bottom-end" fixedHeight={false}>
{#snippet buttonReplacement()}
{@const active = kindOptions.find((o) => o.value === itemKind)}
<Button
nonCaptureEvent
unifiedSize="md"
variant="default"
title="Filter by kind"
startIcon={active?.icon ? { icon: active.icon } : undefined}
endIcon={{ icon: ChevronDown }}
>
{active?.label ?? 'All kinds'}
</Button>
{/snippet}
</DropdownV2>
</div>
{/if}
<!-- 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}
<!-- No hub entry where the instance has the hub turned off: the same setting the
{#if canCreateHere}
<!-- 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. -->
<CreateActionsMenu
onImportHubProject={$disableHubStore || !editRights.roleCanAuthor('script')
? undefined
: () => (hubPickerOpen = true)}
/>
{/if}
<CreateActionsMenu
onImportHubProject={$disableHubStore || !editRights.roleCanAuthor('script')
? undefined
: () => (hubPickerOpen = true)}
/>
{/if}
</div>
</div>
</div>
{#if !contentActive && hasChips}
<!-- Owner and label chips on one line. Each function binding routes the chip's
<!-- The chips scroll away with the rows; only the controls above stay. -->
{#if !contentActive && hasChips}
<!-- Owner and label chips on one line. Each function binding routes the chip's
selection into the searchbar key of the same name, and `queryName` points
ListFilters' own mount-time URL read at the param the filter instance syncs, so
the two writers agree. No `syncQuery`: the filter instance owns the URL. -->
<div class="gap-2 w-full flex flex-wrap mt-3">
<ListFilters
inline
bind:selectedFilter={() => ownerFilter, setOwnerFilter}
filters={owners}
queryName="owner"
maxDisplayed={10}
/>
<ListFilters
inline
bind:selectedFilter={() => labelFilter, setLabelFilter}
filters={allLabels}
queryName="label"
maxDisplayed={10}
color="blue"
icon={Tag}
/>
</div>
{/if}
{#if filteredItems?.length == 0 && !workspaceEmpty}
<div class="mt-10"></div>
{/if}
<div class="mt-3">
{#if filterValues.val.content}
<!-- Content filter: swap the normal list/tree for the content-match view (the same one
<div
class="gap-x-2 gap-y-0.5 w-full flex flex-wrap px-4 sm:px-0 pb-3"
use:clampRows={{ rows: 2, expanded: chipsExpanded }}
>
<ListFilters
inline
bind:selectedFilter={() => ownerFilter, setOwnerFilter}
filters={owners}
color="subtle"
queryName="owner"
/>
<ListFilters
inline
bind:selectedFilter={() => labelFilter, setLabelFilter}
filters={allLabels}
queryName="label"
color="subtle"
icon={Tag}
/>
<div data-clamp-toggle hidden>
<LabelBadge
icon={chipsExpanded ? undefined : MoreHorizontal}
title={chipsExpanded ? 'Show fewer filters' : 'Show all filters'}
onclick={() => (chipsExpanded = !chipsExpanded)}
>
{#if chipsExpanded}Show less{/if}
</LabelBadge>
</div>
</div>
<!-- Its own element, not the chips' border: it stays under the controls once the chips
have scrolled away. -->
<div class="sticky z-10 border-b" style:top="{toolbarHeight}px"></div>
{/if}
{#if filteredItems?.length == 0 && !workspaceEmpty}
<div class="mt-10"></div>
{/if}
<!-- Rows keep their own padding for the hover fill; pulled out by it, their content
lines up with the controls above and the fill runs into the page's gutter. -->
<div class="sm:-mx-4">
{#if filterValues.val.content}
<!-- Content filter: swap the normal list/tree for the content-match view (the same one
used by the Ctrl-K "Content" modal). It loads the workspace's scripts/flows/apps/
resources and matches their contents client-side — usable on any instance. Keyed by
workspace so a switch remounts a fresh instance and late in-flight responses from
the previous workspace can't land in it. -->
<!-- -mx-2 cancels ContentSearchInner's own px-2 so its rows line up flush with the
runnable list instead of sitting slightly inset. -->
<div class="-mx-2">
{#key $workspaceStore}
<ContentSearchInner bind:this={contentSearchEl} search={filterValues.val.content} />
{/key}
</div>
{:else if filteredItems == undefined || treeCountsPending}
<div class="mt-4"></div>
<Skeleton layout={[[2], 1]} />
{#each new Array(6) as _}
<Skeleton layout={[[4], 0.5]} />
{/each}
{:else if filteredItems.length === 0 && (filter !== '' || visiblePipelineFolders.size === 0)}
<!-- Pipelines aren't part of the text filter, so only fall through to show
<!-- px-1 plus ContentSearchInner's own px-2 lines its rows up with the card's
controls above. -->
<div class="px-1 pb-2">
{#key $workspaceStore}
<ContentSearchInner bind:this={contentSearchEl} search={filterValues.val.content} />
{/key}
</div>
{:else if filteredItems == undefined || treeCountsPending}
<div class="px-4 pb-3">
<div class="mt-4"></div>
<Skeleton layout={[[2], 1]} />
{#each new Array(6) as _}
<Skeleton layout={[[4], 0.5]} />
{/each}
</div>
{:else if filteredItems.length === 0 && (filter !== '' || visiblePipelineFolders.size === 0)}
<div class="px-4 pb-3">
<!-- Pipelines aren't part of the text filter, so only fall through to show
them (list rows / injected tree folders) when not actively searching;
a no-match search still reads as empty. -->
{#if workspaceEmpty}
<!-- Held until the archived probe answers rather than drawn and swapped: the two
{#if workspaceEmpty}
<!-- Held until the archived probe answers rather than drawn and swapped: the two
placeholders say different things, and showing the wrong one first says the
workspace is empty when it is not. -->
{#if emptyStateAnswered}
{#if archivedProbe?.hasArchived || canCreateHere}
<!-- Shown to whoever has something to do here: the archived notice to
{#if emptyStateAnswered}
{#if archivedProbe?.hasArchived || canCreateHere}
<!-- Shown to whoever has something to do here: the archived notice to
everyone, since reading archived items is not a write, and the create
actions only to a user who may take them. -->
<WorkspaceEmptyState
archivedOnly={archivedProbe?.hasArchived === true}
canCreate={canCreateHere}
onPick={(project) => (hubPick = project)}
onShowArchived={() => (filterValues.val = { ...filterValues.val, archived: true })}
/>
<WorkspaceEmptyState
archivedOnly={archivedProbe?.hasArchived === true}
canCreate={canCreateHere}
onPick={(project) => (hubPick = project)}
onShowArchived={() =>
(filterValues.val = { ...filterValues.val, archived: true })}
/>
{:else}
<NoItemFound {activeFilters} />
{/if}
{/if}
{:else}
<NoItemFound {activeFilters} />
{/if}
{/if}
{:else}
<NoItemFound {activeFilters} />
{/if}
{#if hasMoreServer && !searching}
<!-- The active filter matched nothing on the loaded pages, but the server
{#if hasMoreServer && !searching}
<!-- The active filter matched nothing on the loaded pages, but the server
has more: keep paging reachable so matches on later pages aren't lost. -->
<div class="text-center text-xs text-secondary mt-2">
<button class="text-primary hover:text-emphasis underline" onclick={fetchMoreServer}
>Load more to search further</button
>
<div class="text-center text-xs text-secondary mt-2">
<button class="text-primary hover:text-emphasis underline" onclick={fetchMoreServer}
>Load more to search further</button
>
</div>
{/if}
</div>
{/if}
{:else if treeView}
<!-- Remount the tree on a MODE change only (treeKey = view/owner/search/label):
{:else if treeView}
<!-- Remount the tree on a MODE change only (treeKey = view/owner/search/label):
expanded folders (their `opened` state is local to each TreeView) collapse
and re-load fresh for the new mode. An in-place order/archive/library/kind
change keeps treeKey stable, so folders stay open and refresh via
reloadItems instead (see loadOwnerItems). -->
{#key treeKey}
<TreeViewRoot
items={treeSource}
{collapseAll}
sortCompare={compareItems}
groupDesc={sortOrder === 'name_desc'}
hasMoreServer={treeGlobalHasMore}
onLoadMore={fetchMoreServer}
pipelineFolders={visiblePipelineFolders}
allFolders={treeInjectFolders}
allUsers={treeInjectUsers}
ownerCounts={!searching && labelFilter == undefined ? ownerCounts : undefined}
selfUsername={$userStore?.username}
groupOtherUsers={treeLazyMode}
ownerLoad={treeLazyMode ? ownerLoad : undefined}
onExpandOwner={treeLazyMode ? loadOwnerItems : undefined}
onCollapseOwner={treeLazyMode ? collapseOwner : undefined}
isSearching={filter !== ''}
on:scriptChanged={reloadItemsAndCounts}
on:flowChanged={reloadItemsAndCounts}
on:appChanged={reloadItemsAndCounts}
on:rawAppChanged={reloadItemsAndCounts}
on:reload={reloadItemsAndCounts}
{showCode}
showEditButton={showEditButtons}
/>
{/key}
{:else}
<div class="border rounded-md bg-surface-tertiary" class:wm-imported={justImported}>
{#if filter === ''}
{#each [...visiblePipelineFolders].sort() as folder (folder)}
<PipelineRow {folder} onDeleted={reloadItemsAndCounts} />
{/each}
{/if}
{#each displayedItems as item, i (item.type + '/' + item.path + (item.hash ? '/' + item.hash : ''))}
<Item
{item}
{#key treeKey}
<TreeViewRoot
items={treeSource}
{collapseAll}
sortCompare={compareItems}
groupDesc={sortOrder === 'name_desc'}
hasMoreServer={treeGlobalHasMore}
onLoadMore={fetchMoreServer}
pipelineFolders={visiblePipelineFolders}
allFolders={treeInjectFolders}
allUsers={treeInjectUsers}
ownerCounts={!searching && labelFilter == undefined ? ownerCounts : undefined}
selfUsername={$userStore?.username}
groupOtherUsers={treeLazyMode}
ownerLoad={treeLazyMode ? ownerLoad : undefined}
onExpandOwner={treeLazyMode ? loadOwnerItems : undefined}
onCollapseOwner={treeLazyMode ? collapseOwner : undefined}
isSearching={filter !== ''}
on:scriptChanged={reloadItemsAndCounts}
on:flowChanged={reloadItemsAndCounts}
on:appChanged={reloadItemsAndCounts}
@@ -2069,45 +2108,68 @@
on:reload={reloadItemsAndCounts}
{showCode}
showEditButton={showEditButtons}
keyboardSelected={selectedIndex === i}
framed={false}
/>
{/each}
</div>
{#if items && hasMore}
<span class="text-xs font-normal text-secondary"
>{Math.min(nbDisplayed, items.length)} items{hasMoreServer && !searching
? ''
: ` out of ${items.length}`}
<button
bind:this={loadMoreEl}
class="ml-4 text-xs font-normal text-primary hover:text-emphasis rounded px-1 {selectedIndex ===
loadMoreIndex
? 'bg-gray-200 dark:bg-gray-700 underline'
: ''}"
onclick={loadMore}>load 30 more</button
></span
>
{/if}
{/if}
{#if searching && searchCursor}
<!-- The server has further search matches beyond the page already merged in;
fetch them one page at a time on demand rather than auto-downloading a
broad query's entire result set. -->
<div class="text-center text-xs text-secondary mt-2">
{#if searchLoadingMore}
Loading more results…
{:else}
<button class="text-primary hover:text-emphasis underline" onclick={loadMoreSearchResults}
>Load more results</button
{/key}
{:else}
<!-- No lines between rows: the card holds one list, and the row hover tells them apart. -->
<div data-unruled data-hover-actions class="rounded-b-md" class:wm-imported={justImported}>
{#if filter === ''}
{#each [...visiblePipelineFolders].sort() as folder (folder)}
<PipelineRow {folder} onDeleted={reloadItemsAndCounts} />
{/each}
{/if}
{#each displayedItems as item, i (item.type + '/' + item.path + (item.hash ? '/' + item.hash : ''))}
<Item
{item}
on:scriptChanged={reloadItemsAndCounts}
on:flowChanged={reloadItemsAndCounts}
on:appChanged={reloadItemsAndCounts}
on:rawAppChanged={reloadItemsAndCounts}
on:reload={reloadItemsAndCounts}
{showCode}
showEditButton={showEditButtons}
keyboardSelected={selectedIndex === i}
/>
{/each}
</div>
{#if items && hasMore}
<span class="block px-4 py-2 border-t text-xs font-normal text-secondary"
>{Math.min(nbDisplayed, items.length)} items{hasMoreServer && !searching
? ''
: ` out of ${items.length}`}
<button
bind:this={loadMoreEl}
class="ml-4 text-xs font-normal text-primary hover:text-emphasis rounded px-1 {selectedIndex ===
loadMoreIndex
? 'bg-gray-200 dark:bg-gray-700 underline'
: ''}"
onclick={loadMore}>load 30 more</button
></span
>
{/if}
</div>
{/if}
{#if homeSelection.active}
<!-- The bar floats over the page bottom; without this the last rows sit
under it with no way to scroll them clear. -->
<div class="h-20"></div>
{/if}
{/if}
{#if searching && searchCursor}
<!-- The server has further search matches beyond the page already merged in;
fetch them one page at a time on demand rather than auto-downloading a
broad query's entire result set. -->
<div class="text-center text-xs text-secondary py-2 border-t">
{#if searchLoadingMore}
Loading more results…
{:else}
<button
class="text-primary hover:text-emphasis underline"
onclick={loadMoreSearchResults}>Load more results</button
>
{/if}
</div>
{/if}
{#if homeSelection.active}
<!-- The bar floats over the list's bottom; without this the last rows sit
under it with no way to scroll them clear. -->
<div class="h-20"></div>
{/if}
</div>
</div>
</CenteredPage>
@@ -1,6 +1,6 @@
<script lang="ts">
import { Folder, User } from 'lucide-svelte'
import { Badge } from '../common'
import LabelBadge from '../common/badge/LabelBadge.svelte'
import type { BadgeColor, BadgeIconProps } from '../common/badge/model'
import { appIconComponent } from '../icons/appIcon.svelte'
import { integrationDisplayName } from '../resourceTypeDisplay'
@@ -14,9 +14,6 @@
queryName?: string
syncQuery?: boolean
bottomMargin?: boolean
// Keep only the first N filters visible, the rest behind a "…" toggle. Unset
// shows every one.
maxDisplayed?: number
// Chip look. `icon` is drawn before every chip; unset, the icon follows the value
// (user/folder prefix, or the app icon under `resourceType`).
color?: BadgeColor
@@ -34,7 +31,6 @@
queryName = 'filter',
syncQuery = false,
bottomMargin = true,
maxDisplayed,
color = 'transparent',
icon,
inline = false
@@ -76,71 +72,39 @@
: [selectedFilter, ...filters]
: filters
)
let expanded = $state(false)
let truncated = $derived.by(() => {
if (maxDisplayed == undefined || filtersAndSelected.length <= maxDisplayed)
return filtersAndSelected
const shown = filtersAndSelected.slice(0, maxDisplayed)
// Clicking the selected chip is how the filter is cleared, so it is never truncated
// away, however far down the order it sits.
if (selectedFilter && !shown.includes(selectedFilter)) shown.push(selectedFilter)
return shown
})
// Derived from what is actually withheld, so the selected chip kept above never counts
// as hidden — otherwise the toggle offers to reveal a chip that is already on screen.
let hiddenCount = $derived(filtersAndSelected.length - truncated.length)
let displayedFilters = $derived(expanded ? filtersAndSelected : truncated)
</script>
{#if Array.isArray(filtersAndSelected) && filtersAndSelected.length > 0}
<div
class={inline ? 'contents' : `gap-2 w-full flex flex-wrap ${bottomMargin ? 'my-4' : 'mt-4'}`}
>
{#each displayedFilters as filter (filter)}
<div>
<Badge
class="inline-flex items-center gap-1 align-middle"
{#each filtersAndSelected as filter (filter)}
<div data-chip data-selected={filter === selectedFilter ? '' : undefined}>
<LabelBadge
{color}
icon={icon ??
(resourceType
? undefined
: filter.startsWith('u/')
? User
: filter.startsWith('f/')
? Folder
: undefined)}
selected={filter === selectedFilter}
onclick={() => {
selectedFilter = selectedFilter == filter ? undefined : filter
writeQuery(selectedFilter)
}}
{color}
clickable
selected={filter === selectedFilter}
>
<span style="height: 12px" class="-mt-0.5">
{#if icon}
{@const Icon = icon}
<Icon class="mr-0.5" size={12} />
{:else if resourceType}
{@const SvelteComponent = appIconComponent(filter)}
{#if SvelteComponent}
<SvelteComponent height="14px" width="14px" />
{/if}
{:else if filter.startsWith('u/')}
<User class="mr-0.5" size={14} />
{:else if filter.startsWith('f/')}
<Folder class="mr-0.5" size={14} />
{#if !icon && resourceType}
{@const AppIcon = appIconComponent(filter)}
{#if AppIcon}
<AppIcon height="12px" width="12px" />
{/if}
</span>
{/if}
{resourceType ? integrationDisplayName(filter) : filter}
{#if filter === selectedFilter}&cross;{/if}
</Badge>
</LabelBadge>
</div>
{/each}
{#if hiddenCount > 0}
<div>
<Badge
class="inline-flex items-center gap-1 align-middle"
{color}
clickable
title={expanded ? 'Show fewer' : `Show ${hiddenCount} more`}
onclick={() => (expanded = !expanded)}
>
{expanded ? 'Show less' : '…'}
</Badge>
</div>
{/if}
</div>
{/if}
@@ -266,7 +266,8 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
onclick={toggleOwner}
class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer"
data-list-row
class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover"
>
<div
class={twMerge('flex flex-row items-center gap-4 text-sm font-semibold')}
@@ -350,6 +351,7 @@
{/each}
{#if effectiveMax < item.items.length}
<div
data-list-row
class="px-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary"
style="padding-left: {(visualDepth + 1) * 16}px;"
>
@@ -387,6 +389,7 @@
is the point: without them this reads as an optional extra rather than
as rows still missing. -->
<div
data-list-row
class="px-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary"
style="padding-left: {(visualDepth + 1) * 16}px;"
>
@@ -40,6 +40,8 @@
onExpandOwner?: (owner: string, more?: boolean, opts?: { all?: boolean }) => void
onCollapseOwner?: (owner: string) => void
showEditButton?: boolean
/** Off where the tree sits in a card of its host's, which already draws the frame. */
framed?: boolean
// Tuck every user space but `selfUsername`'s into one collapsible "Other users" row
// under it. Only for browsing: a search or filter must not hide its matches behind
// a closed row.
@@ -66,6 +68,7 @@
onExpandOwner,
onCollapseOwner,
showEditButton = true,
framed = true,
groupOtherUsers = false,
leaf
}: Props = $props()
@@ -280,7 +283,12 @@
<!-- Every row draws its own border-b, so the last one would double the frame's bottom border.
Pulling the content 1px down puts that border under the frame, where overflow-hidden
clips it, whichever row (collapsed owner, leaf, expanded subtree) ends the list. -->
<div class="border rounded-md bg-surface-tertiary overflow-hidden">
<!-- Unframed, the tree is part of a card that separates nothing between its rows. -->
<div
data-unruled={framed ? undefined : true}
data-hover-actions={framed ? undefined : true}
class="{framed ? 'border rounded-md bg-surface-tertiary' : 'rounded-b-md'} overflow-hidden"
>
<div class="-mb-px">
{#each rows.slice(0, nbDisplayed) as row (row.kind === 'otherUsers' ? 'other_users' : 'folderName' in row.node ? `f__${row.node.folderName}` : 'username' in row.node ? `u__${row.node.username}` : `i__${row.node.type}__${row.node.path}`)}
{#if row.kind === 'otherUsers'}
@@ -290,7 +298,8 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
onclick={toggleOtherUsers}
class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer"
data-list-row
class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover"
>
<div class="flex flex-row items-center gap-4">
<Users size={16} class="text-secondary" />
@@ -324,6 +333,7 @@
{/each}
{#if nbOtherUsersDisplayed < otherUsers.length}
<div
data-list-row
class="pl-8 pr-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary"
>
<span class="text-xs text-secondary">
@@ -0,0 +1,62 @@
import type { Action } from 'svelte/action'
export type ClampRowsOptions = { rows: number; expanded: boolean }
/**
* Keeps a wrapping row of `[data-chip]` items to `rows` lines, measured rather than counted, so
* how many fit follows the width. The `[data-clamp-toggle]` child shows only on overflow, and
* while collapsed it takes the end of the last line: items are hidden from there back until it
* fits. A `[data-selected]` item is never hidden, since clicking it is how its filter clears.
*/
export const clampRows: Action<HTMLElement, ClampRowsOptions> = (node, initial) => {
let options = initial
let frame = 0
let width = -1
function run() {
frame = 0
const toggle = node.querySelector<HTMLElement>('[data-clamp-toggle]')
const items = Array.from(node.querySelectorAll<HTMLElement>('[data-chip]'))
for (const item of items) item.hidden = false
if (toggle) toggle.hidden = true
const lines = [...new Set(items.map((item) => item.offsetTop))].sort((a, b) => a - b)
if (lines.length <= options.rows || !toggle) return
toggle.hidden = false
if (options.expanded) return
const lastLine = lines[options.rows - 1]
for (const item of items) {
if (item.offsetTop > lastLine && !item.hasAttribute('data-selected')) item.hidden = true
}
const hideable = items.filter((item) => !item.hidden && !item.hasAttribute('data-selected'))
while (toggle.offsetTop > lastLine && hideable.length) hideable.pop()!.hidden = true
}
function schedule() {
if (!frame) frame = requestAnimationFrame(run)
}
// Width only: hiding items changes the height, which must not measure again.
const resize = new ResizeObserver(([entry]) => {
if (entry.contentRect.width === width) return
width = entry.contentRect.width
schedule()
})
resize.observe(node)
// The items themselves changing; the `hidden` flips above are attributes, not seen here.
const mutations = new MutationObserver(schedule)
mutations.observe(node, { childList: true, subtree: true, characterData: true })
return {
update(next) {
options = next
schedule()
},
destroy() {
cancelAnimationFrame(frame)
resize.disconnect()
mutations.disconnect()
}
}
}
@@ -21,7 +21,8 @@
setSessionDraftPrompt
} from './sessionState.svelte'
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
import { takeComposerFocus } from './homeSessionsTransition.svelte'
import { composerSentFromHome, takeComposerFocus } from './homeSessionsTransition.svelte'
import { homeComposerContext } from './homeComposerContext.svelte'
// Home's block is the empty session's own chat, run by that session's manager: the
// composer, its controls and what a send does are the session's, not a copy of them.
@@ -51,6 +52,7 @@
// The turn is already running on the session's manager; the page it belongs to takes over.
function onSent() {
composerSentFromHome()
selectSession(sessionId)
void goto(sessionPageHref(sessionId))
}
@@ -71,18 +73,25 @@
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)
})
})
</script>
{#snippet inputPreface()}
{#snippet actingOn()}
{#if session}
<SessionWorkspaceBar {session} />
{/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. -->
{#if session && $copilotWorkspace !== undefined}
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}
<AIChat
bind:this={aiChat}
hideHeader
@@ -92,9 +101,13 @@
{onDraftChange}
initialAttachments={getSessionDraftAttachments(sessionId)}
{onAttachmentsChange}
starter={{ where: 'home', prompts: starterPrompts.list, chips: starterPrompts.chipsOffered }}
starter={{
where: 'home',
suggestions: starterPrompts.suggestions,
fewItems: starterPrompts.fewItems ?? false
}}
viewTransitionNames
{onSent}
{inputPreface}
{actingOn}
/>
{/if}
@@ -28,8 +28,9 @@
}
</script>
<div class="flex flex-row items-center gap-1 py-0.5 px-1 text-2xs text-secondary">
<span class="shrink-0">Acting on</span>
<!-- 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}
@@ -25,6 +25,7 @@
X
} from 'lucide-svelte'
import SessionWorkspaceBar from './SessionWorkspaceBar.svelte'
import { arrivingFromHomeSend } from './homeSessionsTransition.svelte'
import SessionChangesBar from './SessionChangesBar.svelte'
import SessionShareButton from './SessionShareButton.svelte'
import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte'
@@ -350,9 +351,6 @@
/>
</div>
{/if}
{#if !hasFirstUserMessage}
<SessionWorkspaceBar {session} />
{/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
@@ -389,6 +387,10 @@
</div>
{/snippet}
{#snippet actingOn()}
<SessionWorkspaceBar {session} />
{/snippet}
{#snippet sessionHeader()}
<EditableInput
bind:this={summaryInput}
@@ -494,13 +496,14 @@
starter={opensSession
? {
where: 'session',
prompts: starterPrompts.list,
chips: starterPrompts.chipsOffered
suggestions: starterPrompts.suggestions,
fewItems: starterPrompts.fewItems ?? false
}
: undefined}
viewTransitionNames={headerInPage}
viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())}
emptyHint={sessionEmptyHint}
{inputPreface}
actingOn={hasFirstUserMessage ? undefined : actingOn}
/>
</div>
</Pane>
@@ -0,0 +1,49 @@
import type { ContextElement } from '$lib/components/copilot/chat/context'
/** Resolves once the element is in the draft, so several attach in the order given. */
type Attach = (element: ContextElement) => Promise<void>
/** What the composer can take as context from a workspace item: a script, a flow or a code
* app, as "+" → Mention file builds it. A visual-builder app or an agent has no context
* element, so it gets none. */
export function itemContextElement(item: {
kind: string
path: string
summary?: string
rawApp?: boolean
}): ContextElement | undefined {
const type =
item.kind === 'script'
? 'workspace_script'
: item.kind === 'flow'
? 'workspace_flow'
: (item.kind === 'app' && item.rawApp) || item.kind === 'raw_app'
? 'workspace_app'
: undefined
if (!type) return undefined
return { type, path: item.path, title: item.path, summary: item.summary, deletable: true }
}
let attach = $state<Attach | undefined>(undefined)
/**
* The way from anywhere on Home into Home's composer: a row's "Ask AI" hands its item over
* here, and the composer takes it as context. Only a mounted composer registers, so a page
* whose composer is removed, hidden or not Home offers no button that would go nowhere.
*/
export const homeComposerContext = {
get available(): boolean {
return attach !== undefined
},
async attach(element: ContextElement): Promise<void> {
await attach?.(element)
},
/** 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
return () => {
if (attach === fn) attach = undefined
}
}
}
@@ -1,11 +1,11 @@
import type { OnNavigate } from '@sveltejs/kit'
import { sessionState } from './sessionState.svelte'
// Moving between Home and AI Sessions keeps the session block in sight: the browser
// snapshots the page before and after the navigation and glides each element that
// carries the same `view-transition-name` on both sides (AIChatDisplay names the
// heading and the composer); the rest of the page cross-fades. The timing lives in
// app.css, keyed on the `data-home-sessions-transition` attribute set here for the
// length of the move.
// Moving between Home and AI Sessions keeps the composer in sight: the browser
// snapshots the page before and after the navigation and glides the element that
// carries the `composer` view-transition-name on both sides (AIChatDisplay names it);
// the rest of the page cross-fades. The timing lives in app.css, keyed on the
// `data-home-sessions-transition` attribute set here for the length of the move.
const HOME = '/'
const SESSIONS = '/sessions'
@@ -32,6 +32,22 @@ export function takeComposerFocus(): boolean {
return focused
}
// A session that has sent its first message has a composer of its own, not Home's draft, so
// a move between it and Home is not one composer moving: its page names no composer. The one
// exception is the send from Home itself, which lands on that session already under way.
let sentFromHome = $state(false)
/** Called by Home's composer as its send hands over to the session page. */
export function composerSentFromHome(): void {
sentFromHome = true
}
/** Whether the session page arriving now came from a send on Home, so its composer is the
* one Home just sent from. */
export function arrivingFromHomeSend(): boolean {
return sentFromHome
}
/** For SvelteKit's `onNavigate`: runs a move between Home and AI Sessions as a view
* transition. Any other navigation, or a browser without the API, is left alone. */
export function homeSessionsTransition(navigation: OnNavigate): Promise<void> | undefined {
@@ -48,21 +64,33 @@ export function homeSessionsTransition(navigation: OnNavigate): Promise<void> |
: from === SESSIONS && to === HOME
? 'leave'
: undefined
// Good for the navigation the send started, and only that one.
if (direction !== 'enter') sentFromHome = false
if (!direction || navigation.willUnload || !document.startViewTransition) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return
const root = document.documentElement
// Reduced motion keeps the transition but drops every name, so the two pages simply
// cross-fade as one.
root.dataset.homeSessionsTransition = window.matchMedia('(prefers-reduced-motion: reduce)')
.matches
? 'fade'
: direction
// To or from a session under way there is no composer to carry over: Home's would only
// fade out or in on its own, so the move drops every name and the page cross-fades as
// one. Leaving, the page says so; arriving, the session's record does (it has sent once
// it has a workspace), short of the send from Home that just started it.
const composerOnScreen = Array.from(document.querySelectorAll('[data-session-composer]')).some(
(el) => getComputedStyle(el).viewTransitionName === 'composer'
)
const arrivingId = navigation.to?.url.searchParams.get('session') ?? sessionState.currentSessionId
const arrivingUnderWay =
!sentFromHome && !!sessionState.sessions.find((s) => s.id === arrivingId)?.workspace_id
const plain = direction === 'leave' ? !composerOnScreen : arrivingUnderWay
root.dataset.homeSessionsTransition = plain ? 'fade' : direction
return new Promise((resolve) => {
const transition = document.startViewTransition(async () => {
resolve()
await navigation.complete
})
// Rejects when the navigation is cancelled or fails; the attribute goes either way.
const done = () => delete root.dataset.homeSessionsTransition
const done = () => {
delete root.dataset.homeSessionsTransition
sentFromHome = false
}
void transition.finished.then(done, done)
})
}
@@ -300,7 +300,7 @@
<ForkWorkspaceBanner />
<WorkspaceDraftsBanner />
<div class="max-w-7xl px-4 sm:px-8 md:px-8 h-fit w-full mb-6">
<div class="max-w-[1120px] px-4 sm:px-8 md:px-8 h-fit w-full mb-6 shrink-0">
<!-- 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