feat: let a folder be added to the ai session context

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-29 02:41:26 -07:00
co-authored by Claude Opus 5.5
parent b74fc9e187
commit 2c8d421ee4
9 changed files with 125 additions and 106 deletions
@@ -6,6 +6,7 @@
import {
contextElementKey,
createAttachedFileContextElement,
isMentionContext,
isSameContextElement,
type AppDomSelectorElement,
type ContextElement
@@ -864,9 +865,7 @@
// Workspace items are fetched on-demand and not in availableContext,
// so skip the availableContext check for them
const isWorkspaceItem =
contextElement.type === 'workspace_script' ||
contextElement.type === 'workspace_flow' ||
contextElement.type === 'workspace_app'
isMentionContext(contextElement)
if (
!isWorkspaceItem &&
!availableContext.find(
@@ -39,6 +39,7 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
import type { AttachedFile, AttachedFolder } from './files/attachedFiles.svelte'
import {
ContextIconMap,
withFolderContextLeaves,
type ContextElement,
type WorkspaceAppElement,
type WorkspaceFlowElement,
@@ -266,12 +267,14 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
if (diffs) branches.push(diffs)
if (modules) branches.push(modules)
if (dbs) branches.push(dbs)
const wsChildren = buildWorkspaceTree({
loaded: loadedForTree,
kinds: WORKSPACE_KINDS,
loadingKind: loader.loadingKind,
layout: 'flat'
}) as DrillNode<ChatLeafData>[]
const wsChildren: DrillNode<ChatLeafData>[] = withFolderContextLeaves(
buildWorkspaceTree({
loaded: loadedForTree,
kinds: WORKSPACE_KINDS,
loadingKind: loader.loadingKind,
layout: 'flat'
})
)
// Workspace-only (e.g. global chat with no diffs/modules/dbs): skip
// the redundant 'Workspace' row and surface its children at the root.
if (branches.length === 0) return wsChildren
@@ -326,6 +329,9 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
}
onSelectWorkspaceItem(element)
}
} else if (d.type === 'workspace_folder') {
// A folder is a workspace reference like an item, never in availableContext.
onSelectWorkspaceItem?.(d)
} else {
// Runtime context element — added directly.
onSelect(d)
@@ -83,9 +83,7 @@ export default class ContextManager {
this.workspace = workspace
this.selectedContext = currentlySelectedContext.filter(
(context) =>
context.type === 'workspace_script' ||
context.type === 'workspace_flow' ||
context.type === 'workspace_app'
isMentionContext(context)
)
}
@@ -164,9 +162,7 @@ export default class ContextManager {
newSelectedContext = newSelectedContext
.filter(
(c) =>
c.type === 'workspace_script' ||
c.type === 'workspace_flow' ||
c.type === 'workspace_app' ||
isMentionContext(c) ||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
)
.map((c) =>
@@ -293,9 +289,7 @@ export default class ContextManager {
c.type === 'code' ||
// Workspace references are user-picked via @-mention and not in
// availableContext; preserve so badges survive editor refreshes.
c.type === 'workspace_script' ||
c.type === 'workspace_flow' ||
c.type === 'workspace_app' ||
isMentionContext(c) ||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
)
.map((c) => {
@@ -1,7 +1,7 @@
<!--
@component
Workspace-only picker for the AI session composer's `+ -> Mention file`
submenu. It mirrors ChatContextPicker's workspace branch, but starts directly
submenu. It mirrors ChatContextPicker's workspace branch, folders included, but starts directly
at the workspace root because the parent menu item already names the scope.
-->
<script lang="ts">
@@ -17,13 +17,17 @@ at the workspace root because the parent menu item already names the scope.
import { useWorkspaceItemsLoader } from '$lib/components/workspaceItemsLoader.svelte'
import { buildWorkspaceTree, relativizeWorkspacePath } from '$lib/components/workspaceTree'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import type {
ContextElement,
WorkspaceAppElement,
WorkspaceFlowElement,
WorkspaceScriptElement
import {
withFolderContextLeaves,
type ContextElement,
type WorkspaceAppElement,
type WorkspaceFlowElement,
type WorkspaceFolderElement,
type WorkspaceScriptElement
} from './context'
type LeafData = WorkspaceItem | WorkspaceFolderElement
interface Props {
onSelect: (element: ContextElement) => void
onAfterClose?: () => void
@@ -50,13 +54,15 @@ at the workspace root because the parent menu item already names the scope.
return { ...loaded, app: loaded.app.filter((a) => a.raw_app) }
})
const tree = $derived<DrillNode<WorkspaceItem>[]>(
buildWorkspaceTree({
loaded: loadedForTree,
kinds: WORKSPACE_KINDS,
loadingKind: loader.loadingKind,
layout: 'flat'
}) as DrillNode<WorkspaceItem>[]
const tree = $derived<DrillNode<LeafData>[]>(
withFolderContextLeaves(
buildWorkspaceTree({
loaded: loadedForTree,
kinds: WORKSPACE_KINDS,
loadingKind: loader.loadingKind,
layout: 'flat'
})
)
)
function workspaceElement(item: WorkspaceItem): ContextElement | undefined {
@@ -89,8 +95,8 @@ at the workspace root because the parent menu item already names the scope.
}
}
function handlePick(leaf: DrillLeaf<WorkspaceItem>) {
const element = workspaceElement(leaf.data)
function handlePick(leaf: DrillLeaf<LeafData>) {
const element = 'kind' in leaf.data ? workspaceElement(leaf.data) : leaf.data
if (!element) return
onSelect(element)
close(onAfterClose)
@@ -119,11 +125,15 @@ at the workspace root because the parent menu item already names the scope.
}
</script>
{#snippet leafIcon(leaf: DrillLeaf<WorkspaceItem>)}
<RowIcon kind={leaf.data.kind} size={12} />
{#snippet leafIcon(leaf: DrillLeaf<LeafData>)}
{#if 'kind' in leaf.data}
<RowIcon kind={leaf.data.kind} size={12} />
{:else}
<Folder size={12} class="shrink-0 text-tertiary" />
{/if}
{/snippet}
{#snippet branchIcon(branch: DrillBranch<WorkspaceItem>)}
{#snippet branchIcon(branch: DrillBranch<LeafData>)}
{#if branch.icon}
{@const Icon = branch.icon}
<Icon size={12} class="shrink-0 text-tertiary" />
@@ -140,7 +150,10 @@ at the workspace root because the parent menu item already names the scope.
onPick={handlePick}
{leafIcon}
{branchIcon}
leafSecondary={(leaf, scope) => relativizeWorkspacePath(workspaceItemDisplayPath(leaf.data), scope)}
leafSecondary={(leaf, scope) =>
'kind' in leaf.data
? relativizeWorkspacePath(workspaceItemDisplayPath(leaf.data), scope)
: undefined}
onScopeChange={handleScopeChange}
onFilterChange={loader.onFilterChange}
rootLoading={WORKSPACE_KINDS.some((k) => !loader.loaded[k] && loader.loadingKind[k])}
@@ -9,13 +9,16 @@ import {
TextSelect,
Table2,
LayoutDashboard,
MousePointer2
MousePointer2,
Folder
} from 'lucide-svelte'
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
import type { ScriptLang } from '$lib/gen/types.gen'
import { type DBSchema } from '$lib/stores'
import { type Change } from 'diff'
import type { AppDatatableMetadata, BackendRunnable, SelectedContext } from './app/core'
import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker'
import { dirKey } from '$lib/components/workspacePicker'
export const ContextIconMap = {
code: Code,
@@ -31,6 +34,7 @@ export const ContextIconMap = {
workspace_script: Code2,
workspace_flow: BarsStaggered,
workspace_app: LayoutDashboard,
workspace_folder: Folder,
// Fallback — the badge renders attached_file with the per-extension file icon.
attached_file: FileText
// flow_module type is handled with FlowModuleIcon
@@ -286,6 +290,43 @@ export interface WorkspaceAppElement {
summary?: string
}
/** Workspace folder context element — a whole `f/<folder>`, its items read by the chat on
* demand like any other workspace reference. */
export interface WorkspaceFolderElement {
type: 'workspace_folder'
path: string
title: string
}
export function folderContextElement(path: string): WorkspaceFolderElement & { deletable: boolean } {
return { type: 'workspace_folder', path, title: path, deletable: true }
}
const FOLDER_DIR_PREFIX = dirKey('all', 'f/')
/** Opens every `f/` folder of a flat workspace tree (any depth) on a leaf that picks the folder
* itself, so a folder is taken as context from inside it, or by searching its path. */
export function withFolderContextLeaves<L>(
nodes: DrillNode<L>[]
): DrillNode<L | WorkspaceFolderElement>[] {
return nodes.map((node) => {
if (node.type !== 'branch') return node
const children = withFolderContextLeaves(node.children)
if (!node.key.startsWith(FOLDER_DIR_PREFIX)) return { ...node, children }
const path = node.key.slice(FOLDER_DIR_PREFIX.length - 'f/'.length)
const leaf: DrillLeaf<WorkspaceFolderElement> = {
type: 'leaf',
key: `folder:${path}`,
label: 'Whole folder',
secondary: path,
icon: Folder,
data: folderContextElement(path),
searchableText: path
}
return { ...node, children: [leaf, ...children] }
})
}
/** Message-attached text file, rendered with the shared context badge. Never part
* of `selectedContext` — constructed at render time from the composer's / a sent
* message's `files` state (see createAttachedFileContextElement). */
@@ -318,6 +359,7 @@ export type ContextElement = (
| WorkspaceScriptElement
| WorkspaceFlowElement
| WorkspaceAppElement
| WorkspaceFolderElement
| AttachedFileElement
) & {
deletable?: boolean
@@ -334,8 +376,18 @@ export function contextElementKey(c: ContextElement): string {
/** An `@`-mentioned workspace item, attached to one message the way a DOM pick
* is. Membership only: this does not gate on mode, so every caller must. Outside
* GLOBAL these stay selected as chips the user removes by hand. */
export function isMentionContext(c: ContextElement): boolean {
return c.type === 'workspace_script' || c.type === 'workspace_flow' || c.type === 'workspace_app'
export type MentionContext = Extract<
ContextElement,
{ type: 'workspace_script' | 'workspace_flow' | 'workspace_app' | 'workspace_folder' }
>
export function isMentionContext(c: ContextElement): c is MentionContext {
return (
c.type === 'workspace_script' ||
c.type === 'workspace_flow' ||
c.type === 'workspace_app' ||
c.type === 'workspace_folder'
)
}
export function isSameContextElement(a: ContextElement, b: ContextElement): boolean {
@@ -173,7 +173,7 @@ import { scriptLangToEditorLang } from '$lib/scripts'
import { appFileEditorLang } from '../appFileEditorLang'
import { searchDocsTool, readDocsPageTool } from '../docs/core'
import { createDbSchemaTool } from '../script/core'
import type { ContextElement } from '../context'
import { isMentionContext, type ContextElement } from '../context'
import { getDatatableTools } from '../datatableTools'
import { getDatatableMigrationTools } from '../datatableMigrationTools'
import { getDucklakeTools } from '../ducklakeTools'
@@ -9753,12 +9753,7 @@ export function prepareGlobalUserMessage(
selectedContext: ContextElement[] = [],
options: GlobalUserMessageOptions = {}
): ChatCompletionUserMessageParam {
const selectedWorkspaceItems = selectedContext.filter(
(context) =>
context.type === 'workspace_script' ||
context.type === 'workspace_flow' ||
context.type === 'workspace_app'
)
const selectedWorkspaceItems = selectedContext.filter(isMentionContext)
const activeEditor =
options.activeEditor ??
(options.workspace ? getActiveGlobalEditorContext(options.workspace) : undefined)
@@ -9789,6 +9784,10 @@ export function prepareGlobalUserMessage(
if (selectedWorkspaceItems.length > 0) {
content += '## SELECTED CONTEXT\n'
for (const context of selectedWorkspaceItems) {
if (context.type === 'workspace_folder') {
content += `- type: folder, path: ${context.path} (its items: list_workspace_items with path_prefix "${context.path}/")\n`
continue
}
const itemType =
context.type === 'workspace_script'
? 'script'
@@ -465,6 +465,11 @@ export function buildContextString(selectedContext: ContextElement[]): string {
workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n'
}
workspaceItemsContext += `- type: raw_app, path: ${context.path}\n`
} else if (context.type === 'workspace_folder') {
if (!workspaceItemsContext) {
workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n'
}
workspaceItemsContext += `- type: folder, path: ${context.path}\n`
}
}
@@ -3,11 +3,13 @@
import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte'
import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte'
import { Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte'
import { AtSign, Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte'
import { userStore } from '$lib/stores'
import Dropdown from '$lib/components/DropdownV2.svelte'
import TreeOwnerRow from './TreeOwnerRow.svelte'
import HomeFolderBadge from './HomeFolderBadge.svelte'
import { homeComposerContext } from '../sessions/homeComposerContext.svelte'
import { folderContextElement } from '../copilot/chat/context'
import PipelineRow from '../common/table/PipelineRow.svelte'
import Item from './Item.svelte'
import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils'
@@ -304,6 +306,13 @@
fixedHeight={false}
placement="bottom-start"
items={[
{
displayName: 'Add to AI session context',
icon: AtSign,
type: 'ai',
action: () => homeComposerContext.attach(folderContextElement(`f/${folderName}`)),
hide: !homeComposerContext.available
},
{
displayName: canWrite ? 'Manage folder' : 'View folder',
icon: canWrite ? Pen : Eye,
@@ -1,58 +0,0 @@
<script lang="ts">
import { ChevronLeft, ChevronRight, MessagesSquare } from 'lucide-svelte'
import { page } from '$app/state'
import MenuButton from '$lib/components/sidebar/MenuButton.svelte'
import SessionPicker from './SessionPicker.svelte'
import { swapSidebarList } from './sessionSwitch.svelte'
import type { SidebarList } from './sidebarList.svelte'
let { list, isCollapsed = false }: { list: SidebarList; isCollapsed?: boolean } = $props()
// Hovering the row opens the session menu; a click shows the session list instead. Taken
// in the capture phase, ahead of the menu's own trigger, which would pin the menu open.
// The menu opens and closes on hover by calling click() on that trigger: those untrusted
// clicks are its own and pass through.
function showSessions(e: MouseEvent) {
if (!e.isTrusted) return
e.preventDefault()
e.stopPropagation()
swapSidebarList('sessions', page.url.pathname === '/')
}
</script>
{#if list === 'workspace'}
<div onclickcapture={showSessions} role="none">
<SessionPicker {isCollapsed}>
{#snippet hoverTrigger({ trigger, unread })}
<div class="relative">
<MenuButton
{trigger}
{isCollapsed}
icon={MessagesSquare}
label="AI Sessions"
class="!text-xs"
trailingIcon={ChevronRight}
aiId="sidebar-menu-ai-sessions"
aiDescription="Button to show the AI sessions list in the sidebar"
/>
{#if unread > 0}
<span
class="absolute top-1 right-1 pointer-events-none inline-block w-2 h-2 rounded-full bg-surface-accent-primary"
aria-label="{unread} unread message{unread === 1 ? '' : 's'} across all sessions"
></span>
{/if}
</div>
{/snippet}
</SessionPicker>
</div>
{:else}
<MenuButton
on:click={() => swapSidebarList('workspace', page.url.pathname === '/')}
{isCollapsed}
icon={ChevronLeft}
label="Workspace"
class="!text-xs"
aiId="sidebar-menu-workspace"
aiDescription="Button to show the workspace navigation in the sidebar"
/>
{/if}