Merge remote-tracking branch 'origin/unify-ai-session-home-chatbox' into home-items-tabs

Conflicts:
- devPreview.ts, kitchen_sink/home_preview: kept deleted, as the base removed them.
- TreeOwnerRow.svelte: took the base's unruled-list version.
- ItemsList.svelte: kept setUnruledList, dropped the sort menu, the list/tree
  toggle imports and the base's separator in favour of the tab strip.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-19 07:52:59 -07:00
co-authored by Claude Opus 5.5
38 changed files with 285 additions and 556 deletions
-22
View File
@@ -427,28 +427,6 @@ 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. */
@@ -1,5 +1,5 @@
<script lang="ts">
import LabelBadge from './common/badge/LabelBadge.svelte'
import LabelList from './common/badge/LabelList.svelte'
import type { BadgeColor } from './common/badge/model'
import { Folder } from 'lucide-svelte'
@@ -9,24 +9,7 @@
color?: BadgeColor
}
let { labels, max = 3, color = 'gray' }: Props = $props()
let { labels, max, color }: Props = $props()
</script>
{#if labels?.length}
<div class="flex items-center gap-0.5">
{#each labels.slice(0, max) as label (label)}
<LabelBadge {color} icon={Folder} title="Label inherited from folder: {label}">
{label}
</LabelBadge>
{/each}
{#if labels.length > max}
<LabelBadge
{color}
title={labels
.slice(max)
.map((l) => 'Label inherited from folder: ' + l)
.join('\n')}>+{labels.length - max}</LabelBadge
>
{/if}
</div>
{/if}
<LabelList {labels} icon={Folder} titlePrefix="Label inherited from folder" {max} {color} />
@@ -0,0 +1,33 @@
<script lang="ts">
import LabelBadge from './LabelBadge.svelte'
import type { BadgeColor, BadgeIconProps } from './model'
interface Props {
labels: string[] | undefined | null
icon: BadgeIconProps['icon']
/** Names where each label comes from in its tooltip, e.g. "Label". */
titlePrefix: string
/** Shown as badges; the rest are counted, and named in the count's tooltip. */
max?: number
color?: BadgeColor
}
let { labels, icon, titlePrefix, 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)}
<LabelBadge {color} {icon} title="{titlePrefix}: {label}">{label}</LabelBadge>
{/each}
{#if labels.length > max}
<LabelBadge
{color}
title={labels
.slice(max)
.map((l) => `${titlePrefix}: ${l}`)
.join('\n')}>+{labels.length - max}</LabelBadge
>
{/if}
</div>
{/if}
@@ -4,7 +4,7 @@
import DraftBadge from '$lib/components/DraftBadge.svelte'
import type ShareModal from '$lib/components/ShareModal.svelte'
import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte'
import InheritedLabels from '$lib/components/InheritedLabels.svelte'
import RowLabels from './RowLabels.svelte'
import type { ListableResource } from '$lib/gen'
import { userStore, workspaceStore } from '$lib/stores'
import { createEventDispatcher } from 'svelte'
@@ -84,7 +84,7 @@
>
{#snippet badges()}
<SharedBadge canWrite={agent.canWrite} extraPerms={agent.extra_perms} />
<InheritedLabels labels={agent.inherited_labels} max={1} color="subtle" />
<RowLabels inherited={agent.inherited_labels} />
<DraftBadge
is_draft={agent.is_draft}
draft_only={agent.draft_only}
@@ -12,7 +12,6 @@
import Button from '../button/Button.svelte'
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'
@@ -129,8 +128,7 @@
<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" />
<RowLabels labels={app.labels} inherited={app.inherited_labels} />
<DraftBadge
is_draft={app.is_draft}
draft_only={app.draft_only}
@@ -5,13 +5,14 @@
homeComposerContext,
itemContextElement
} from '$lib/components/sessions/homeComposerContext.svelte'
import type { BulkKind } from '$lib/components/home/homeSelection.svelte'
let {
kind,
path,
summary,
rawApp
}: { kind: string; path: string; summary?: string; rawApp?: boolean } = $props()
}: { kind: BulkKind; path: string; summary?: string; rawApp?: boolean } = $props()
let element = $derived(itemContextElement({ kind, path, summary: summary || undefined, rawApp }))
</script>
@@ -36,7 +36,6 @@
} from 'lucide-svelte'
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'
@@ -161,8 +160,7 @@
<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" />
<RowLabels labels={flow.labels} inherited={flow.inherited_labels} />
<DraftBadge
is_draft={flow.is_draft}
draft_only={flow.draft_only}
@@ -80,6 +80,7 @@
{#snippet actions()}
{#if !$userStore?.operator}
<Dropdown
size="sm"
items={[
{
displayName: 'Delete',
@@ -47,6 +47,7 @@
{/snippet}
{#snippet actions()}
<Dropdown
size="sm"
items={async () => {
let { path } = app
@@ -9,6 +9,9 @@
import Tooltip from '../../meltComponents/Tooltip.svelte'
import Checkbox from '../checkbox/Checkbox.svelte'
import type { RowSelection } from './rowSelection'
import { HOVER_ACTIONS_CLASS, inUnruledList } from './unruledList'
const unruled = inUnruledList()
interface Props {
marked: string | undefined
@@ -177,12 +180,14 @@
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(
'group/row w-full inline-flex items-center gap-4 first-of-type:!border-t-0 first-of-type:rounded-t-md last-of-type:rounded-b-md [*:not(:last-child)]:border-b px-4 py-3 border-b last:border-b-0',
depth > 0 ? '!rounded-none' : '',
'group/row w-full inline-flex items-center gap-4 px-4 py-3',
unruled
? 'rounded-md'
: 'first-of-type:!border-t-0 first-of-type:rounded-t-md last-of-type:rounded-b-md [*:not(:last-child)]:border-b border-b last:border-b-0',
depth > 0 && !unruled ? '!rounded-none' : '',
disabled ? 'opacity-25' : 'hover:bg-surface-hover',
clickToSelect || inSelectionMode ? 'cursor-pointer select-none' : '',
selected || rowSelection?.selected
@@ -261,7 +266,10 @@
</div>
{/if}
<div data-row-actions class="flex shrink-0 items-center justify-end">
<div
data-row-actions
class="flex shrink-0 items-center justify-end {unruled ? HOVER_ACTIONS_CLASS : ''}"
>
{@render actions?.()}
</div>
</div>
@@ -290,14 +298,15 @@
{/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. -->
row's hover or keyboard focus only, so a list of titles doesn't read as a column of
outlines. Opacity, not visibility: a hidden button drops out of the Tab order. -->
<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"
class="inline-flex shrink-0 p-px text-yellow-500 opacity-0 data-[starred]:opacity-100 group-hover/row:opacity-100 group-has-[:focus-visible]/row:opacity-100"
/>
{/if}
</div>
@@ -1,25 +1,17 @@
<script lang="ts">
import { Tag } from 'lucide-svelte'
import LabelBadge from '../badge/LabelBadge.svelte'
import { Folder, Tag } from 'lucide-svelte'
import LabelList from '../badge/LabelList.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
let { labels, inherited }: { labels?: string[] | null; inherited: string[] | undefined } =
$props()
</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}
<!-- A row has little room beside its title: one of each kind shows, the rest are counted. -->
<LabelList {labels} icon={Tag} titlePrefix="Label" max={1} color="subtle" />
<LabelList
labels={inherited}
icon={Folder}
titlePrefix="Label inherited from folder"
max={1}
color="subtle"
/>
@@ -50,7 +50,6 @@
import WacExportDrawer from '$lib/components/scripts/WacExportDrawer.svelte'
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'
@@ -209,8 +208,7 @@
>
{/if}
<SharedBadge canWrite={script.canWrite} extraPerms={script.extra_perms} />
<RowLabels labels={script.labels} />
<InheritedLabels labels={script.inherited_labels} max={1} color="subtle" />
<RowLabels labels={script.labels} inherited={script.inherited_labels} />
<!-- Last, so the draft badges line up down the list whatever labels each row has. -->
<DraftBadge
is_draft={script.is_draft}
@@ -0,0 +1,26 @@
import { getContext, setContext } from 'svelte'
const KEY = Symbol('unruledList')
/** Marks the rows below as one unruled list (Home's items): no line between rows, a rounded
* hover, and row actions shown only on the row in use. Every other list keeps its ruled rows. */
export function setUnruledList() {
setContext(KEY, true)
}
export function inUnruledList(): boolean {
return getContext<boolean | undefined>(KEY) ?? false
}
/** The divider an ordinary list row draws, or none in an unruled list. */
export function rowRule(unruled: boolean): string {
return unruled ? 'rounded-md' : 'border-b'
}
/** Row actions in an unruled list: shown for the row hovered, tabbed into, keyboard-selected,
* or with one of its menus open. Opacity rather than visibility, so Tab still reaches them;
* focus counts only when visible, since 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. Needs `group/row`
* on the row. */
export const HOVER_ACTIONS_CLASS =
'opacity-0 transition-opacity duration-100 group-hover/row:opacity-100 group-has-[:focus-visible]/row:opacity-100 group-data-[row-keyboard-selected=true]/row:opacity-100 has-[[aria-expanded=true]]:opacity-100'
@@ -72,7 +72,7 @@
import ComposerSuggestions from './starter/ComposerSuggestions.svelte'
import type { DraftAttachments } from './messageDraft.svelte'
import type { ChatStarter } from './starter/starterPrompts.svelte'
import { composerCollapses, isComposerOverlay } from './starter/composerCollapse'
import { isComposerOverlay } from './starter/composerCollapse'
import { smoothHeight } from './starter/smoothHeight'
const MAX_YOLO_TOOLTIP_TOOLS = 8
@@ -315,8 +315,7 @@
/** 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)
await mentionWorkspaceItem(element)
aiChatInput?.focusInput()
}
@@ -557,7 +556,7 @@
function mentionWorkspaceItem(element: ContextElement) {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
return aiChatInput?.insertMention(element.title)
}
function onFolderInputChange(e: Event) {
@@ -598,20 +597,22 @@
// menu it is opening.
let composerEl: HTMLDivElement | undefined = $state()
let composerOpened = $state(false)
const homeComposer = $derived(starterLayout && starter?.where === 'home')
// Anything the user has started (text, an attachment) or is in the middle of (they opened it
// and have not left) keeps it open, and so does a workspace small enough that the composer is
// the page's main way in.
const composerCollapsed = $derived(
composerCollapses({
onHome: starterLayout && starter?.where === 'home',
usable: !disabled,
fewItems: starter?.fewItems ?? false,
opened: composerOpened,
draftEmpty: aiChatInput?.isDraftEmpty() ?? true
})
homeComposer &&
!disabled &&
!(starter?.where === 'home' && starter.fewItems) &&
!composerOpened &&
(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 (!homeComposer || !composerOpened || composerEl?.contains(e.target as Node)) return
if (!isComposerOverlay(e.target)) closeComposer()
}
@@ -980,12 +981,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
class="relative {columnClass} pb-2"
style:view-transition-name={viewTransitionNames ? 'composer' : undefined}
onfocusin={(e) => {
if (e.target instanceof HTMLTextAreaElement) composerOpened = true
if (homeComposer && 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
if (!homeComposer || !composerOpened) return
closeComposer()
if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur()
}}
@@ -1053,7 +1054,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
isFirstMessage={messages.length === 0}
hero={starterLayout}
collapsed={composerCollapsed}
chatIcon={starterLayout && starter?.where === 'home'}
chatIcon={homeComposer}
{onSent}
>
{#snippet collapsedControls()}
@@ -1096,14 +1097,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
void mentionWorkspaceItem(element)
close()
aiChatInput?.focusInput()
}}
onSelectWorkspaceItem={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
void mentionWorkspaceItem(element)
close()
aiChatInput?.focusInput()
}}
@@ -1304,8 +1303,13 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
{#if footerMessageShown}
<div class="text-primary text-xs my-2 px-2">
<Markdown md={disabledMessage} />
<!-- The workspace picker stays: picking another workspace is how a chat that
cannot run here becomes usable again. -->
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
{@render actingOn?.()}
<div class="text-primary text-xs my-2 px-2">
<Markdown md={disabledMessage} />
</div>
</div>
{:else}
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center">
@@ -1618,21 +1618,15 @@
}}
rows={1}
placeholder={modePlaceholder}
class={twMerge(
'resize-none',
COMPOSER_FIELD_RESET,
CHAT_INPUT_PADDING,
toolbarInBox && FIELD_PADDING_WITH_TOOLBAR
)}
class={twMerge('resize-none', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING)}
{disabled}
></textarea>
{#if !bottomRightSnippet && !toolbarInBox}
{#if !bottomRightSnippet}
<div class="absolute bottom-1 right-1">
{@render sendStopButton()}
</div>
{/if}
</div>
{@render toolbarRow()}
</div>
{/if}
{#if toolbar && !toolbarInBox}
@@ -2256,7 +2256,7 @@ export class AIChatManager implements ChatViewHost {
)
}
setAiChatInput(aiChatInput: AIChatInput | null) {
setAiChatInput(aiChatInput: AIChatInput) {
this.aiChatInput = aiChatInput
}
@@ -805,8 +805,8 @@
<!-- 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 }}
class={twMerge(composerBoxClass(disabled), hero && HERO_BOX_CLASS)}
use:smoothHeight={{ enabled: hero, key: oneLine }}
>
<div class={oneLine ? 'flex flex-row items-center' : ''}>
<!-- Context chips live inside the input box, above the textarea. The snippet
@@ -72,7 +72,7 @@ export interface ChatViewHost {
/** Resolves to whether the draft was consumed as a turn. */
sendRequest: (options?: ChatSendRequestOptions) => Promise<boolean | undefined>
cancel: (reason?: string) => void
setAiChatInput: (aiChatInput: AIChatInput | null) => void
setAiChatInput: (aiChatInput: AIChatInput) => void
/** Unregisters `aiChatInput` if it is still the registered one. A host's chat can remount
* elsewhere (Home hands its session to /sessions), and the new composer may register before
* the old one's teardown runs. */
@@ -1,18 +0,0 @@
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)
})
})
@@ -1,16 +1,3 @@
/** 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.
@@ -35,11 +35,14 @@ export function smoothHeight(node: HTMLElement, params: SmoothHeightParams) {
node.style.height = `${inner.offsetHeight + borders}px`
}
const ro = new ResizeObserver(apply)
// Created on first use: most chats mount this disabled and never turn it on.
let ro: ResizeObserver | undefined
const observe = () => {
ro.disconnect()
ro?.disconnect()
const inner = node.firstElementChild
if (inner) ro.observe(inner)
if (!enabled || !inner) return
ro ??= new ResizeObserver(apply)
ro.observe(inner)
}
observe()
apply()
@@ -52,7 +55,7 @@ export function smoothHeight(node: HTMLElement, params: SmoothHeightParams) {
apply()
},
destroy() {
ro.disconnect()
ro?.disconnect()
}
}
}
@@ -145,10 +145,8 @@ async function fetchItemCount(workspace: string): Promise<number> {
}
/** 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 under a greeting;
* Home shows it alone, collapsed to one line at rest unless `fewItems`. */
where: 'home' | 'session'
suggestions: ComposerSuggestion[]
fewItems: boolean
}
export type ChatStarter = { suggestions: ComposerSuggestion[] } & (
| /** An empty session centres the block in the pane under a greeting. */
{ where: 'session' } /** Home shows it alone, collapsed to one line at rest unless `fewItems`. */
| { where: 'home'; fewItems: boolean }
)
@@ -2,7 +2,6 @@ import { WorkspaceService } from '$lib/gen'
import { copilotWorkspace, setCopilotInfo } from '$lib/aiStore'
import { workspaceAIClients } from './lib'
import { writable } from 'svelte/store'
import { previewAiConfig } from '$lib/devPreview'
// The workspace of the most recent loadCopilot *request*, set synchronously before the
// await — as opposed to `copilotWorkspace`, which only updates once a load resolves. A
@@ -45,7 +44,7 @@ export function loadCopilot(workspace: string): Promise<void> {
async function fetchAndApply(workspace: string, token: number) {
workspaceAIClients.init(workspace)
try {
const info = previewAiConfig(await WorkspaceService.getCopilotInfo({ workspace }))
const info = await WorkspaceService.getCopilotInfo({ workspace })
if (token !== loadCopilotToken) return
setCopilotInfo(info)
copilotWorkspace.set(workspace)
@@ -0,0 +1,44 @@
import { resource } from 'runed'
import { fromStore } from 'svelte/store'
import { WorkspaceService } from '$lib/gen'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
/**
* Whether a workspace hid the AI assistant (`ai_config.copilot_disabled`), read for that workspace
* directly: `copilotInfo` holds whichever workspace loaded last, so it answers only when it was
* loaded for this very workspace. `hidden` is `undefined` until a verdict for the workspace asked
* about lands; runed keeps the previous `current` while a new source loads, so each verdict is
* tagged with its workspace. A failed read counts as not hidden, as an unloaded config does
* everywhere else.
*/
export function useWorkspaceAiHidden(workspace: () => string | undefined) {
const loadedInfo = fromStore(copilotInfo)
const loadedWorkspace = fromStore(copilotWorkspace)
const verdict = resource(workspace, async (ws, _prev, { signal }) => {
if (!ws) return { workspace: ws, hidden: false }
let hidden = false
try {
hidden = (await WorkspaceService.getCopilotInfo({ workspace: ws })).copilot_disabled === true
} catch (e) {
console.error(`Failed to read the AI config of workspace ${ws}:`, e)
}
// The generated client can't take an abort signal, so drop a superseded response here.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
return { workspace: ws, hidden }
})
const hidden = $derived.by(() => {
const ws = workspace()
const current = verdict.current
if (current && current.workspace === ws) return current.hidden
return ws && loadedWorkspace.current === ws ? loadedInfo.current.workspaceDisabled : undefined
})
return {
get hidden(): boolean | undefined {
return hidden
},
/** Whether any verdict has landed yet, for any workspace. */
get settledOnce(): boolean {
return verdict.current !== undefined
}
}
}
@@ -570,7 +570,7 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac
}
// Typed off the interface: a Svelte component's own type resolves differently
// across import specifiers, and the two would then not be assignable.
#aiChatInput: Parameters<ChatViewHost['setAiChatInput']>[0] = null
#aiChatInput: Parameters<ChatViewHost['setAiChatInput']>[0] | null = null
setAiChatInput: ChatViewHost['setAiChatInput'] = (aiChatInput) =>
// Called from the composer's mount effect, and taking what a turn handed back reads the
// draft it writes: tracked, that would rerun the effect and hand it back again.
@@ -15,8 +15,6 @@
import Button from '../common/button/Button.svelte'
import CloseButton from '../common/CloseButton.svelte'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { WorkspaceService } from '$lib/gen'
import { resource } from 'runed'
import { hubBaseUrlStore, userStore, workspaceStore } from '$lib/stores'
import { sessionState } from '../sessions/sessionState.svelte'
import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte'
@@ -31,7 +29,7 @@
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
import { prefetchItemCount } from '../copilot/chat/starter/starterPrompts.svelte'
import { previewAiConfig } from '$lib/devPreview'
import { useWorkspaceAiHidden } from '../copilot/workspaceAiHidden.svelte'
const COLLAPSED_SETTING = 'home-ai-composer-collapsed'
@@ -45,8 +43,8 @@
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
// Whether this reader wants the composer on the home page at all, so it lives per browser
// rather than per workspace or account. The setting's name predates the composer's own
// one-line state, which is unrelated.
// rather than per workspace or account. It has nothing to do with the composer's one-line
// state despite the key's name; renaming the key would reset every reader's choice.
let removed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true')
function setRemoved(next: boolean) {
removed = next
@@ -67,6 +65,7 @@
let pulseEndTimer: ReturnType<typeof setTimeout> | undefined
function removeComposer() {
// The `close` key keeps these events in the series they have always been counted in.
logFeatureUsage('home', 'ai_hero_remove', { key: 'close' })
setRemoved(true)
if (reducedMotion.val) return
@@ -98,33 +97,16 @@
// 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
// that is the draft's, so a draft acting on a workspace that hides AI would otherwise take
// the whole block, and the picker that could undo it, off Home.
const homeAiHidden = resource(
() => $workspaceStore ?? undefined,
async (workspace, _, { signal }) => {
if (!workspace) return false
let hidden = false
try {
hidden =
previewAiConfig(await WorkspaceService.getCopilotInfo({ workspace })).copilot_disabled ===
true
} catch (e) {
console.error(`Failed to read the AI config of workspace ${workspace}:`, e)
}
// runed keeps a superseded fetch's result, and the generated client takes no signal.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
return hidden
}
)
// Whether Home's own workspace hides the assistant, read for that workspace: once the block
// shows, the shared copilot config is the draft's, so a draft acting on a workspace that hides
// AI would otherwise take the whole block, and the picker that could undo it, off Home.
const homeAiHidden = useWorkspaceAiHidden(() => $workspaceStore ?? undefined)
// The composer hands off to /sessions, which refuses operators and users opted out of the
// sessions beta — so hide it from them (the prompt would be silently dropped) while the
// AI-independent CLI/MCP row below stays.
let showComposer = $derived(
prefersSessionHandoff($userStore?.operator) && !runOnlyWorkspace && !homeAiHidden.current
prefersSessionHandoff($userStore?.operator) && !runOnlyWorkspace && !homeAiHidden.hidden
)
let hero = $derived(showComposer && !removed)
@@ -135,11 +117,12 @@
{#if hero}
<!-- 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. -->
row stays once the box opens downward. Shown on hover; the container starts at the
composer's edge so the pointer reaches the unpin button without leaving the hovered
zone. Below `sm` there is no side padding to hold it, so unpinning is in the band's
menu instead. -->
<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"
class="hidden sm:block absolute top-4 left-full pl-1 z-20 transition-opacity opacity-0 group-hover/composer:opacity-100 focus-within:opacity-100"
>
<CloseButton small noBg Icon={PinOff} title="Unpin from Home" onClick={removeComposer} />
</div>
@@ -200,7 +183,7 @@
<!-- Nothing left to hold once the side trips stand in the bar and the composer is on the
page: an ellipsis that opens an empty menu is a button that does nothing. -->
<!-- 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
unpin button removes it, so an ellipsis holding a second way to do that is a button whose only
item is a duplicate. -->
{#if !sideTripsInBar || (showComposer && removed)}
<!-- The flash rides the ellipsis itself, not the row: with the side trips beside it the
@@ -219,6 +202,11 @@
placement="bottom-end"
size="sm"
items={[
// The menu shows here only while the bar is narrow, which includes every phone,
// where the composer has no room for its own unpin button.
...(hero
? [{ displayName: 'Unpin from Home', icon: PinOff, action: removeComposer }]
: []),
...(showComposer && removed
? [
{
@@ -35,7 +35,7 @@
import type { IconType } from '$lib/utils'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts'
import { HOME_COLUMN_WIDTH, HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts'
import SearchItems from '../SearchItems.svelte'
import FilterSearchbar, {
@@ -49,8 +49,9 @@
import ListFilters from './ListFilters.svelte'
import LabelBadge from '../common/badge/LabelBadge.svelte'
import { clampRows } from './clampRows'
import { setUnruledList } from '../common/table/unruledList'
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
import { getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils'
import { getLocalSetting, isOwner, pluralize, storeLocalSetting } from '$lib/utils'
import { sendUserToast } from '$lib/toast'
import Drawer from '../common/drawer/Drawer.svelte'
import HighlightCode from '../HighlightCode.svelte'
@@ -75,6 +76,8 @@
let { subtab = $bindable('script'), showEditButtons = true }: Props = $props()
setUnruledList()
// Which user-folder scoping toggle (if any) this role gets. Declared before the
// FilterSearchbar schema and the derived filters that both read it.
let filterUserFoldersType: 'only f/*' | 'u/username and f/*' | undefined = $derived(
@@ -1865,11 +1868,13 @@
</DrawerContent>
</Drawer>
<!-- 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. -->
<CenteredPage
wrapperClasses="w-full pb-6"
class="{HOME_COLUMN_WIDTH} sm:px-8"
handleOverflow={false}
>
<!-- The items section: its controls, its filters and its rows. No `overflow-hidden` on it:
the page scrolls, and that would stop the controls sticking. -->
<div class="flex flex-col">
<div
bind:clientHeight={toolbarHeight}
@@ -1888,10 +1893,11 @@
</div>
<!-- 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">
under the view controls as a whole, and on a phone the search takes a row of its
own above the kind filter and New. -->
<div class="flex flex-wrap 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="relative text-primary w-full basis-full sm:basis-auto sm:min-w-[200px] sm:max-w-[22rem]"
class:opacity-40={placeholderTakesOver}
inert={toolbarInert}
>
@@ -1983,7 +1989,7 @@
{/if}
{#if !contentActive && !workspaceEmpty}
<!-- Under the chips, but sticking with the controls once the chips have scrolled away.
Pulled out like the rows, so a tab's label lines up with the controls above. -->
Not pulled out like the rows: its underline spans the controls' width. -->
<div class="sticky z-10 bg-surface" style:top="{toolbarHeight}px">
<Tabs bind:selected={() => tab, (v) => setTab(v as HomeTab)}>
{#each homeTabs as t (t.value)}
@@ -2016,7 +2022,7 @@
<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. -->
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
@@ -2024,8 +2030,8 @@
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. -->
<!-- px-1 plus ContentSearchInner's own px-2 lines its rows up with the card's
controls above. -->
<!-- px-1 plus ContentSearchInner's own px-2 lines its rows up with the controls
above. -->
<div class="px-1 pb-2">
{#key $workspaceStore}
<ContentSearchInner bind:this={contentSearchEl} search={filterValues.val.content} />
@@ -2125,8 +2131,7 @@
/>
{/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}>
<div class:wm-imported={justImported}>
{#if filter === ''}
{#each [...visiblePipelineFolders].sort() as folder (folder)}
<PipelineRow {folder} onDeleted={reloadItemsAndCounts} />
@@ -2148,7 +2153,7 @@
</div>
{#if items && hasMore}
<span class="block px-4 py-2 border-t text-center text-xs font-normal text-secondary"
>{Math.min(nbDisplayed, items.length)} items{hasMoreServer && !searching
>{pluralize(Math.min(nbDisplayed, items.length), 'item')}{hasMoreServer && !searching
? ''
: ` out of ${items.length}`}
<button
@@ -1,12 +1,14 @@
<script lang="ts">
import { ChevronDown, ChevronUp } from 'lucide-svelte'
import type { Snippet } from 'svelte'
import { Button } from '$lib/components/common'
import { inUnruledList, rowRule } from '../common/table/unruledList'
const unruled = inUnruledList()
/** A row of the tree that groups others under it (a folder, a user, "Other users"): clicking
* anywhere on it opens or closes what it groups. */
interface Props {
icon: any
icon: typeof import('lucide-svelte').Folder
name: string
opened: boolean
onToggle: () => void
@@ -25,8 +27,9 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
onclick={onToggle}
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"
class="px-4 py-2 {rowRule(
unruled
)} w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover"
>
<div
class="flex flex-row items-center gap-4"
@@ -40,14 +43,16 @@
</div>
</div>
</div>
<!-- Button stops its click from reaching the row, so it toggles once on its own. -->
<Button
iconOnly
variant="subtle"
unifiedSize="xs"
title={toggleLabel ?? name}
<!-- Keyboard access only: its click bubbles to the row, which does the toggling. -->
<button
class="w-full flex flex-row-reverse"
aria-expanded={opened}
onClick={onToggle}
startIcon={{ icon: opened ? ChevronUp : ChevronDown }}
/>
aria-label={toggleLabel ?? name}
>
{#if opened}
<ChevronUp size={16} />
{:else}
<ChevronDown size={16} />
{/if}
</button>
</div>
@@ -10,6 +10,7 @@
import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils'
import { pluralize } from '$lib/utils'
import { Button } from '$lib/components/common'
import { inUnruledList, rowRule } from '../common/table/unruledList'
interface Props {
item: ItemType | FolderItem | UserItem
@@ -72,6 +73,8 @@
leaf
}: Props = $props()
const unruled = inUnruledList()
let visualDepth = $derived(depth + indent)
const dispatch = createEventDispatcher<{ reload: void }>()
@@ -324,8 +327,9 @@
{/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"
class="px-4 py-2 {rowRule(
unruled
)} flex flex-row items-center justify-between gap-4 bg-surface-secondary"
style="padding-left: {(visualDepth + 1) * 16}px;"
>
<!-- Rows, not items: this slices the node's own entries, where a subfolder
@@ -362,8 +366,9 @@
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"
class="px-4 py-2 {rowRule(
unruled
)} flex flex-row items-center justify-between gap-4 bg-surface-secondary"
style="padding-left: {(visualDepth + 1) * 16}px;"
>
<span class="text-xs text-secondary">
@@ -5,6 +5,7 @@
import { Button } from '$lib/components/common'
import { Users } from 'lucide-svelte'
import TreeOwnerRow from './TreeOwnerRow.svelte'
import { inUnruledList, rowRule } from '../common/table/unruledList'
import { getLocalSetting, pluralize, storeLocalSetting } from '$lib/utils'
interface Props {
@@ -41,7 +42,7 @@
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. */
/** Off where the tree is part of its host's list rather than a box of its own (Home). */
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
@@ -74,6 +75,8 @@
leaf
}: Props = $props()
const unruled = inUnruledList()
// How many root nodes render at once. A root node is a collapsed owner row that
// fetches nothing until expanded, so a large slice costs a row each and no request
// — and an owner sliced off the end is indistinguishable from one that doesn't
@@ -284,12 +287,7 @@
<!-- 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. -->
<!-- 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="{framed ? 'border rounded-md bg-surface-tertiary' : ''} 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'}
@@ -316,8 +314,9 @@
{/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"
class="pl-8 pr-4 py-2 {rowRule(
unruled
)} flex flex-row items-center justify-between gap-4 bg-surface-secondary"
>
<span class="text-xs text-secondary">
Showing {nbOtherUsersDisplayed} of {otherUsers.length} users
@@ -104,7 +104,7 @@
starter={{
where: 'home',
suggestions: starterPrompts.suggestions,
fewItems: starterPrompts.fewItems ?? false
fewItems: starterPrompts.fewItems
}}
viewTransitionNames
{onSent}
@@ -494,11 +494,7 @@
? 'This session is archived. Unarchive it from the banner above to keep working.'
: ''}
starter={opensSession
? {
where: 'session',
suggestions: starterPrompts.suggestions,
fewItems: starterPrompts.fewItems ?? false
}
? { where: 'session', suggestions: starterPrompts.suggestions }
: undefined}
viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())}
emptyHint={sessionEmptyHint}
@@ -1,4 +1,5 @@
import type { ContextElement } from '$lib/components/copilot/chat/context'
import type { BulkKind } from '$lib/components/home/homeSelection.svelte'
/** Resolves once the element is in the draft, so several attach in the order given. */
type Attach = (element: ContextElement) => Promise<void>
@@ -7,7 +8,7 @@ type Attach = (element: ContextElement) => Promise<void>
* 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
kind: BulkKind
path: string
summary?: string
rawApp?: boolean
@@ -17,7 +18,7 @@ export function itemContextElement(item: {
? 'workspace_script'
: item.kind === 'flow'
? 'workspace_flow'
: (item.kind === 'app' && item.rawApp) || item.kind === 'raw_app'
: item.kind === 'app' && item.rawApp
? 'workspace_app'
: undefined
if (!type) return undefined
+3
View File
@@ -10,6 +10,9 @@ export const DEFAULT_WEBHOOK_TYPE: 'async' | 'sync' = 'async'
export const HOME_SHOW_HUB = true
/** The width of Home's one column: the composer and the items list below it. */
export const HOME_COLUMN_WIDTH = 'max-w-[1120px]'
export const HOME_SHOW_CREATE_FLOW = true
export const HOME_SEARCH_SHOW_FLOW = true
-57
View File
@@ -1,57 +0,0 @@
import type { AIConfig } from './gen'
/**
* Dev only: how this browser pretends the workspace's AI is set up, so the states a fresh
* cloud workspace goes through can be seen without reconfiguring one. Set from the
* `/kitchen_sink/home_preview` page; read nowhere in a production build.
*/
export type DevAiState = 'real' | 'free-tier' | 'free-tier-exhausted' | 'no-key' | 'hidden'
export type DevPreview = { ai: DevAiState; freeTierUsedPct: number }
const KEY = 'devPreview'
export function readDevPreview(): DevPreview | undefined {
if (!import.meta.env.DEV) return undefined
try {
const raw = globalThis.window?.localStorage?.getItem(KEY)
return raw ? (JSON.parse(raw) as DevPreview) : undefined
} catch {
return undefined
}
}
export function writeDevPreview(preview: DevPreview | undefined): void {
try {
if (preview && preview.ai !== 'real') localStorage.setItem(KEY, JSON.stringify(preview))
else localStorage.removeItem(KEY)
} catch {}
}
/**
* The workspace's AI config as the preview pretends it is; unchanged outside dev. The
* simulated states are whole configs rather than edits of the real one, so they look the
* same whatever the workspace has set up. The free tier mirrors what the server serves
* (`free_tier_copilot_config`): its one provider and model, or nothing once exhausted.
*/
export function previewAiConfig(config: AIConfig): AIConfig {
const preview = readDevPreview()
switch (preview?.ai) {
case 'free-tier':
return {
providers: {
deepseek: { resource_path: '', models: ['deepseek-v4-flash'], web_search_enabled: false }
},
default_model: { provider: 'deepseek', model: 'deepseek-v4-flash' },
free_tier: { exhausted: false, used_ratio: preview.freeTierUsedPct / 100 }
}
case 'free-tier-exhausted':
return { free_tier: { exhausted: true, used_ratio: 1 } }
case 'no-key':
return {}
case 'hidden':
return { ...config, copilot_disabled: true }
default:
return config
}
}
@@ -1,6 +1,7 @@
<script lang="ts">
import { AppService, FlowService, type OpenFlow, type Script } from '$lib/gen'
import { userStore, workspaceStore } from '$lib/stores'
import { HOME_COLUMN_WIDTH } from '$lib/consts'
import { Alert, Button, Drawer, DrawerContent } from '$lib/components/common'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
@@ -300,7 +301,7 @@
<ForkWorkspaceBanner />
<WorkspaceDraftsBanner />
<div class="max-w-[1120px] px-4 sm:px-8 md:px-8 h-fit w-full mb-6 shrink-0">
<div class="{HOME_COLUMN_WIDTH} 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
@@ -25,8 +25,7 @@
type Scope
} from '$lib/components/sessions/PreviewRouterPicker.svelte'
import { goto } from '$lib/navigation'
import { resource } from 'runed'
import { WorkspaceService } from '$lib/gen'
import { useWorkspaceAiHidden } from '$lib/components/copilot/workspaceAiHidden.svelte'
import SessionWrapper from '$lib/components/sessions/SessionWrapper.svelte'
import PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte'
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
@@ -45,7 +44,6 @@
import { enterSessionMode } from '$lib/components/sessions/sessionSwitch.svelte'
import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte'
import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
import {
getOrCreateRuntime,
getRuntime,
@@ -325,45 +323,15 @@
(activeSession ? getEffectiveWorkspaceId(activeSession) : undefined) ?? $workspaceStore
)
// Whether that workspace hid the AI assistant (`ai_config.copilot_disabled`). Read
// directly rather than from `copilotInfo`: that store holds whichever workspace loaded
// last, and the gate below unmounts the session wrapper that would refresh it, so a
// hidden verdict would stick across session and workspace switches. Tagged with its
// workspace and guarded against a superseded response like the protection-rules
// resource: runed keeps the previous `current` while a new source loads, so a switch
// would otherwise be judged on the previous workspace's verdict. A failed read leaves
// the page usable, as an unloaded config does everywhere else.
const workspaceAiHidden = resource(
() => previewWorkspace,
async (workspace, _prev, { signal }) => {
if (!workspace) return { workspace, hidden: false }
let hidden = false
try {
hidden = (await WorkspaceService.getCopilotInfo({ workspace })).copilot_disabled === true
} catch (e) {
console.error(`Failed to read the AI config of workspace ${workspace}:`, e)
}
// The generated client can't take an abort signal, so drop a superseded response here.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
return { workspace, hidden }
}
)
// Only a verdict for the workspace currently judged counts; `undefined` means it has not
// landed yet.
const aiHiddenVerdict = $derived.by(() => {
const current = workspaceAiHidden.current
if (current && current.workspace === previewWorkspace) return current.hidden
// The AI config already loaded for this very workspace (by Home, on the way here) carries
// the same flag. Tagged with its workspace, so it is never another workspace's verdict.
return previewWorkspace && $copilotWorkspace === previewWorkspace
? $copilotInfo.workspaceDisabled
: undefined
})
// Whether that workspace hid the AI assistant. The gate below unmounts the session wrapper
// that would refresh `copilotInfo`, so the verdict is read for the workspace itself.
const workspaceAiHidden = useWorkspaceAiHidden(() => previewWorkspace)
const aiHiddenVerdict = $derived(workspaceAiHidden.hidden)
// The full loader is for the page's first verdict only. Later, picking another workspace in
// "Acting on" leaves the session on screen, inert until its verdict lands (the resource
// keeps the previous one meanwhile): covering it for a request reads as the page reloading.
// "Acting on" leaves the session on screen, inert until its verdict lands: covering it for
// a request reads as the page reloading.
const firstVerdictPending = $derived(
aiHiddenVerdict === undefined && workspaceAiHidden.current === undefined
aiHiddenVerdict === undefined && !workspaceAiHidden.settledOnce
)
// Lazy-mount gate: a tab's content only renders once its key lands here (on
@@ -1290,8 +1258,9 @@
{:else if aiHiddenVerdict}
<!-- The workspace hid the assistant, and the sidebar switch with it, so only a
direct URL or a session acting on such a workspace lands here. -->
<!-- Centred like the loader above: the page header overlays this pane's top edge. -->
<div
class="absolute inset-0 z-20 bg-surface p-8 flex flex-col items-start gap-3 text-secondary text-sm"
class="absolute inset-0 z-20 bg-surface p-8 flex flex-col items-center justify-center gap-3 text-secondary text-sm text-center"
>
<p class="text-primary font-medium">AI Sessions are hidden in this workspace</p>
<p>A workspace admin hid AI sessions in the workspace settings.</p>
@@ -1,215 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte'
import { RotateCw, SquareArrowOutUpRight } from 'lucide-svelte'
import { WorkspaceService } from '$lib/gen'
import { Button } from '$lib/components/common'
import Select from '$lib/components/select/Select.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte'
import { readDevPreview, writeDevPreview, type DevAiState } from '$lib/devPreview'
// Home as a given account would see it, in a frame beside the controls: the real page,
// told by this browser's dev overrides (`$lib/devPreview`, `cloudHostedOverride`) what to
// pretend. Every change reloads the frame, since those overrides are read at load.
const CLOUD_KEY = 'cloudHostedOverride'
const UNPINNED_KEY = 'home-ai-composer-collapsed'
const AI_STATES: { value: DevAiState; label: string }[] = [
{ value: 'real', label: "The workspace's real setup" },
{ value: 'free-tier', label: 'Free Windmill AI, partly used' },
{ value: 'free-tier-exhausted', label: 'Free Windmill AI, used up' },
{ value: 'no-key', label: 'No AI key configured' },
{ value: 'hidden', label: 'AI hidden in the workspace' }
]
const WIDTHS = [
{ value: 'full', label: 'Full' },
{ value: '1024', label: '1024' },
{ value: '768', label: '768' },
{ value: '400', label: '400' }
]
function readStorage(key: string): string | null {
try {
return localStorage.getItem(key)
} catch {
return null
}
}
function writeStorage(key: string, value: string | undefined) {
try {
if (value === undefined) localStorage.removeItem(key)
else localStorage.setItem(key, value)
} catch {}
}
const initial = readDevPreview()
let ai = $state<DevAiState>(initial?.ai ?? 'real')
const USED_PCTS = [0, 30, 60, 90, 99]
let usedPct = $state(initial?.freeTierUsedPct ?? 60)
let cloud = $state(readStorage(CLOUD_KEY) === '1')
let workspace = $state<string | undefined>(readStorage('workspace') ?? undefined)
let width = $state('full')
let workspaces = $state<{ label: string; value: string }[]>([])
let reloadKey = $state(0)
let src = $derived(workspace ? `/?workspace=${encodeURIComponent(workspace)}` : '/')
function apply() {
writeDevPreview({ ai, freeTierUsedPct: usedPct })
writeStorage(CLOUD_KEY, cloud ? '1' : undefined)
reloadKey++
}
function showComposerAgain() {
writeStorage(UNPINNED_KEY, undefined)
reloadKey++
}
onMount(async () => {
const list = await WorkspaceService.listUserWorkspaces()
workspaces = list.workspaces.map((w) => ({ label: `${w.name} (${w.id})`, value: w.id }))
})
</script>
<svelte:head><title>Home preview</title></svelte:head>
<div class="flex h-screen bg-surface-secondary text-primary">
<aside class="w-72 shrink-0 border-r bg-surface flex flex-col gap-5 p-4 overflow-y-auto">
<div class="flex items-center justify-between">
<h1 class="text-sm font-semibold text-emphasis">Home preview</h1>
<DarkModeToggle />
</div>
{#if !import.meta.env.DEV}
<p class="text-xs text-secondary">
The overrides only work in a dev build (<code>npm run dev</code>).
</p>
{/if}
<section class="flex flex-col gap-1.5">
<span class="text-xs font-semibold text-emphasis">Workspace</span>
<Select
items={workspaces}
bind:value={
() => workspace,
(v) => {
workspace = v
reloadKey++
}
}
placeholder="Pick a workspace"
size="sm"
/>
<span class="text-2xs text-hint">
An empty one (e.g. <code>empty</code>) shows the first-visit state.
</span>
</section>
<section class="flex flex-col gap-1.5">
<span class="text-xs font-semibold text-emphasis">AI setup</span>
<Select
items={AI_STATES}
bind:value={
() => ai,
(v) => {
ai = v ?? 'real'
apply()
}
}
size="sm"
/>
{#if ai === 'free-tier'}
<div class="flex flex-col gap-1 text-2xs text-secondary">
<span>Used</span>
<ToggleButtonGroup
selected={String(usedPct)}
onSelected={(v) => {
usedPct = Number(v)
apply()
}}
>
{#snippet children({ item })}
{#each USED_PCTS as p (p)}
<ToggleButton value={String(p)} label="{p}%" {item} size="sm" />
{/each}
{/snippet}
</ToggleButtonGroup>
</div>
<span class="text-2xs text-hint">
Home hides the usage line; it shows in a session once it has a message.
</span>
{/if}
</section>
<section class="flex flex-col gap-1.5">
<span class="text-xs font-semibold text-emphasis">Hosting</span>
<Toggle
size="sm"
bind:checked={
() => cloud,
(v) => {
cloud = v
apply()
}
}
options={{ right: 'Cloud (app.windmill.dev)' }}
/>
<span class="text-2xs text-hint">
Cloud-only UI (quotas, upgrade) also needs a backend started with CLOUD_HOSTED.
</span>
</section>
<section class="flex flex-col gap-1.5">
<span class="text-xs font-semibold text-emphasis">Frame width</span>
<ToggleButtonGroup selected={width} onSelected={(v) => (width = v)}>
{#snippet children({ item })}
{#each WIDTHS as w (w.value)}
<ToggleButton value={w.value} label={w.label} {item} size="sm" />
{/each}
{/snippet}
</ToggleButtonGroup>
</section>
<section class="flex flex-col gap-2">
<Button
unifiedSize="sm"
variant="default"
startIcon={{ icon: RotateCw }}
onClick={() => reloadKey++}
>
Reload the frame
</Button>
<Button unifiedSize="sm" variant="subtle" onClick={showComposerAgain}>
Show the composer again if unpinned
</Button>
<Button
unifiedSize="sm"
variant="subtle"
startIcon={{ icon: SquareArrowOutUpRight }}
href={src}
target="_blank"
>
Open in a tab
</Button>
</section>
<p class="text-2xs text-hint mt-auto">
The settings are stored in this browser and apply to every tab of this dev server until set
back to the real setup and cloud off.
</p>
</aside>
<main class="flex-1 min-w-0 flex justify-center overflow-auto p-4">
<div
class="h-full border rounded-md overflow-hidden bg-surface shrink-0"
style:width={width === 'full' ? '100%' : `${width}px`}
>
{#key reloadKey}
<iframe title="Home" {src} class="w-full h-full"></iframe>
{/key}
</div>
</main>
</div>