chore: move working folders and folder instructions to their own pr

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-30 05:59:59 -07:00
co-authored by Claude Opus 5.5
parent 65f6ecfd39
commit 086ffadb9f
33 changed files with 155 additions and 1930 deletions
+1 -1
View File
@@ -1 +1 @@
9084bd523e19c5de1f43568714c6aeaf6a466368
26663361632280a25b964e6f3944e503dca2a366
@@ -179,11 +179,10 @@
height as one replaces another. That needs a definite height from the caller.
`inert` and not just opacity: an off-screen page keeps its DOM, so without it the
tab order and every screen reader still walk through it. -->
<!-- `tabindex="-1"`: focusable programmatically, never a tab stop of its own, so no
focus ring: one around the whole page after a keyboard navigation marks nothing. -->
<!-- `tabindex="-1"`: focusable programmatically, never a tab stop of its own. -->
<div
tabindex="-1"
class="paged-content-page absolute inset-0 flex flex-col outline-none"
class="paged-content-page absolute inset-0 flex flex-col"
class:is-hidden={i !== index}
class:opacity-0={i !== index}
class:pointer-events-none={i !== index}
@@ -35,8 +35,6 @@
import AIChatModelSettings from './AIChatModelSettings.svelte'
import ScrollFade from '$lib/components/ScrollFade.svelte'
import AssistantSettingsModal from './AssistantSettingsModal.svelte'
import WorkingInPicker from './WorkingInPicker.svelte'
import { scopeLabel } from './workingScope'
import { SkillsMenu } from './skills/skillsMenu.svelte'
import { McpMenu } from '$lib/components/mcp/mcpMenu.svelte'
import ChatMode from './ChatMode.svelte'
@@ -646,31 +644,6 @@
const waitingForUserAction = $derived(chatHost.loading && !!pendingUserAction(messages))
// The out-of-scope card appears in the transcript without taking focus, so a screen reader
// hears about it from a live region that stays mounted and changes its text.
const outOfScopeAnnouncement = $derived.by(() => {
const held = [...messages]
.reverse()
.find((m) => m.role === 'tool' && m.isLoading && m.outOfScope && !m.outOfScope.decision)
if (held?.role !== 'tool' || !held.outOfScope) return ''
const { path, scope, verb } = held.outOfScope
return `This would ${verb} ${path}, outside ${scope}. Allow once, or allow writes in ${held.outOfScope.root}.`
})
// The turns sent in another scope than the turn before, with the scope they took.
const scopeChanges = $derived.by(() => {
const changes = new Map<number, string | null>()
let previous: string | undefined
messages.forEach((m, i) => {
// Read back from saved chats, so only a list or `null` counts.
if (m.role !== 'user' || (m.workingIn !== null && !Array.isArray(m.workingIn))) return
const label = m.workingIn ? scopeLabel(m.workingIn) : ''
if (previous !== undefined && label !== previous) changes.set(i, label || null)
previous = label
})
return changes
})
// Gated on `loading` because a card restored from history still looks parked:
// its resolver left with the old page, so the composer must not advertise an
// answer it cannot deliver.
@@ -912,13 +885,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
isLast: boolean,
inGroup: boolean
)}
{#if scopeChanges.has(messageIndex)}
{@const root = scopeChanges.get(messageIndex)}
<p class="mt-4 text-center text-2xs text-tertiary">
Now working in {#if root}<span class="font-mono">{root}</span>{:else}the whole
workspace{/if}
</p>
{/if}
<AIChatMessage
{message}
{messageIndex}
@@ -980,7 +946,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
/>
</div>
{/if}
<div class="sr-only" role="status">{outOfScopeAnnouncement}</div>
</div>
</div>
<!-- Sits below the scroll-to-latest button, which carries z-10. -->
@@ -1110,9 +1075,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{onSent}
>
{#snippet collapsedControls()}
{#if chatHost.mode === AIMode.GLOBAL}
<WorkingInPicker ws={aiChatManager.operatingWorkspace ?? ''} onlyWhenScoped />
{/if}
{#if chatHost.supportsModelSettings}
<AIChatModelSettings promptSettings={false} />
{/if}
@@ -1356,9 +1318,6 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/snippet}
</Tooltip>
{/if}
{#if chatHost.mode === AIMode.GLOBAL}
<WorkingInPicker ws={aiChatManager.operatingWorkspace ?? ''} />
{/if}
{#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled}
<ChatQuickActions {askAi} {diffMode} />
{/if}
@@ -157,21 +157,10 @@ import {
import { workModeSwitchTools } from './workModeSwitch'
import { filterSessionTools, sessionToolAllowed } from './global/sessionToolset'
import {
formatFolderInstructions,
instructionsCovering,
listFolderInstructions,
readFolderInstructionBody,
type FolderInstruction,
type FolderInstructionsDelivery
} from './folderInstructions'
import {
logWorkingScope,
ownerRoot,
scopeKind,
WorkingScope,
type ScopeDecision,
type ScopeSource
} from './workingScope'
import {
loadWorkspaceSkills,
resolveGlobalPromptIdentity,
@@ -925,9 +914,6 @@ export class AIChatManager implements ChatViewHost {
{ resolve: (value: boolean) => void; toolName?: string }
>()
private userQuestionCallbacks = new Map<string, (choices: string[] | undefined) => void>()
// Kept apart from confirmationCallbacks: YOLO answers those, and never answers these.
// Resolved undefined when the turn stops first.
private scopeCallbacks = new Map<string, (decision: ScopeDecision | undefined) => void>()
/**
* One run form's whole life while it waits, so ending it is one delete and cannot end half
* of it. Held here rather than in the form, which unmounts and remounts as it moves between
@@ -949,96 +935,6 @@ export class AIChatManager implements ChatViewHost {
// sessions modules — and re-read on every system-message rebuild; the send
// path rebuilds after beforeSend, so a fork committed there is picked up.
sessionContextResolver: (() => SessionPromptContext | undefined) | undefined = undefined
// The session's scope, read from its record (roots undefined for the whole workspace), and
// the write that stores a change the user makes. Same seam as above. Unset outside sessions,
// which always work in the whole workspace.
workingInResolver:
| (() => { roots: readonly string[] | undefined; source: ScopeSource })
| undefined = undefined
onWorkingInChanged:
| ((roots: readonly string[] | undefined, source: 'manual' | undefined) => void)
| undefined = undefined
/** The scope the picker shows: the session's, which the next turn takes. */
get workingIn(): readonly string[] | undefined {
return this.workingInResolver?.().roots
}
get supportsWorkingIn(): boolean {
return this.workingInResolver !== undefined
}
/** The scope the running turn took when it was sent: a change from the picker waits for the
* next turn, so the prompt and the gate agree for the whole request. Undefined between turns. */
#turnScope: { roots: readonly string[] | undefined } | undefined = undefined
/** A pick in the picker; `fallback` for the scope dropped because the folder is not in the
* workspace "Acting on" switched to, which leaves the default rather than a choice. */
setWorkingIn = (roots: readonly string[] | undefined, { fallback = false } = {}) => {
this.onWorkingInChanged?.(roots, fallback ? undefined : 'manual')
// Before the first send, that send counts the scope it goes out in.
if (this.#loggedScopeSet && !fallback) {
logWorkingScope(`scope:${scopeKind(roots)}:manual`, this.operatingWorkspace)
}
if (this.#turnScope) return
if (this.mode === AIMode.GLOBAL) {
void this.refreshGlobalFolderInstructions()
this.configureGlobalMode()
}
}
/** The card's "Allow writes in <root>": unlike the picker, it applies to the running turn. */
#addToScope = (root: string) => {
const roots = this.#turnScope ? this.#turnScope.roots : this.workingIn
if (!roots || roots.includes(root)) return
const next = [...roots, root]
this.onWorkingInChanged?.(next, 'manual')
if (this.#turnScope) this.#turnScope = { roots: next }
}
/** What a picker row badges: the instructions, skills and MCP servers under it. */
get scopeResources(): {
instructions: readonly { path: string }[]
skills: readonly { path: string }[]
mcpServers: readonly { path: string }[]
} {
return {
instructions: this.globalFolderInstructions,
skills: this.globalSkills,
mcpServers: this.mcpServers
}
}
get scopeIdentity(): GlobalPromptIdentity | undefined {
return this.globalIdentity
}
// Use writes nothing, so a scope there would only narrow listing and swap skills without
// guarding anything: the session works as if no folder were picked.
#workingScope = (): WorkingScope | undefined =>
this.mode === AIMode.GLOBAL && this.workingInResolver && !this.useModeActive
? new WorkingScope(
this.#turnScope ? this.#turnScope.roots : this.workingIn,
this.globalIdentity
)
: undefined
/** The scope in force: the running turn's, else the one the next turn takes. */
get workingScope(): WorkingScope | undefined {
return this.#workingScope()
}
// Skills saved in other folders are suspended while scoped, from every way in: the prompt's
// list, the `/` picker and a typed `/name`. read_skill refuses them on its own.
#loadedSkills = (): AiSkillListItem[] => {
const scope = this.#workingScope()
return scope ? this.globalSkills.filter((s) => scope.loadsSkill(s.path)) : this.globalSkills
}
/** The scoped folders' instructions, formatted for the system prompt, and the paths they
* carry, which first-touch delivery then skips. `scope` is the label they were read for. */
#scopeInstructions: { scope: string; workspace: string; text: string; paths: string[] } | undefined =
undefined
/** Folders a whole-workspace session wrote to, for the `written:` counter. */
#writtenRoots = new Set<string>()
#loggedScopeSet = false
/** The scoped folders' instructions, while they were read for the scope and workspace in
* force: a scope changed since keeps none until the next refresh rather than the old ones. */
#currentScopeInstructions = (scope = this.#workingScope()) => {
const held = this.#scopeInstructions
return held && held.scope === scope?.label && held.workspace === (this.operatingWorkspace ?? '')
? held
: undefined
}
// Whether another tab is running a turn on this session right now (sessions
// wiring, same seam as above). The composer locks on it, and sendRequest
// refuses on it — the refusal covers the send already in flight when the
@@ -1604,7 +1500,7 @@ export class AIChatManager implements ChatViewHost {
// The `ai_instruction` resources readable in the operating workspace, loaded
// alongside skills. The prompt names their folders; the tool loop delivers each
// one's body the first time a call touches its folder, recording which call did.
private globalFolderInstructions = $state<FolderInstruction[]>([])
private globalFolderInstructions: FolderInstruction[] = []
private globalFolderInstructionsRefreshId = 0
private folderInstructionsDeliveredBy = new Map<string, FolderInstructionsDelivery>()
@@ -1645,7 +1541,7 @@ export class AIChatManager implements ChatViewHost {
// those by path and the submit path declines to guess between them.
sessionCommands: ChatCommandItem[] = $derived([
...this.sessionBuiltinCommands,
...this.#loadedSkills()
...this.globalSkills
.filter((s) => !this.sessionBuiltinCommands.some((b) => b.name === s.name))
.map((s) => ({ ...s, kind: 'skill' as const }))
])
@@ -2155,33 +2051,6 @@ export class AIChatManager implements ChatViewHost {
})
}
requestScopeDecision = (toolId: string): Promise<ScopeDecision | undefined> =>
new Promise((resolve) => {
this.scopeCallbacks.set(toolId, resolve)
})
handleScopeDecision = (toolId: string, decision: ScopeDecision) => {
const resolve = this.scopeCallbacks.get(toolId)
if (!resolve) return
this.scopeCallbacks.delete(toolId)
logWorkingScope(`block:${decision}`, this.operatingWorkspace)
resolve(decision)
}
/** Counts the folders a whole-workspace session's AI writes to: `1` on its first, `2+` on
* its second, which is where a one-folder scope would have got in the way. */
#recordWrite = (paths: readonly string[]) => {
if (!this.workingInResolver || this.#workingScope()?.roots) return
const before = this.#writtenRoots.size
for (const path of paths) {
const root = ownerRoot(path)
if (root) this.#writtenRoots.add(root)
}
const after = this.#writtenRoots.size
if (before === 0 && after >= 1) logWorkingScope('written:1', this.operatingWorkspace)
if (before < 2 && after >= 2) logWorkingScope('written:2+', this.operatingWorkspace)
}
// Handle confirmation response for a specific tool
handleToolConfirmation = (toolId: string, confirmed: boolean) => {
const confirmationCallback = this.confirmationCallbacks.get(toolId)
@@ -2936,21 +2805,16 @@ export class AIChatManager implements ChatViewHost {
this.syncArtifactsSession()
}
private globalAssemblyOpts = (): GlobalAssemblyOpts => {
const workingScope = this.#workingScope()
return {
previewTools: this.isSessionChat,
user: this.globalIdentity,
skills: this.#loadedSkills(),
folderInstructions: this.globalFolderInstructions,
mcpServers: this.mcpServers,
workingScope,
scopeInstructions: this.#currentScopeInstructions(workingScope)?.text,
access: this.#toolAccess,
sessionContext: this.#sessionPromptContext(),
pipelineFolders: this.#pipelineFolders()
}
}
private globalAssemblyOpts = (): GlobalAssemblyOpts => ({
previewTools: this.isSessionChat,
user: this.globalIdentity,
skills: this.globalSkills,
folderInstructions: this.globalFolderInstructions,
mcpServers: this.mcpServers,
access: this.#toolAccess,
sessionContext: this.#sessionPromptContext(),
pipelineFolders: this.#pipelineFolders()
})
#sessionPromptContext = (): SessionPromptContext | undefined => {
const ctx = this.sessionContextResolver?.()
@@ -2993,34 +2857,6 @@ export class AIChatManager implements ChatViewHost {
}
this.globalFolderInstructions =
workspace === (this.operatingWorkspace ?? '') ? instructions : []
const scope = this.#workingScope()
const covering = scope?.roots
? instructionsCovering(this.globalFolderInstructions, scope.roots)
: []
const blocks = (
await Promise.all(
covering.map(async (instruction) => {
try {
return { instruction, body: await readFolderInstructionBody(workspace, instruction.path) }
} catch (e) {
console.error(`Failed to read folder instructions ${instruction.path}`, e)
return undefined
}
})
)
).filter((b) => b !== undefined)
if (refreshId !== this.globalFolderInstructionsRefreshId) {
return
}
this.#scopeInstructions =
scope?.roots && blocks.length
? {
scope: scope.label,
workspace,
text: formatFolderInstructions(blocks),
paths: blocks.map((b) => b.instruction.path)
}
: undefined
if (this.mode === AIMode.GLOBAL) {
this.configureGlobalMode()
}
@@ -3125,9 +2961,8 @@ export class AIChatManager implements ChatViewHost {
}
// A path identifies one skill; a name shared by two would otherwise silently
// apply instructions the user did not choose, so it is left unexpanded.
const skills = this.#loadedSkills()
const byPath = skills.find((s) => s.path === match[1])
const matches = byPath ? [byPath] : skills.filter((s) => s.name === match[1])
const byPath = this.globalSkills.find((s) => s.path === match[1])
const matches = byPath ? [byPath] : this.globalSkills.filter((s) => s.name === match[1])
if (matches.length !== 1) {
return instructions
}
@@ -4060,11 +3895,6 @@ export class AIChatManager implements ChatViewHost {
// controller here that abort would hit nothing and the request would still fire
// once the pre-flight resolves; the pre-flight-cancel check after beforeSend honours it.
this.abortController = new AbortController()
// Taken once, with the message: the bubble records the scope it was sent in, and the
// prompt and gate keep it for the whole turn.
const sentScope =
this.mode === AIMode.GLOBAL && !this.useModeActive ? this.workingInResolver?.() : undefined
if (sentScope) this.#turnScope = { roots: sentScope.roots }
this.displayMessages = [
...this.displayMessages,
{
@@ -4076,7 +3906,6 @@ export class AIChatManager implements ChatViewHost {
images: images.length > 0 ? images : undefined,
files: files.length > 0 ? files : undefined,
synthetic: options.synthetic ? true : undefined,
workingIn: sentScope ? (sentScope.roots ? [...sentScope.roots] : null) : undefined,
index: this.messages.length // matching with actual messages index. not -1 because it's not yet added to the messages array
}
]
@@ -4090,7 +3919,6 @@ export class AIChatManager implements ChatViewHost {
this.displayMessages = this.displayMessages.filter((_, i) => i !== optimisticIndex)
this.loading = false
this.loadingLabel = undefined
this.#turnScope = undefined
}
if (this.beforeSend) {
try {
@@ -4130,13 +3958,6 @@ export class AIChatManager implements ChatViewHost {
// keeps the prompt — the cached prefix of every iteration — stable for the whole
// request.
if (this.mode === AIMode.GLOBAL) {
if (sentScope && !this.#loggedScopeSet) {
this.#loggedScopeSet = true
logWorkingScope(
`scope:${scopeKind(sentScope.roots)}:${sentScope.source}`,
this.operatingWorkspace
)
}
await Promise.all([
this.refreshGlobalIdentity(this.operatingWorkspace ?? ''),
this.refreshGlobalSkills(this.operatingWorkspace ?? ''),
@@ -4588,14 +4409,7 @@ export class AIChatManager implements ChatViewHost {
onJobDetached: (jobId) => this.markJobDetached(jobId),
folderInstructions: {
list: () => this.globalFolderInstructions,
deliveredBy: this.folderInstructionsDeliveredBy,
inPrompt: () => this.#currentScopeInstructions()?.paths ?? []
},
workingScope: {
scope: this.#workingScope,
requestDecision: this.requestScopeDecision,
add: this.#addToScope,
recordWrite: this.#recordWrite
deliveredBy: this.folderInstructionsDeliveredBy
}
}
: {}),
@@ -4857,7 +4671,6 @@ export class AIChatManager implements ChatViewHost {
sendUserToast(getSendRequestErrorMessage(err, webSearchUnavailable), true)
} finally {
this.loading = false
this.#turnScope = undefined
// Backstop for the paths that leave the try without reaching either call
// above (a pre-flight throw, an aborted compaction).
stopCheckpoints()
@@ -4912,11 +4725,6 @@ export class AIChatManager implements ChatViewHost {
resolve(false)
}
this.confirmationCallbacks.clear()
for (const resolve of this.scopeCallbacks.values()) {
logWorkingScope('block:none', this.operatingWorkspace)
resolve(undefined)
}
this.scopeCallbacks.clear()
for (const resolveQuestion of this.userQuestionCallbacks.values()) {
resolveQuestion(undefined)
}
@@ -1,61 +1,29 @@
<!--
@component
The Instructions section of the assistant settings modal: every block of instructions the
assistant follows, in one list — the workspace one an admin sets for everyone, the user one
stored in this browser, then each folder's `ai_instruction` resources in a tree. A row opens
its block on a detail page laid over the list, like a skill in the Skills section.
The Instructions section of the assistant settings modal: the two blocks of custom
instructions the system prompt carries — the workspace one an admin sets for everyone,
and the user one stored in this browser — a tab each, both editable in place. One Save
writes whichever of the two changed, including the tab that is not on screen.
-->
<script lang="ts">
import { Button, ListRow, Section } from '$lib/components/common'
import { Button, Section, Tab, TabContent, Tabs } from '$lib/components/common'
import Description from '$lib/components/Description.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import Alert from '$lib/components/common/alert/Alert.svelte'
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import PagedContent from '$lib/components/common/modal/PagedContent.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import Label from '$lib/components/Label.svelte'
import Path from '$lib/components/Path.svelte'
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
import Markdown from 'svelte-exmarkdown'
import { gfmPlugin } from 'svelte-exmarkdown/gfm'
import { markdownProse } from '$lib/components/markdownProse'
import {
copilotInfo,
getUserCustomPrompts,
setCopilotInfo,
setUserCustomPrompts
} from '$lib/aiStore'
import { ResourceService, WorkspaceService } from '$lib/gen'
import { WorkspaceService } from '$lib/gen'
import { userStore, type UserExt } from '$lib/stores'
import { getUserExt } from '$lib/user'
import { sendUserToast } from '$lib/toast'
import {
ArrowLeft,
Building2,
ChevronDown,
ChevronRight,
ExternalLink,
Eye,
Folder,
FolderTree,
Pencil,
Plus,
RotateCcw,
ScrollText,
Trash2,
User
} from 'lucide-svelte'
import { Building2, ExternalLink, User } from 'lucide-svelte'
import { untrack } from 'svelte'
import { getAiChatManager } from './aiChatManagerContext'
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import {
listFolderInstructionRows,
readFolderInstructionBody,
saveFolderInstruction,
type FolderInstructionRow
} from './folderInstructions'
import { buildSkillTree, countSkills, type SkillTreeNode } from './skills/skillTree'
const operatingUser = useOperatingUser()
const actingUser = $derived(operatingUser.current)
@@ -67,12 +35,12 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
}: {
/** The workspace the chat operates on, which is not always the one on screen. */
ws: string
/** Whether this is the panel on screen. The list costs a settings read and a
* resource listing, so it is fetched when someone looks at instructions rather
* than on every open of the modal. */
/** Whether this is the panel on screen. The workspace half costs a settings read,
* so it is fetched when someone looks at instructions rather than on every open
* of the modal. */
active: boolean
/** True while this section is in the middle of something the modal must not
* close under: a detail page, instructions typed and not yet saved, a dialog. */
* close under — here, instructions typed and not yet saved. */
blocksClose: boolean
} = $props()
@@ -84,6 +52,12 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
let aiSettingsHref = $derived(`/workspace_settings?workspace=${ws}&tab=ai`)
let mode = $derived(aiChatManager.mode)
let tab = $state<'workspace' | 'user'>('workspace')
let note = $derived(
tab === 'workspace'
? `Applies to everyone in ${ws}.`
: 'Stored in this browser and sent in every workspace, so they follow you rather than the workspace.'
)
// `actingUser?.is_admin` is the role in the nav workspace, not necessarily in `ws`, so
// the resolved role is keyed to the workspace it was read for, and an unresolved one
// reads as no admin: offering the field and taking it away on resolve would discard
@@ -140,56 +114,10 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
let workspaceChanged = $derived(!workspaceReadOnly && workspaceDraft !== workspaceSaved)
let userChanged = $derived(userDraft !== userSaved)
type Detail =
| { kind: 'workspace' }
| { kind: 'user' }
| { kind: 'folder'; row: FolderInstructionRow }
| { kind: 'new' }
/** The block the detail page holds, with the workspace it was opened in: a folder's
* instructions read in A must not stay on screen, and be saved, after a switch to B.
* Kept after the page closes, so the page sliding away still shows what it held. */
let opened = $state<{ workspace: string; detail: Detail } | undefined>(undefined)
let detailOpen = $state(false)
let detail = $derived(opened?.workspace === ws ? opened.detail : undefined)
let showingDetail = $derived(detailOpen && detail !== undefined)
let folderRows = $state<FolderInstructionRow[]>([])
let folderLoadError = $state<string | undefined>(undefined)
let tree = $derived(buildSkillTree(folderRows))
/** Folders the user closed, keyed by full prefix. */
let collapsed = $state<Record<string, boolean>>({})
// The folder instruction on the detail page: what Monaco holds against what was read.
let folderContent = $state('')
let folderOriginal = $state('')
let folderMode = $state<'view' | 'edit'>('view')
let newPath = $state('')
let newPathError = $state('')
let editorSeq = $state(0)
let bodyEditor: SimpleEditor | undefined = $state(undefined)
/** Bumped on every open of a folder instruction or a new one, so a read or a save that
* lands after the user moved to another one leaves that one's editor alone. */
let visit = 0
let toDelete = $state<FolderInstructionRow | undefined>(undefined)
let folderChanged = $derived(
detail?.kind === 'new'
? folderContent.trim() !== ''
: detail?.kind === 'folder' && folderContent !== folderOriginal
)
let dirty = $derived(workspaceChanged || userChanged || folderChanged)
/** Whether the block on the detail page has unsaved text. */
let pageChanged = $derived(
detail?.kind === 'workspace'
? workspaceChanged
: detail?.kind === 'user'
? userChanged
: folderChanged
)
let dirty = $derived(workspaceChanged || userChanged)
$effect(() => {
blocksClose = dirty || showingDetail || toDelete !== undefined
blocksClose = dirty
})
// Loaded on the first look and again on a workspace switch: B's instructions must not
@@ -203,14 +131,13 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
const shown = active
const clean = !dirty
untrack(() => {
// Parked: read again on the next visit, since every block is editable from
// elsewhere too.
// Parked: read again on the next visit, since the workspace half is editable
// from the settings page too.
if (!shown) {
loadedWorkspace = undefined
return
}
if (!target || !clean || target === loadedWorkspace) return
if (loadedWorkspace !== undefined) collapsed = {}
loadedWorkspace = target
void load(target)
})
@@ -238,13 +165,12 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
sendUserToast(`Failed to load workspace AI prompt: ${err}`, true)
}
}
await loadFolders(target, resolved)
if (seq !== loadSeq) return
workspaceMissingProviders = missingProviders
// Read before the assignments below move the baseline they compare against.
// Each half is then seeded only while it still holds what it was loaded with:
// the effect that starts this checks `dirty` before the request, not after it,
// so an admin who opens the block and types straight away would otherwise have
// so an admin who opens the tab and types straight away would otherwise have
// the settings response land on top of the text they are in the middle of.
const keepWorkspaceDraft = workspaceChanged
const keepUserDraft = userChanged
@@ -257,186 +183,25 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
}
}
let folderSeq = 0
async function loadFolders(target: string, user = roleRead?.user) {
const seq = ++folderSeq
try {
// The role read for `target`, not the nav workspace's: it decides which rows
// offer Edit.
const rows = await listFolderInstructionRows(target, user ?? $userStore ?? undefined)
if (seq !== folderSeq || target !== ws) return
folderRows = rows
folderLoadError = undefined
} catch (e) {
if (seq !== folderSeq || target !== ws) return
folderRows = []
folderLoadError = e.body ?? e.message
}
}
/** Escape backs out one step rather than closing the modal: `blocksClose` holds the
* modal shut meanwhile. On a detail page it first puts unsaved text back, then
* returns to the list; on the list it puts back drafts left there. */
/** Escape puts the fields back rather than closing the modal: `blocksClose` holds the
* modal shut while there is unsaved text, so this is the way out of a draft, and a
* second press then closes. */
function onKeydown(event: KeyboardEvent) {
// Only while this is the section on screen: every section stays mounted, so an
// Escape meant for another one would revert these drafts with nothing visible
// to say that it had.
if (!active || event.key !== 'Escape' || toDelete !== undefined) return
if (showingDetail) {
event.preventDefault()
event.stopPropagation()
if (pageChanged) revertPage()
else closeDetail()
return
}
if (!dirty) return
if (!active || event.key !== 'Escape' || !dirty) return
event.preventDefault()
event.stopPropagation()
workspaceDraft = workspaceSaved
userDraft = userSaved
setFolderContent(folderOriginal)
}
function revertPage() {
if (detail?.kind === 'workspace') workspaceDraft = workspaceSaved
else if (detail?.kind === 'user') userDraft = userSaved
else setFolderContent(folderOriginal)
}
function openBlock(kind: 'workspace' | 'user') {
opened = { workspace: ws, detail: { kind } }
detailOpen = true
}
/** Both the state the form reads and what Monaco shows: `SimpleEditor` takes `code`
* when it builds its model and never again, and the detail page stays mounted. */
function setFolderContent(next: string) {
folderContent = next
bodyEditor?.setCode(next)
}
/** Lands on the rendered instructions: reading them is the common reason to open
* them, and the header's View/Edit switch is one click from the other half. */
async function openFolder(row: FolderInstructionRow) {
// Back to the row whose draft the list marks unsaved: the draft, not the server body.
if (detail?.kind === 'folder' && detail.row.path === row.path && folderChanged) {
detailOpen = true
return
}
// Pinned across the await, and re-checked after it: a switch in between must not
// open A's body under B, where Save would write it.
const source = ws
const seq = ++visit
try {
const body = await readFolderInstructionBody(source, row.path)
if (source !== ws || seq !== visit) return
setFolderContent(body)
folderOriginal = body
folderMode = 'view'
opened = { workspace: source, detail: { kind: 'folder', row } }
detailOpen = true
} catch (e) {
sendUserToast(`Failed to load ${row.path}: ${e.body ?? e.message}`, true)
}
}
function openNew() {
if (blockedByPendingFork()) return
visit++
editorSeq++
newPath = ''
setFolderContent('')
folderOriginal = ''
folderMode = 'edit'
opened = { workspace: ws, detail: { kind: 'new' } }
detailOpen = true
}
function closeDetail() {
detailOpen = false
}
/** Left and Right step between the two pages, which is `PagedContent` answering the
* arrows once it is given this. Forward only goes somewhere once a block was opened. */
function navigate(key: string) {
if (key === 'list') closeDetail()
else if (detail !== undefined) detailOpen = true
}
function blockedByPendingFork(): boolean {
const parent = pendingForkParent()
if (parent === undefined) return false
sendUserToast(
`This session has not created its workspace yet, so the instructions would be written to "${parent}" instead. Send a message first.`,
true
)
return true
}
/** The chat reads the folder list on its next send; told now, so its system prompt
* names a folder just given instructions. Never mid-turn: the refresh would rewrite
* the system prompt underneath a running turn. */
function refreshChat(target: string) {
if (!aiChatManager.loading && !aiChatManager.sendInFlight) {
void aiChatManager.refreshGlobalFolderInstructions(target)
}
}
async function saveFolder() {
const current = detail
if (current?.kind !== 'folder' && current?.kind !== 'new') return
if (blockedByPendingFork()) return
const target = ws
const path = current.kind === 'new' ? newPath : current.row.path
// Monaco hands its text to `folderContent` on a debounce, so the last keystrokes
// before a quick click would otherwise be left out of the save.
bodyEditor?.flushPendingChanges()
const content = folderContent
const seq = visit
async function save() {
saving = true
try {
await saveFolderInstruction(target, path, content, { create: current.kind === 'new' })
sendUserToast(current.kind === 'new' ? `Added ${path}` : `Saved ${path}`)
await loadFolders(target)
refreshChat(target)
// Another instruction opened meanwhile owns the editor now.
if (seq !== visit) return
folderOriginal = content
if (current.kind === 'new') {
const row = folderRows.find((r) => r.path === path)
if (row) opened = { workspace: target, detail: { kind: 'folder', row } }
folderMode = 'view'
}
} catch (e) {
// The editor keeps what was typed, so the save can be retried.
sendUserToast(`Failed to save ${path}: ${e.body ?? e.message}`, true)
} finally {
saving = false
}
}
async function removeFolder(row: FolderInstructionRow) {
if (blockedByPendingFork()) return
const target = ws
try {
await ResourceService.deleteResource({ workspace: target, path: row.path })
sendUserToast(`Deleted ${row.path}`)
setFolderContent('')
folderOriginal = ''
closeDetail()
await loadFolders(target)
refreshChat(target)
} catch (e) {
sendUserToast(`Failed to delete ${row.path}: ${e.body ?? e.message}`, true)
}
}
async function saveBlock() {
saving = true
try {
if (detail?.kind === 'user' && userChanged) saveUser(userDraft.trim())
if (detail?.kind === 'workspace' && workspaceChanged)
await saveWorkspace(workspaceDraft.trim())
if (userChanged) saveUser(userDraft.trim())
if (workspaceChanged) await saveWorkspace(workspaceDraft.trim())
} finally {
saving = false
}
@@ -494,163 +259,10 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
sendUserToast(`Failed to save workspace AI prompt: ${err}`, true)
}
}
/** The first line of a block, for its row. */
function preview(text: string): string | undefined {
return text.trim().split('\n')[0] || undefined
}
</script>
<svelte:window onkeydown={onKeydown} />
<!-- The list and the detail page are levels of one panel, so moving between them slides
rather than cuts. Warmed once this panel is on screen: the detail page carries a Monaco
instance, and building it on the first click lands that work inside the transition. -->
<PagedContent
warm={active}
class="grow min-h-0"
current={showingDetail ? 'detail' : 'list'}
onNavigate={active ? navigate : undefined}
pages={[
{ key: 'list', content: listPage },
{ key: 'detail', content: detailPage }
]}
/>
{#snippet listPage()}
<!-- Stable gutter: folding a folder can take the list under the scrollable height, and
every row would otherwise jump sideways as the scrollbar came and went. -->
<div class="grow min-h-0 overflow-y-auto pr-2" style="scrollbar-gutter: stable;">
<Section
label="Instructions"
description="What the assistant follows on top of its own prompt. The workspace's and yours are in every system prompt; a folder's are in it while the session works in that folder, and otherwise reach it the first time it works on an item there."
>
{#snippet action()}
<div class="flex items-center gap-2 shrink-0">
{#if isAdmin}
<Button
href={aiSettingsHref}
target="_blank"
variant="subtle"
unifiedSize="sm"
endIcon={{ icon: ExternalLink }}
>
AI settings
</Button>
{/if}
<Button
variant="accent"
unifiedSize="sm"
startIcon={{ icon: Plus }}
disabled={saving || forkPending}
onClick={openNew}
>
New folder instructions
</Button>
</div>
{/snippet}
<div class="flex flex-col gap-0.5">
{@render block('workspace')}
{@render block('user')}
{#each tree as node (node.path)}
{@render folder(node, true)}
{/each}
</div>
{#if folderLoadError}
<div class="text-xs text-red-600 dark:text-red-400 px-2 pt-2">
Failed to load folder instructions: {folderLoadError}
</div>
{:else if !loading && folderRows.length === 0}
<p class="text-2xs text-hint px-2 pt-2">
No folder has instructions yet. A folder's instructions are followed for every item in it.
</p>
{/if}
</Section>
</div>
{/snippet}
{#snippet block(kind: 'workspace' | 'user')}
{@const saved = kind === 'workspace' ? workspaceSaved : userSaved}
{@const changed = kind === 'workspace' ? workspaceChanged : userChanged}
{#snippet icon()}
{#if kind === 'workspace'}
<Building2 size={16} class="text-tertiary" />
{:else}
<User size={16} class="text-tertiary" />
{/if}
{/snippet}
{#snippet title()}
<span class="truncate leading-5">{kind === 'workspace' ? 'Workspace' : 'You'}</span>
{/snippet}
{#snippet subtitle()}
{#if changed}
<span class="text-hint">Unsaved changes ·</span>
{/if}
{preview(saved) ?? (kind === 'workspace' ? `None set for ${ws}` : 'None set')}
{/snippet}
<ListRow {icon} {title} {subtitle} onClick={() => openBlock(kind)} />
{/snippet}
<!-- One folder and everything under it. Recursive: a path may name folders below the `u/x`
or `f/x` root it starts from. -->
{#snippet folder(node: SkillTreeNode<FolderInstructionRow>, root: boolean)}
<div>
<button
type="button"
class="w-full flex items-center gap-2 px-2 py-2 text-left rounded-md hover:bg-surface-hover"
aria-expanded={!collapsed[node.path]}
onclick={() => (collapsed[node.path] = !collapsed[node.path])}
>
{#if collapsed[node.path]}
<ChevronRight size={14} class="text-tertiary shrink-0" />
{:else}
<ChevronDown size={14} class="text-tertiary shrink-0" />
{/if}
{#if root && node.path.startsWith('u/')}
<User size={14} class="text-secondary shrink-0" />
{:else if root}
<Folder size={14} class="text-secondary shrink-0" />
{:else}
<FolderTree size={14} class="text-secondary shrink-0" />
{/if}
<!-- Explicitly normal: buttons carry a heavier weight the label would inherit. -->
<span class="text-xs font-normal text-emphasis truncate">{node.label}</span>
<span class="text-2xs text-secondary">{countSkills(node)}</span>
</button>
{#if !collapsed[node.path]}
<div class="pl-4 flex flex-col gap-0.5">
{#each node.children as child (child.path)}
{@render folder(child, false)}
{/each}
{#each node.skills as row (row.path)}
{@render instruction(row)}
{/each}
</div>
{/if}
</div>
{/snippet}
{#snippet instruction(row: FolderInstructionRow)}
{#snippet icon()}
<ScrollText size={16} class="text-tertiary" />
{/snippet}
{#snippet title()}
<span class="truncate leading-5">{row.name}</span>
{/snippet}
{#snippet subtitle()}
{#if folderChanged && detail?.kind === 'folder' && detail.row.path === row.path}
<span class="text-hint">Unsaved changes ·</span>
{/if}
{@const inScope = aiChatManager.workingScope?.roots?.find((r) => `${r}/`.startsWith(row.scope))}
{#if inScope}
<span class="text-accent">In the prompt while working in {inScope} ·</span>
{/if}
Followed for every item under {row.scope}
{/snippet}
<ListRow {icon} {title} {subtitle} onClick={() => openFolder(row)} />
{/snippet}
{#snippet field(p: { value: string; readOnly: boolean; onInput: (v: string) => void })}
<div class="flex flex-col gap-1">
<TextInput
@@ -665,7 +277,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
// Also while saving: the write spans two requests and its success path puts the
// submitted value back, so text typed in between would be swallowed. `load`
// keeps a newer draft instead, because it starts on its own and must not block
// someone who opened the block to type.
// someone who opened the tab to type.
readonly: p.readOnly || saving,
oninput: (e) => p.onInput(e.currentTarget.value)
}}
@@ -678,191 +290,68 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
</div>
{/snippet}
{#snippet detailPage()}
<!-- Same reserved gutter as the list, so the slide between the pages does not shift what
is under the cursor. -->
<div class="grow min-h-0 overflow-y-auto pr-2" style="scrollbar-gutter: stable;">
<!-- Sticky so the way back is always one click away, however far the page scrolls. -->
<div class="flex sticky top-0 z-10 bg-surface pb-1">
<Section
label="Instructions"
description="Text added to every system prompt in this workspace, on top of the assistant's own. Both blocks are sent, the workspace one first."
class="flex flex-col gap-4"
>
{#snippet action()}
<div class="flex items-center gap-2 shrink-0">
{#if isAdmin}
<Button
href={aiSettingsHref}
target="_blank"
variant="subtle"
unifiedSize="sm"
endIcon={{ icon: ExternalLink }}
>
AI settings
</Button>
{/if}
<Button
variant="subtle"
unifiedSize="xs"
startIcon={{ icon: ArrowLeft }}
btnClasses="text-secondary"
onClick={closeDetail}
variant="accent"
unifiedSize="sm"
disabled={!dirty || saving || loading}
onClick={save}
>
Instructions
Save
</Button>
</div>
{#if detail?.kind === 'workspace' || detail?.kind === 'user'}
{@const kind = detail.kind}
<Section
label={kind === 'workspace' ? 'Workspace instructions' : 'Your instructions'}
wrapperClass="mt-1"
class="flex flex-col gap-2"
>
{#snippet action()}
<Button
variant="accent"
unifiedSize="sm"
disabled={!pageChanged || saving || loading}
onClick={saveBlock}
>
Save
</Button>
{/snippet}
<Description>
{kind === 'workspace'
? `In every system prompt in ${ws}, for everyone.`
: 'Stored in this browser and sent in every workspace, so they follow you rather than the workspace.'}
</Description>
{#if kind === 'workspace'}
{#if workspaceReadOnly}
<Alert type="info" title="These are read-only for you" size="xs">
{readOnlyReason}
</Alert>
{/if}
{/snippet}
<Tabs values={['workspace', 'user']} bind:selected={tab}>
<Tab value="workspace" label="Workspace" icon={Building2} />
<Tab value="user" label="User (you)" icon={User} />
{#snippet content()}
<!-- The note belongs to the panel rather than to either tab: one element that
follows the selection, so switching tabs does not rebuild it and the space
under the tab row is the same on both. The wrapper carries no padding of its
own — `Tabs` renders the row and this content as two roots, so the Section's
`gap-4` is already the space between them. -->
<div class="flex flex-col gap-2">
<Description>{note}</Description>
{#if workspaceReadOnly && tab === 'workspace'}
<Alert type="info" title="These are read-only for you" size="xs">
{readOnlyReason}
</Alert>
{/if}
<!-- `alwaysMounted`: Save writes whichever half changed, including the tab that
is not on screen, so a field left with unsaved text has to go on holding it. -->
<TabContent value="workspace" alwaysMounted>
{@render field({
value: workspaceDraft,
readOnly: workspaceReadOnly,
onInput: (v) => (workspaceDraft = v)
})}
{:else}
{@render field({ value: userDraft, readOnly: false, onInput: (v) => (userDraft = v) })}
{/if}
</Section>
{/if}
<!-- Mounted whatever the page holds and only hidden: an `{#if}` would dispose Monaco on
every visit to the workspace or user block and rebuild it on the way back. -->
<div class={detail?.kind === 'folder' || detail?.kind === 'new' ? 'block' : 'hidden'}>
<Section
label={detail?.kind === 'folder' ? detail.row.path : 'New folder instructions'}
wrapperClass="mt-1"
headerClass="min-w-0 truncate pr-2"
>
{#snippet action()}
{#if detail?.kind === 'folder'}
<div class="flex justify-end shrink-0">
<ToggleButtonGroup bind:selected={folderMode}>
{#snippet children({ item })}
<ToggleButton value="view" label="View" icon={Eye} {item} small />
<ToggleButton
value="edit"
label="Edit"
icon={Pencil}
{item}
small
disabled={!detail?.row.canWrite || forkPending}
/>
{/snippet}
</ToggleButtonGroup>
</div>
{/if}
{/snippet}
<div class="w-full flex flex-col gap-3">
{#if detail?.kind === 'folder'}
<Description>
Followed for every item under {detail.row.scope}, delivered the first time the
assistant works on one of them.
</Description>
{/if}
<div class="{folderMode === 'view' ? 'block' : 'hidden'} {markdownProse.sm}">
<div class="border rounded-md p-3 overflow-auto space-y-2">
{#if folderContent.trim()}
<Markdown md={folderContent} plugins={[gfmPlugin()]} />
{:else}
<span class="text-xs text-hint">Empty.</span>
{/if}
</div>
</div>
<div class="{folderMode === 'edit' ? 'flex' : 'hidden'} flex-col gap-3">
{#if detail?.kind === 'new'}
<Label label="Path">
<span class="text-xs font-normal text-secondary">
The folder decides what these cover: every item under it, for everyone who can
read them.
</span>
{#key editorSeq}
<Path
bind:path={newPath}
bind:error={newPathError}
initialPath=""
fullNamePlaceholder="AGENTS"
kind="resource"
workspaceOverride={ws}
autofocus={false}
/>
{/key}
</Label>
{/if}
<div class="border border-border-light rounded-md overflow-hidden">
<SimpleEditor
bind:this={bodyEditor}
autoHeight
lang="markdown"
bind:code={folderContent}
fixedOverflowWidgets={false}
class="min-h-24"
/>
</div>
<div class="flex items-center justify-between gap-2">
<div>
{#if detail?.kind === 'folder'}
{@const row = detail.row}
<Button
variant="subtle"
unifiedSize="sm"
startIcon={{ icon: Trash2 }}
disabled={saving || !row.canWrite || forkPending}
onClick={() => (toDelete = row)}
>
Delete
</Button>
{/if}
</div>
<div class="flex items-center gap-2">
<Button
onClick={() => setFolderContent(folderOriginal)}
variant="subtle"
unifiedSize="sm"
startIcon={{ icon: RotateCcw }}
disabled={saving || !folderChanged}
>
Reset
</Button>
<Button
onClick={saveFolder}
variant="accent"
unifiedSize="sm"
startIcon={{ icon: detail?.kind === 'new' ? Plus : Pencil }}
disabled={saving ||
!folderChanged ||
(detail?.kind === 'new' && (!newPath || !!newPathError))}
>
{detail?.kind === 'new' ? 'Add instructions' : 'Save instructions'}
</Button>
</div>
</div>
</div>
</div>
</Section>
</div>
</div>
{/snippet}
<ConfirmationModal
open={toDelete !== undefined}
title="Delete folder instructions"
confirmationText="Delete"
onConfirmed={async () => {
const row = toDelete
toDelete = undefined
if (row) await removeFolder(row)
}}
onCanceled={() => (toDelete = undefined)}
>
<span class="text-xs text-primary">
This deletes the resource at <span class="font-semibold">{toDelete?.path}</span>, so the
assistant stops following it for everyone.
</span>
</ConfirmationModal>
</TabContent>
<TabContent value="user" alwaysMounted>
{@render field({
value: userDraft,
readOnly: false,
onInput: (v) => (userDraft = v)
})}
</TabContent>
</div>
{/snippet}
</Tabs>
</Section>
@@ -36,7 +36,6 @@ switch that decides whether this chat carries its tools.
import { getAiChatManager } from './aiChatManagerContext'
import { clearMcpToolsCache } from './global/mcpTools'
import { forgetMcpServerMarks } from '$lib/components/mcp/serverMark'
import { ownerRoot } from './workingScope'
let {
ws,
@@ -488,15 +487,7 @@ switch that decides whether this chat carries its tools.
{#snippet title()}
<span class="truncate leading-5">{server.path}</span>
{/snippet}
{@const scopeRoots = aiChatManager.workingScope?.roots}
{@const fromRoot = scopeRoots?.find((r) => ownerRoot(server.path) === r)}
{@const fromScope = !!fromRoot}
{#snippet subtitle()}
{#if fromRoot}
<span class="text-accent">From {fromRoot}, where this session works.</span>
{/if}
{server.description}
{/snippet}
{#snippet subtitle()}{server.description}{/snippet}
{#snippet trailing()}
<Toggle
size="xs"
@@ -527,7 +518,7 @@ switch that decides whether this chat carries its tools.
{icon}
{title}
{trailing}
subtitle={server.description || fromScope ? subtitle : undefined}
subtitle={server.description ? subtitle : undefined}
onClick={() => openServer(server)}
/>
{/each}
@@ -208,11 +208,6 @@ callers that already know which section they mean, such as the "+" menu's Manage
{#snippet headerLeft()}
<p class="pl-3 pt-1 text-xs text-secondary truncate">
What the assistant can see and use in this session.
{#if aiChatManager.workingScope?.roots?.length === 0}
No folder selected: every change asks.
{:else if aiChatManager.workingScope?.roots}
Working in <span class="font-mono">{aiChatManager.workingScope.label}</span>.
{/if}
</p>
{/snippet}
@@ -239,9 +234,9 @@ callers that already know which section they mean, such as the "+" menu's Manage
<div class="grow min-w-0 flex flex-col min-h-0">
<!-- Every section stays mounted while the modal is open: the sidebar badges
count what each one loaded, so hiding is display-only. Tools, Skills,
Instructions and MCP own their own scrolling — each is a list and a detail page
laid over each other — so only Files and Permissions scroll here. -->
count what each one loaded, so hiding is display-only. Tools, Skills and MCP
own their own scrolling — each is a list and a detail page laid over each
other — so only Instructions scrolls here. -->
<div class="{section === 'tools' ? 'flex' : 'hidden'} grow min-h-0 flex-col overflow-hidden">
<AssistantToolsSection
{tools}
@@ -261,9 +256,7 @@ callers that already know which section they mean, such as the "+" menu's Manage
/>
</div>
<div
class="{section === 'instructions'
? 'flex'
: 'hidden'} grow min-h-0 flex-col overflow-hidden"
class="{section === 'instructions' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2"
>
<AssistantInstructionsSection
{ws}
@@ -43,7 +43,6 @@ and the actions that create, edit, import and delete them.
import { useListHighlight } from '$lib/components/common/listRow/listHighlight.svelte'
import { getAiChatManager } from './aiChatManagerContext'
import { forgetSkill, isSkillEnabled, setSkillEnabled } from './skills/enabledSkills'
import { ownerRoot } from './workingScope'
import {
ambiguousSkillNames,
deleteSkillResource,
@@ -92,17 +91,6 @@ and the actions that create, edit, import and delete them.
const aiChatManager = getAiChatManager()
// While the session works in some folders, a skill saved in another one stays switched on here,
// as it is the user's own preference, but is off for the assistant, and the row says so. One
// saved in the folder itself is badged as coming from it.
function scopeNote(path: string): { off: boolean; root: string } | undefined {
const scope = aiChatManager.workingScope
if (!scope?.roots) return undefined
if (!scope.loadsSkill(path)) return { off: true, root: scope.label }
const root = ownerRoot(path)
return root && scope.roots.includes(root) ? { off: false, root } : undefined
}
// A session whose fork is still staged has no workspace of its own yet, so `ws`
// resolves to the PARENT. Authoring here would then edit the live parent, and a
// toggle would be stored under it and quietly stop applying the moment the first
@@ -877,7 +865,7 @@ What the assistant should do when this skill applies.
>
<Section
label="Skills"
description="Reusable instruction sets the assistant loads when they apply. Every skill in the workspace is on, except those saved in other folders while the session works in one; turning one off is personal to you and to this workspace."
description="Reusable instruction sets the assistant loads when they apply. Every skill in the workspace is on; turning one off is personal to you and to this workspace."
>
{#snippet action()}
<div class="flex items-center gap-2 shrink-0">
@@ -974,15 +962,7 @@ What the assistant should do when this skill applies.
{!grouped && ambiguous.has(skill.name) ? skill.path : skill.name}
</span>
{/snippet}
{@const note = scopeNote(skill.path)}
{#snippet subtitle()}
{#if note?.off}
<span class="text-hint">Off while working in {note.root}.</span>
{:else if note}
<span class="text-accent">From {note.root}, where this session works.</span>
{/if}
{skill.description}
{/snippet}
{#snippet subtitle()}{skill.description}{/snippet}
{#snippet trailing()}
<Toggle
size="xs"
@@ -1018,7 +998,7 @@ What the assistant should do when this skill applies.
id={entryDomId(skillKey(skill.path))}
highlighted={entryIndexByKey.get(skillKey(skill.path)) === highlight.index}
onMouseEnter={() => highlight.hovered(entryIndexByKey.get(skillKey(skill.path)) ?? -1)}
subtitle={skill.description || note ? subtitle : undefined}
subtitle={skill.description ? subtitle : undefined}
onClick={() => openSkill(skill)}
/>
{/snippet}
@@ -1,47 +0,0 @@
<!--
@component
The answer row of a change held outside the session's scope, laid out like a tool confirmation's
footer and placed where one goes. YOLO never answers it, and Stop leaves it unanswered.
-->
<script lang="ts">
import { Button } from '$lib/components/common'
import { twMerge } from 'tailwind-merge'
import { getChatViewHost } from './chatViewHost'
import type { ScopeDecision } from './workingScope'
let {
toolCallId,
path,
root,
scope,
verb,
class: className
}: {
toolCallId: string
path: string
root: string
scope: string
verb: string
class?: string
} = $props()
const chatHost = getChatViewHost()
function answer(decision: ScopeDecision) {
chatHost.handleScopeDecision(toolCallId, decision)
}
</script>
<!-- font-main: the tool cards around it are font-mono, which reads as bold on a button label. -->
<div class={twMerge('flex flex-col gap-2 font-main', className)}>
<p class="text-xs text-primary">
This would {verb} <span class="font-mono">{path}</span>, outside
<span class="font-mono">{scope}</span>.
</p>
<div class="flex flex-row flex-wrap items-center justify-end gap-2">
<Button variant="default" unifiedSize="sm" on:click={() => answer('add')}>
Allow writes in <span class="font-mono">{root}</span>
</Button>
<Button variant="accent" unifiedSize="sm" on:click={() => answer('once')}>Allow once</Button>
</div>
</div>
@@ -4,7 +4,6 @@
import ToolCodeDiffView from './ToolCodeDiffView.svelte'
import ToolPreviewCard from './ToolPreviewCard.svelte'
import ToolConfirmationFooter from './ToolConfirmationFooter.svelte'
import OutOfScopeFooter from './OutOfScopeFooter.svelte'
import { Check, XCircle } from 'lucide-svelte'
import {
diffIsWholeFile,
@@ -25,15 +24,8 @@
const isStreaming = $derived(Boolean(message.isStreamingArguments))
const hasDiff = $derived(Boolean(diff && (diff.before !== '' || diff.after !== '')))
const awaitingConfirmation = $derived(Boolean(message.isLoading && message.needsConfirmation))
const pendingOutOfScope = $derived(
message.isLoading && message.outOfScope && !message.outOfScope.decision
? message.outOfScope
: undefined
)
// Either answer row sits in the body, so the card stays open while one waits.
const awaitingAnswer = $derived(awaitingConfirmation || !!pendingOutOfScope)
// The card body is a bordered box: opened with nothing in it, it draws an empty line.
const hasBody = $derived(hasDiff || Boolean(message.error) || awaitingAnswer)
const hasBody = $derived(hasDiff || Boolean(message.error) || awaitingConfirmation)
// Keyed by call id: a bare flag would carry the expansion onto the next message that
// reuses this instance. An active or failed call opens by itself, and remains open
@@ -43,12 +35,9 @@
// the error.
const toggleKey = $derived(`${message.tool_call_id}:${message.error ? 'error' : ''}`)
let toggled = $state<{ id: string; open: boolean } | undefined>(undefined)
// A change the user declined is their decision, not a failure: it stays closed and neutral,
// or its diff reads as a change that happened.
const declined = $derived(Boolean(message.declinedByUser))
const opensByDefault = $derived(
Boolean(
(message.error && !declined) ||
message.error ||
(hasDiff &&
!diffIsWholeFile(message) &&
(message.isLoading || message.isQueued || message.isStreamingArguments))
@@ -61,7 +50,7 @@
})
// The Apply/Reject footer is inside the body, so a pending confirmation keeps it open.
const expanded = $derived(
awaitingAnswer ||
awaitingConfirmation ||
(hasBody && (toggled?.id === toggleKey ? toggled.open : opensByDefault))
)
const lines = $derived(diff && expanded ? toolDiffLines(diff, isStreaming) : undefined)
@@ -73,7 +62,7 @@
: undefined
)
const isRunning = $derived(Boolean(message.isLoading && !awaitingAnswer))
const isRunning = $derived(Boolean(message.isLoading && !message.needsConfirmation))
const showPreviewChip = $derived(
Boolean(!hidePreviewChip && message.previewCard && !message.isLoading && !message.error)
)
@@ -97,7 +86,7 @@
label={message.content}
{expanded}
onToggle={() => (toggled = { id: toggleKey, open: !expanded })}
toggleable={hasBody && !awaitingAnswer}
toggleable={hasBody && !awaitingConfirmation}
shimmer={isRunning}
class={message.isQueued && !message.error
? 'opacity-60 hover:opacity-100 transition-opacity'
@@ -118,21 +107,10 @@
confirmLabel="Apply"
confirmIcon={Check}
/>
{:else if pendingOutOfScope}
<OutOfScopeFooter
class="px-3 py-2 border-t border-border-light"
toolCallId={message.tool_call_id}
path={pendingOutOfScope.path}
root={pendingOutOfScope.root}
scope={pendingOutOfScope.scope}
verb={pendingOutOfScope.verb}
/>
{/if}
{#if message.error}
<div
class="px-3 py-2 text-2xs {declined
? 'text-secondary'
: 'text-red-600 dark:text-red-400'} whitespace-pre-wrap break-words {hasDiff
class="px-3 py-2 text-2xs text-red-600 dark:text-red-400 whitespace-pre-wrap break-words {hasDiff
? 'border-t border-border-light'
: ''}"
>
@@ -52,7 +52,6 @@
import WebSearchSourcesDisplay from './WebSearchSourcesDisplay.svelte'
import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte'
import McpServerIcon from '$lib/components/mcp/McpServerIcon.svelte'
import OutOfScopeFooter from './OutOfScopeFooter.svelte'
import { resolveMcpServerMark } from '$lib/components/mcp/serverMark'
interface Props {
@@ -124,14 +123,7 @@
// Executing right now, as opposed to queued behind another tool or waiting on
// the user — the only state that gets the shimmer.
const pendingOutOfScope = $derived(
message.isLoading && message.outOfScope && !message.outOfScope.decision
? message.outOfScope
: undefined
)
const isRunning = $derived(
Boolean(message.isLoading && !message.needsConfirmation && !pendingOutOfScope)
)
const isRunning = $derived(Boolean(message.isLoading && !message.needsConfirmation))
// An errored tool must be expandable even if it never opted into details,
// otherwise the error set on its status would be invisible.
@@ -146,7 +138,6 @@
let toggled = $state<{ id: string | undefined; open: boolean } | undefined>(undefined)
const isExpanded = $derived(
Boolean(message.isLoading && message.needsConfirmation) ||
!!pendingOutOfScope ||
(toggled?.id === message.tool_call_id
? toggled.open
: Boolean(
@@ -365,7 +356,7 @@
class={message.isQueued && !message.error
? 'opacity-60 hover:opacity-100 transition-opacity'
: ''}
headerClass={message.needsConfirmation || pendingOutOfScope ? 'opacity-80' : ''}
headerClass={message.needsConfirmation ? 'opacity-80' : ''}
labelClass={showPreviewChip ? 'truncate' : ''}
contentClass="space-y-3"
headerRight={showPreviewChip ? previewChip : message.jobId ? jobLink : undefined}
@@ -385,8 +376,8 @@
{/snippet}
<!-- Parameters Section - show if we have parameters, or if confirmation is needed (even with empty params) -->
{#if hasParameters || message.needsConfirmation || pendingOutOfScope}
<div class={message.needsConfirmation || pendingOutOfScope ? 'opacity-80' : ''}>
{#if hasParameters || message.needsConfirmation}
<div class={message.needsConfirmation ? 'opacity-80' : ''}>
<ToolContentDisplay
title="Parameters"
content={message.parameters}
@@ -406,14 +397,6 @@
confirmLabel={confirmAction.label}
confirmIcon={confirmAction.icon}
/>
{:else if pendingOutOfScope}
<OutOfScopeFooter
toolCallId={message.tool_call_id}
path={pendingOutOfScope.path}
root={pendingOutOfScope.root}
scope={pendingOutOfScope.scope}
verb={pendingOutOfScope.verb}
/>
<!-- Logs and Result - hide while streaming -->
{:else if !message.isStreamingArguments}
@@ -441,12 +424,3 @@
{/if}
</ChatCollapsibleCard>
{/if}
<!-- An exception the user made stays on the record: the card itself is gone once answered. -->
{#if message.outOfScope?.decision}
<p class="font-main text-2xs text-tertiary pl-1 pb-1">
{message.outOfScope.decision === 'once'
? `You allowed this ${message.outOfScope.verb} outside ${message.outOfScope.scope}.`
: `You allowed writes in ${message.outOfScope.root} for this session.`}
</p>
{/if}
@@ -1,176 +0,0 @@
<!--
@component
The composer's "Working in" picker: the folders, and the user's own space, this session's AI
changes items in. Several can be picked, and the menu stays open while they are; every one
picked is the whole workspace, folders created later included. Stays editable after the first
message; a change applies from the next turn.
-->
<script lang="ts">
import { Check, ChevronDown, Folder } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import MenuItem from '$lib/components/meltComponents/MenuItem.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import type { MenubarMenuElements } from '@melt-ui/svelte'
import { getAiChatManager } from './aiChatManagerContext'
import { useWorkingInOptions } from './workingInOptions.svelte'
import { scopeBadge, type ScopeOption } from './workingScope'
type MeltItem = MenubarMenuElements['item']
/** Past this many rows the menu gets a search field. */
const SEARCH_FROM = 8
let {
ws,
onlyWhenScoped = false
}: {
ws: string
/** For the folded composer, which keeps a chip only while the session is scoped: a
* boundary must stay in sight, the default need not. */
onlyWhenScoped?: boolean
} = $props()
const aiChatManager = getAiChatManager()
const scope = useWorkingInOptions(aiChatManager, () => ws)
let query = $state('')
const current = $derived(aiChatManager.workingIn)
const label = $derived(
!current
? 'All folders'
: current.length === 0
? 'No folders'
: current.length === 1
? current[0]
: `${current[0]} +${current.length - 1}`
)
const searchable = $derived(scope.options.length > SEARCH_FROM)
const shown = $derived(
searchable && query.trim()
? scope.options.filter((o) => o.root.toLowerCase().includes(query.trim().toLowerCase()))
: scope.options
)
const own = $derived(shown.filter((o) => o.root.startsWith('u/')))
const folders = $derived(shown.filter((o) => o.root.startsWith('f/')))
function picked(root: string): boolean {
return !current || current.includes(root)
}
/** Picking a root adds it to the scope or takes it out. With every listed root picked the
* session works in the whole workspace, so roots the menu does not list (a folder created
* later) stop asking too. */
function toggle(root: string) {
const all = scope.options.map((o) => o.root)
const roots = current ?? all
const next = roots.includes(root) ? roots.filter((r) => r !== root) : [...roots, root]
aiChatManager.setWorkingIn(all.every((r) => next.includes(r)) ? undefined : next)
}
const ROW_CLASS =
'w-full flex items-center gap-2 px-3 py-1.5 text-left text-xs text-primary font-normal hover:bg-surface-hover data-[highlighted]:bg-surface-hover rounded-sm transition-colors cursor-pointer'
const ACTION_CLASS =
'px-2 py-1 text-2xs text-secondary font-normal hover:bg-surface-hover data-[highlighted]:bg-surface-hover rounded-sm transition-colors cursor-pointer'
</script>
{#snippet sectionTitle(title: string)}
<p class="px-3 pt-1.5 pb-1 text-2xs uppercase tracking-wide text-secondary">{title}</p>
{/snippet}
{#snippet option(item: MeltItem, o: ScopeOption)}
{@const caption = [o.readOnly ? 'Read only' : '', scopeBadge(o)].filter(Boolean).join(' · ')}
<MenuItem {item} class={ROW_CLASS} onClick={() => toggle(o.root)}>
<div class="grow min-w-0">
<p class="truncate">{o.root}</p>
{#if caption}
<p class="text-2xs text-secondary">{caption}</p>
{/if}
</div>
{#if picked(o.root)}
<Check size={14} class="shrink-0 text-primary" />
{/if}
</MenuItem>
{/snippet}
{#if aiChatManager.supportsWorkingIn && !aiChatManager.useModeActive && (current || !onlyWhenScoped)}
<DropdownV2
customMenu
placement="top-start"
fixedHeight={false}
closeOnItemClick={false}
on:close={() => (query = '')}
>
{#snippet buttonReplacement()}
<Button
nonCaptureEvent
unifiedSize="2xs"
variant="subtle"
title="Working in: the AI creates and changes items only in these folders, and asks before changing anything elsewhere. It still reads the whole workspace."
startIcon={{ icon: Folder }}
endIcon={{ icon: ChevronDown }}
>
{label}
</Button>
{/snippet}
{#snippet menu({ item })}
<div
class="bg-surface-tertiary dark:border w-64 rounded-lg shadow-lg focus:outline-none py-1 flex flex-col max-h-[60vh]"
>
<div class="px-3 pt-1.5 pb-1">
<p class="text-xs font-semibold text-emphasis">Allow writes in</p>
<p class="text-2xs text-secondary">Writes anywhere else ask you first.</p>
</div>
{#if searchable}
<div class="px-3 pt-1 pb-1.5">
<TextInput
size="sm"
bind:value={query}
inputProps={{
placeholder: 'Search folders',
// Capture, not bubble: melt reads loose keys as typeahead before a delegated
// handler would run. Escape still reaches the menu to close it.
onkeydowncapture: (e) => {
if (e.key !== 'Escape') e.stopPropagation()
}
}}
/>
</div>
{/if}
<div class="flex items-center justify-end gap-1 px-2">
<MenuItem
{item}
class={ACTION_CLASS}
onClick={() => aiChatManager.setWorkingIn(undefined)}
>
Select all
</MenuItem>
<MenuItem {item} class={ACTION_CLASS} onClick={() => aiChatManager.setWorkingIn([])}>
Deselect all
</MenuItem>
</div>
<div class="overflow-y-auto min-h-0">
{#if own.length}
{@render sectionTitle('Your space')}
{#each own as o (o.root)}
{@render option(item, o)}
{/each}
{/if}
{#if folders.length}
{#if own.length}
<div class="my-1 border-t border-border-light"></div>
{/if}
{@render sectionTitle('Folders')}
{#each folders as o (o.root)}
{@render option(item, o)}
{/each}
{/if}
{#if !shown.length}
<p class="px-3 py-1.5 text-2xs text-secondary">No folder matches</p>
{/if}
</div>
</div>
{/snippet}
</DropdownV2>
{/if}
@@ -8,7 +8,6 @@ import type { AttachedBlob } from './blobUtils'
import type { AttachedImage } from './imageUtils'
import type { AttachedTextFile } from './textFileUtils'
import type { PasteAttachment } from './pasteTokens'
import type { ScopeDecision } from './workingScope'
import type { AttachedFilesStore } from './files/attachedFiles.svelte'
import type { SessionArtifactsStore } from './artifacts/artifactsState.svelte'
import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
@@ -111,7 +110,6 @@ export interface ChatViewHost {
) => void | Promise<void>
handleUserQuestionAnswer: (toolId: string, choices: string[]) => boolean
handleToolConfirmation: (toolId: string, confirmed: boolean) => void
handleScopeDecision: (toolId: string, decision: ScopeDecision) => void
/** A tool is waiting on a run form the user is filling in. Escape belongs to that form
* then, not to the turn — see AIChatDisplay's window handler. */
readonly hasPendingRunForm: boolean
@@ -1,8 +1,4 @@
import { get } from 'svelte/store'
import { ResourceService, type ListableResource } from '$lib/gen'
import { canEditItem } from '$lib/editRights'
import { capabilitiesIn } from '$lib/roleCapabilities'
import { userWorkspaces, type UserExt } from '$lib/stores'
import { ResourceService } from '$lib/gen'
import {
folderInstructionScope,
folderInstructionsOpeningTag as openingTag,
@@ -35,12 +31,14 @@ const PAGE_SIZE = 100
/** Guard against a paging bug looping forever, not a product cap. */
const MAX_PAGES = 20
async function listInstructionResources(
/** Every folder instruction of `resourceType` the user can read in the workspace. Read
* access is the resource's own ACL, so a folder's instructions reach exactly who can see them. */
export async function listFolderInstructions(
workspace: string,
resourceType: string
): Promise<ListableResource[]> {
resourceType: string = FOLDER_INSTRUCTIONS_RESOURCE_TYPE
): Promise<FolderInstruction[]> {
if (!workspace) return []
const rows: ListableResource[] = []
const rows: FolderInstruction[] = []
for (let page = 1; page <= MAX_PAGES; page++) {
const resources = await ResourceService.listResource({
workspace,
@@ -48,64 +46,12 @@ async function listInstructionResources(
page,
perPage: PAGE_SIZE
})
rows.push(...resources)
rows.push(...resources.map((r) => ({ path: r.path, scope: folderInstructionScope(r.path) })))
if (resources.length < PAGE_SIZE) break
}
return rows
}
/** Every folder instruction of `resourceType` the user can read in the workspace. Read
* access is the resource's own ACL, so a folder's instructions reach exactly who can see them. */
export async function listFolderInstructions(
workspace: string,
resourceType: string = FOLDER_INSTRUCTIONS_RESOURCE_TYPE
): Promise<FolderInstruction[]> {
const resources = await listInstructionResources(workspace, resourceType)
return resources.map((r) => ({ path: r.path, scope: folderInstructionScope(r.path) }))
}
/** A folder instruction as Assistant settings lists it. `name` is the basename, which the
* folder tree shows under the folder that holds it. */
export type FolderInstructionRow = FolderInstruction & { name: string; canWrite: boolean }
/** `user` is the account the workspace is browsed as: it decides which rows offer Edit. */
export async function listFolderInstructionRows(
workspace: string,
user: UserExt | undefined
): Promise<FolderInstructionRow[]> {
const caps = capabilitiesIn(
user,
get(userWorkspaces).find((w) => w.id === workspace)
)
const resources = await listInstructionResources(workspace, FOLDER_INSTRUCTIONS_RESOURCE_TYPE)
return resources.map((r) => ({
path: r.path,
scope: folderInstructionScope(r.path),
name: r.path.split('/').pop() ?? r.path,
canWrite: canEditItem('resource', r.path, r.extra_perms, user, caps)
}))
}
export async function saveFolderInstruction(
workspace: string,
path: string,
content: string,
{ create = false }: { create?: boolean } = {}
): Promise<void> {
if (create) {
await ResourceService.createResource({
workspace,
requestBody: {
path,
value: { content },
resource_type: FOLDER_INSTRUCTIONS_RESOURCE_TYPE
}
})
} else {
await ResourceService.updateResource({ workspace, path, requestBody: { value: { content } } })
}
}
/** Workspace paths a tool call names: every string argument called `path` or
* `*_path` that is a `u/`, `f/` or `g/` path, nested ones included — a trigger's target
* sits in `config.path`, and missing it would let that write through unheld. */
@@ -132,8 +78,6 @@ export function workspacePathsInArgs(args: unknown, depth = 0): string[] {
export type FolderInstructionsContext = {
list: () => readonly FolderInstruction[]
deliveredBy: Map<string, FolderInstructionsDelivery>
/** The ones the system prompt carries, the scoped folder's: never delivered again. */
inPrompt?: () => readonly string[]
}
/** Keyed by workspace too: the chat keeps its conversation across a switch of
@@ -184,10 +128,7 @@ export async function pendingFolderInstructions(
const paths = workspacePathsInArgs(args)
if (paths.length === 0) return undefined
const { read, thisBatch } = deliveredIn(ctx, messages, workspace)
const inPrompt = new Set(ctx.inPrompt?.() ?? [])
const pending = instructionsCovering(ctx.list(), paths).filter(
(i) => !read.has(i.path) && !inPrompt.has(i.path)
)
const pending = instructionsCovering(ctx.list(), paths).filter((i) => !read.has(i.path))
const inBatch = pending.filter((i) => thisBatch.has(i.path))
const blocks = (
await Promise.all(
@@ -3261,8 +3261,7 @@ export const readSkillTool: SessionTool<{}> = {
const isSkill = (await listSkillResources(workspace)).skills.some(
(s) => s.path === parsed.path
)
const suspended = toolCallbacks.workingScope?.scope()?.loadsSkill(parsed.path) === false
if (!isSkill || !isSkillEnabled(workspace, parsed.path) || suspended) {
if (!isSkill || !isSkillEnabled(workspace, parsed.path)) {
toolCallbacks.setToolStatus(toolId, { content: `Skill "${name}" is not available` })
return `"${parsed.path}" is not one of the skills available to this chat. Only the paths listed under "Skills" in the system prompt can be read.`
}
@@ -4279,26 +4278,13 @@ export const globalTools: SessionTool<{}>[] = [
).filter((row) => itemMatches(row, parsed.query))
const byKey = new Map<string, WorkspaceItem>()
// Scoped, its folders are the default, one listing each; an explicit path_prefix, ""
// included, overrides them.
const scopeRoots = toolCallbacks.workingScope?.scope()?.roots
const scopedByDefault = parsed.path_prefix === undefined && !!scopeRoots?.length
const prefixes: (string | undefined)[] = scopedByDefault
? scopeRoots!.map((r) => `${r}/`)
: [parsed.path_prefix || undefined]
const workspaceItems = (
await Promise.all(
prefixes.map((prefix) =>
listWorkspaceItems(
types,
workspace,
prefix,
Math.min(limit, MAX_LIST_LIMIT),
parsed.page
)
)
)
).flat()
const workspaceItems = await listWorkspaceItems(
types,
workspace,
parsed.path_prefix,
Math.min(limit, MAX_LIST_LIMIT),
parsed.page
)
for (const item of workspaceItems) {
byKey.set(getWorkspaceItemKey(item.type, item.path, item.triggerKind), item)
}
@@ -4310,7 +4296,7 @@ export const globalTools: SessionTool<{}>[] = [
// (it filters before the cap; query filters after).
if ((parsed.page ?? 1) === 1) {
const draftCountByType = new Map<string, number>()
const narrowing = prefixes.filter((p): p is string => !!p)
const prefix = parsed.path_prefix
for (const draft of await listGlobalDrafts(workspace)) {
if (!types.includes(draft.type)) continue
// A draft's staged name is often not where it is stored: the editor parks
@@ -4318,10 +4304,7 @@ export const globalTools: SessionTool<{}>[] = [
// rename stages the new name over the old path. The server drops
// draft-only rows under any narrowing filter, leaving this pass their
// only source, so either name has to satisfy the prefix.
if (
narrowing.length &&
!narrowing.some((p) => draft.path.startsWith(p) || draft.draftPath?.startsWith(p))
)
if (prefix && !draft.path.startsWith(prefix) && !draft.draftPath?.startsWith(prefix))
continue
const count = draftCountByType.get(draft.type) ?? 0
if (count >= limit) continue
@@ -4345,10 +4328,7 @@ export const globalTools: SessionTool<{}>[] = [
toolCallbacks.setToolStatus(toolId, {
content: `Listed ${results.length} workspace item(s)`
})
const listed = JSON.stringify(results, null, 2)
return scopedByDefault
? `Items under ${prefixes.join(', ')}, where this session works. Pass path_prefix "" for the whole workspace.\n${listed}`
: listed
return JSON.stringify(results, null, 2)
}
},
{
@@ -5296,7 +5276,6 @@ export const globalTools: SessionTool<{}>[] = [
def: createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION),
// A read-only session holds no draft capability, so the schema below offers it viewers.
readOnlySafe: true,
viewOnly: true,
// Withhold the editors a session cannot save, so the model never offers the user a
// panel it would not get.
schemaFor: async (helpers) => {
@@ -14,7 +14,6 @@ import {
import { createMcpTools } from './mcpTools'
import { getPipelinePromptSection, pipelineTools } from '../pipeline/core'
import { getFolderInstructionsPromptSection, type FolderInstruction } from '../folderInstructions'
import type { WorkingScope } from '../workingScope'
// Derived, not retyped: an option added to prepareGlobalSystemMessage is reachable
// here at once. Hand-listing the four would compile fine while leaving the new one
@@ -25,9 +24,6 @@ export type GlobalAssemblyOpts = NonNullable<Parameters<typeof prepareGlobalSyst
/** Folders of the open pipeline editors; the pipeline tools and prompt come with any. */
pipelineFolders?: readonly string[]
folderInstructions?: readonly FolderInstruction[]
workingScope?: WorkingScope
/** The scoped folder's instructions, formatted. */
scopeInstructions?: string
}
export function assembleGlobalSystemMessage(
@@ -36,7 +32,6 @@ export function assembleGlobalSystemMessage(
): ChatCompletionSystemMessageParam {
const systemMessage = prepareGlobalSystemMessage(instructions, opts)
systemMessage.content += getFolderInstructionsPromptSection(opts.folderInstructions ?? [])
systemMessage.content += opts.workingScope?.promptSection(opts.scopeInstructions ?? '') ?? ''
if (opts.sessionContext) {
systemMessage.content += getSessionContextPromptSection(opts.sessionContext, opts.access)
}
@@ -61,7 +61,6 @@ export function readOnlyChatViewHost(options: {
restartGeneration: noop,
handleUserQuestionAnswer: () => false,
handleToolConfirmation: noop,
handleScopeDecision: noop,
hasPendingRunForm: false,
isRunFormPending: () => false,
@@ -224,8 +224,7 @@ describe('processToolCall', () => {
{ path: 'f/other/AGENTS', scope: 'f/other/' },
{ path: 'g/ops/AGENTS', scope: 'g/ops/' }
],
deliveredBy: new Map<string, { workspace: string; paths: readonly string[] }>(),
inPrompt: undefined as (() => string[]) | undefined
deliveredBy: new Map<string, { workspace: string; paths: readonly string[] }>()
}
const messages: any[] = []
const call = async (
@@ -308,59 +307,6 @@ describe('processToolCall', () => {
messages.push({ role: 'tool', tool_call_id: 'stopped', content: 'Interrupted' })
turn()
expect(await call('c7', 'read_item', 'f/billing/y')).toContain('body of f/billing/AGENTS')
// The scoped folder's instructions are in the system prompt: never delivered on touch.
messages.splice(0)
turn()
folderInstructions.inPrompt = () => ['f/other/AGENTS']
expect(await call('p1', 'write_item', 'f/other/x')).toBe('write ok')
})
it('stops a change outside the scope on the user, whatever YOLO says, and never a run', async () => {
const { createToolDef, processToolCall } = await import('./shared')
const { WorkingScope, scopeAllowedNote, scopeStoppedResult } = await import('./workingScope')
const write = vi.fn(async () => 'write ok')
const run = vi.fn(async () => 'run ok')
const tools = [
{ def: createToolDef(z.object({}), 'write_item', 'Write'), fn: write },
{ def: createToolDef(z.object({}), 'run_script', 'Run'), fn: run }
]
let decision: 'once' | 'add' | undefined = undefined
const requestDecision = vi.fn(async () => decision)
const add = vi.fn()
const scope = new WorkingScope(['f/crm'], { username: 'alice', folders: ['analytics'] })
const call = (path: string, name = 'write_item') =>
processToolCall({
tools,
toolCall: {
id: `${name}:${path}`,
type: 'function',
function: { name, arguments: JSON.stringify({ path }) }
},
helpers: {},
workspace: 'test-workspace',
toolCallbacks: {
setToolStatus: vi.fn(),
removeToolStatus: vi.fn(),
shouldAutoAcceptToolConfirmations: () => true,
workingScope: { scope: () => scope, requestDecision, add, recordWrite: vi.fn() }
}
}).then((m) => m.content)
expect(await call('f/crm/x')).toBe('write ok')
expect(await call('f/analytics/x', 'run_script')).toBe('run ok')
expect(requestDecision).not.toHaveBeenCalled()
expect(await call('f/analytics/x')).toBe(scopeStoppedResult('f/analytics/x', 'f/crm'))
expect(write).toHaveBeenCalledTimes(1)
decision = 'once'
expect(await call('f/analytics/y')).toBe(
`write ok\n\n${scopeAllowedNote('f/analytics/y', 'f/analytics', 'f/crm', 'once')}`
)
decision = 'add'
await call('f/analytics/z')
expect(add).toHaveBeenCalledWith('f/analytics')
})
it('returns pre-confirmation validation errors without asking for confirmation', async () => {
@@ -64,16 +64,6 @@ import { logFeatureUsage, logHubScriptPick } from '$lib/utils/featureUsage'
import { forLater } from '$lib/forLater'
import { scriptLangToEditorLang } from '$lib/scripts'
import { getCurrentModel } from '$lib/aiStore'
import {
isRunTool,
ownerRoot,
scopeAllowedNote,
scopeStoppedResult,
scopeVerb,
writtenPaths,
type ScopeDecision,
type WorkingScope
} from './workingScope'
import type { editor as meditor } from 'monaco-editor'
import { pendingFolderInstructions, type FolderInstructionsContext } from './folderInstructions'
import type { WebSearchSource } from './webSearchResult'
@@ -513,8 +503,6 @@ export type UserDisplayMessage = BaseDisplayMessage & {
// The client authored this turn itself (background-job auto-resume), not the
// user — ArrowUp recall must skip it.
synthetic?: boolean
// The scope the turn was sent in, `null` for the whole workspace; absent outside sessions.
workingIn?: string[] | null
}
export type CreatedResourceTriggerKind =
@@ -729,17 +717,6 @@ export type ToolDisplayMessage = {
blockedByPlanMode?: boolean
/** Held back until the model has read the folder instructions it was handed. */
heldForFolderInstructions?: boolean
/** A change or run in a folder that is not a working folder, stopped for the user to allow.
* `decision` is set once they answer. */
/** `scope` is the scope as copy reads it: `f/a` or `f/a and f/b`. */
outOfScope?: {
path: string
/** The owner root of `path`, which "Allow writes in" adds. */
root: string
scope: string
verb: string
decision?: ScopeDecision
}
/** The user declined: the reject button, a Stop, or a posture switch. Set only there, so
* a decision is distinguishable from every other way a call errors. */
declinedByUser?: boolean
@@ -852,10 +829,7 @@ export function pendingUserActionDetail(
if (isActiveRunForm(message)) {
return { action: 'confirmation', toolCallId: message.tool_call_id }
}
if (
(message.needsConfirmation || (message.outOfScope && !message.outOfScope.decision)) &&
message.isLoading
) {
if (message.needsConfirmation && message.isLoading) {
return { action: 'confirmation', toolCallId: message.tool_call_id }
}
}
@@ -1158,58 +1132,6 @@ export async function processToolCall<T>({
}
}
// Not a confirmation: YOLO never answers it, since the scope is a boundary the user set.
// Runs are the autonomy setting's alone. After the instructions hold, which sends the
// call back for a retry: asked before it, the user would answer twice.
const workingScope = toolCallbacks.workingScope
const writes =
!!tool &&
tool.planModeSafe !== true &&
!tool.viewOnly &&
!isRunTool(tool.def.function.name)
const scope = writes ? workingScope?.scope() : undefined
const outsidePath = scope?.outsidePath(args)
let scopeNote = ''
if (outsidePath && scope?.roots && workingScope && tool) {
const outOfScope = {
path: outsidePath,
// Always set: a path no owner root covers is never outside a scope.
root: ownerRoot(outsidePath) ?? outsidePath,
scope: scope.label,
verb: scopeVerb(tool.def.function.name)
}
toolCallbacks.setToolStatus(toolCall.id, {
parameters: args,
isLoading: true,
isQueued: false,
isStreamingArguments: false,
needsConfirmation: false,
outOfScope,
showDetails: tool.showDetails,
autoCollapseDetails: tool.autoCollapseDetails
})
const decision = await workingScope.requestDecision(toolCall.id)
if (!decision) {
logToolOutcome('declined')
toolCallbacks.setToolStatus(toolCall.id, {
content: `Stopped: ${outsidePath} is outside ${scope.label}`,
isLoading: false,
error: 'Nothing was changed.',
declinedByUser: true
})
return {
role: 'tool' as const,
tool_call_id: toolCall.id,
content: scopeStoppedResult(outsidePath, scope.label)
}
}
toolCallbacks.setToolStatus(toolCall.id, { outOfScope: { ...outOfScope, decision } })
if (decision === 'add') workingScope.add(outOfScope.root)
scopeNote = scopeAllowedNote(outsidePath, outOfScope.root, scope.label, decision)
const postDecisionBlock = planModeBlock() ?? withdrawnBlock()
if (postDecisionBlock) return postDecisionBlock
}
const requiresConfirmation = tool?.requiresConfirmation === true
// By name: skipping the wait is itself an answer on the user's behalf, and one tool
// must not be answered for.
@@ -1298,7 +1220,6 @@ export async function processToolCall<T>({
toolId: toolCall.id
})
logToolOutcome(settledInsideTool ?? 'ok')
if (writes && !settledInsideTool) workingScope?.recordWrite(writtenPaths(args))
toolCallbacks.setToolStatus(toolCall.id, {
isLoading: false,
isStreamingArguments: false
@@ -1317,7 +1238,7 @@ export async function processToolCall<T>({
const toAdd = {
role: 'tool' as const,
tool_call_id: toolCall.id,
content: [result, scopeNote, folderInstructions?.text].filter(Boolean).join('\n\n')
content: folderInstructions ? `${result}\n\n${folderInstructions.text}` : result
}
return toAdd
} catch (err) {
@@ -1397,9 +1318,6 @@ export interface Tool<T> {
schemaFor?: (helpers: any) => Promise<ChatCompletionFunctionTool>
/** Safe to run while plan mode is active. Absence fails closed. */
planModeSafe?: boolean
/** Shows an item without changing or running it, though not `planModeSafe`: working
* folders never hold it, so the AI can show what it reads in any folder. */
viewOnly?: boolean
/** The arguments a plan-mode-safe tool still refuses while the posture holds — for a tool
* that is admissible in general but not on every target. Consulted only once `planModeSafe`
* is true. */
@@ -1565,16 +1483,6 @@ export interface ToolCallbacks {
onReasoningStart?: () => void
requestConfirmation?: (toolId: string, toolName?: string) => Promise<boolean>
shouldAutoAcceptToolConfirmations?: (toolName?: string) => boolean
/** The session's scope. Wired by session chats only. */
workingScope?: {
scope: () => WorkingScope | undefined
/** Parks the call on the card until the user answers; a Stop resolves undefined. */
requestDecision: (toolId: string) => Promise<ScopeDecision | undefined>
/** Allows writes in one more root, the running turn included. */
add: (root: string) => void
/** Counts a write that went through, for the folders-written counter. */
recordWrite: (paths: readonly string[]) => void
}
isPlanModeActive?: () => boolean
onToolBlockedByPlanMode?: () => void
/** Whether the session has stopped shipping this tool since the call was made, as a switch to
@@ -79,16 +79,6 @@ describe('groupToolRuns', () => {
tool('read_flow_module_code', flow)
])
).toEqual([0, 1, { explore: [2, 3] }])
expect(
shape([
tool('patch_flow_json', flow),
tool('patch_flow_json', flow, {
isLoading: true,
outOfScope: { path: 'f/a/x', root: 'f/a', scope: 'f/b', verb: 'edit' }
}),
tool('patch_flow_json', flow)
])
).toEqual([0, 1, 2])
expect(
shape([
tool('patch_flow_json', flow),
@@ -114,7 +114,6 @@ function groupableCall(message: DisplayMessage): ToolDisplayMessage | undefined
// row with its own card (run, question, diff, image, sources) is the content itself; a call
// held for folder instructions never ran, so it is not a change or a lookup.
if (message.needsConfirmation || message.blockedByPlanMode) return undefined
if (message.outOfScope && !message.outOfScope.decision) return undefined
if (message.heldForFolderInstructions) return undefined
if (message.runForm || message.inspectedRun || message.userQuestion) return undefined
// An app edit's diff covers one file of many, so it stays a row inside the app's group.
@@ -1,36 +0,0 @@
import { resource } from 'runed'
import { FolderService } from '$lib/gen'
import type { AIChatManager } from './AIChatManager.svelte'
import { scopeOptions, type ScopeOption } from './workingScope'
/** The roots the chat's picker offers, read live from its manager, for the workspace the
* session acts on. */
export function useWorkingInOptions(
manager: AIChatManager,
workspace: () => string | undefined
): { readonly options: ScopeOption[] } {
const folders = resource(workspace, async (ws) => {
if (!ws) return []
// The send path loads these; a picker opened before the first send needs them for the
// user's own row and the badges. Not mid-turn: a refresh would invalidate the send's
// own, as AssistantSettingsModal's refresh explains.
if (!manager.loading && !manager.sendInFlight) {
void manager.refreshGlobalIdentity()
void manager.refreshGlobalFolderInstructions()
}
const names = await FolderService.listFolderNames({ workspace: ws })
// "Acting on" can move an unsent session to a workspace without some chosen folders:
// they drop out, and with none left the session works in the whole workspace.
const roots = manager.workingIn
const kept = roots?.filter((r) => !r.startsWith('f/') || names.includes(r.slice(2)))
if (roots && kept && kept.length < roots.length && manager.messages.length === 0) {
if (ws === workspace()) manager.setWorkingIn(kept.length ? kept : undefined, { fallback: true })
}
return names
})
return {
get options() {
return scopeOptions(folders.current ?? [], manager.scopeIdentity, manager.scopeResources)
}
}
}
@@ -1,42 +0,0 @@
import { describe, expect, it } from 'vitest'
import { WorkingScope } from './workingScope'
const alice = { username: 'alice', folders: ['crm', 'crm_analytics'] }
describe('WorkingScope.outsidePath', () => {
const scope = new WorkingScope(['f/crm'], alice)
it('names a write outside the scope, a trigger request included', () => {
expect(scope.outsidePath({ path: 'f/crm_analytics/weekly' })).toBe('f/crm_analytics/weekly')
expect(scope.outsidePath({ kind: 'http', config: { path: 'f/ops/hook' } })).toBe('f/ops/hook')
})
it('lets through writes inside it, paths in a payload, and the runnable a schedule runs', () => {
expect(scope.outsidePath({ path: 'f/crm/sync' })).toBeUndefined()
expect(scope.outsidePath({ path: 'f/crm/app', value: { path: 'f/ops/x' } })).toBeUndefined()
expect(scope.outsidePath({ path: 'f/crm/daily', script_path: 'f/shared/job' })).toBeUndefined()
})
it('lets through a write in any folder of a scope of several', () => {
const several = new WorkingScope(['f/crm', 'f/ops'], alice)
expect(several.outsidePath({ path: 'f/ops/job' })).toBeUndefined()
expect(several.outsidePath({ path: 'f/billing/x' })).toBe('f/billing/x')
})
it('names every write when no folder is selected, the user space included', () => {
expect(new WorkingScope([], alice).outsidePath({ path: 'u/alice/x' })).toBe('u/alice/x')
})
it('names nothing for the whole workspace', () => {
expect(new WorkingScope(undefined, alice).outsidePath({ path: 'u/bob/x' })).toBeUndefined()
})
})
describe('WorkingScope.loadsSkill', () => {
it("suspends other folders' skills and keeps the user's own space on", () => {
const scope = new WorkingScope(['f/crm'], alice)
expect(scope.loadsSkill('f/crm/tone')).toBe(true)
expect(scope.loadsSkill('u/alice/style')).toBe(true)
expect(scope.loadsSkill('f/marketing/tone')).toBe(false)
})
})
@@ -1,250 +0,0 @@
import { logFeatureUsage } from '$lib/utils/featureUsage'
/**
* Working in: the owner roots, `f/<folder>` or `u/<user>`, a session's AI changes items in, or
* the whole workspace. A guardrail against the AI's mistakes, not a permission: reads stay
* open, runs follow the autonomy setting, and a change outside the scope stops on a card the
* user answers, YOLO included.
*/
const ROOT = /^([fu])\/([^/]+)(?:\/|$)/
/** The owner root a workspace path lives under, or undefined for a path outside `f/` and
* `u/` (a hub path, a group), which no scope covers. */
export function ownerRoot(path: string): string | undefined {
const match = ROOT.exec(path.replace(/^\$(?:res|var):/, '').replace(/^\/+/, ''))
return match ? `${match[1]}/${match[2]}` : undefined
}
/** The scope a session opened from an item starts in: its folder, for an item under `f/`. */
export function presetScopeFor(path: string | undefined): string[] | undefined {
const root = path ? ownerRoot(path) : undefined
return root?.startsWith('f/') ? [root] : undefined
}
/** How a scope reads in copy: `f/a`, `f/a and f/b`, `f/a, f/b and f/c`. */
export function scopeLabel(roots: readonly string[]): string {
return roots.length < 2
? (roots[0] ?? '')
: `${roots.slice(0, -1).join(', ')} and ${roots[roots.length - 1]}`
}
export type WorkingScopeIdentity = {
username: string
is_admin?: boolean
/** The folders the user can write. */
folders?: string[]
}
/** Argument names that carry the path a call writes. */
const PATH_ARGUMENTS = ['path', 'app_path', 'resource_path']
/** Bags carried through to somewhere else — a runnable's arguments, a resource's value. A
* `path` inside one is the payload's, not a workspace path. */
const OPAQUE_ARGUMENTS = ['args', 'arguments', 'staticInputs', 'value']
/** The one nested bag read: `write_trigger` takes its whole request inside `config`. Elsewhere
* a nested path is a reference the call does not write (the script an app runnable calls). */
const REQUEST_BAG = 'config'
/** The workspace paths a call writes. */
export function writtenPaths(args: unknown): string[] {
const paths: string[] = []
const visit = (candidate: unknown, depth: number, parentKey?: string) => {
if (!candidate || typeof candidate !== 'object') return
for (const [key, child] of Object.entries(candidate)) {
if (
typeof child === 'string' &&
PATH_ARGUMENTS.includes(key) &&
(depth === 0 || parentKey === REQUEST_BAG)
) {
paths.push(child)
} else if (typeof child === 'object' && !OPAQUE_ARGUMENTS.includes(key)) {
visit(child, depth + 1, key)
}
}
}
visit(args, 0)
return [...new Set(paths)]
}
/** `run_script`, `test_run_step`, `test_pipeline_node`…: every tool that runs code is named so,
* and runs are the autonomy setting's to govern, in scope or not. */
const RUN_TOOL = /^(run|test)_/
export function isRunTool(toolName: string): boolean {
return RUN_TOOL.test(toolName)
}
/** The verb the block row uses for a call. */
export function scopeVerb(toolName: string): string {
if (toolName.startsWith('delete_')) return 'delete'
if (toolName.startsWith('deploy_')) return 'deploy'
if (toolName.startsWith('create_') || toolName.startsWith('init_')) return 'create'
return 'edit'
}
export class WorkingScope {
constructor(
/** The roots worked in, undefined for the whole workspace. Empty: none, so every change
* asks. */
readonly roots: readonly string[] | undefined,
readonly identity: WorkingScopeIdentity | undefined
) {}
/** The scope in copy, empty for the whole workspace. */
get label(): string {
if (!this.roots) return ''
return this.roots.length ? scopeLabel(this.roots) : 'the selected folders'
}
includes(path: string): boolean {
const root = ownerRoot(path)
return !root || !this.roots || this.roots.includes(root)
}
/** Whether a skill saved at `path` is loaded: those in other folders are suspended while
* scoped, the user's own space stays on. */
loadsSkill(path: string): boolean {
return this.includes(path) || ownerRoot(path) === `u/${this.identity?.username}`
}
/** The first path a write with these arguments lands on outside the scope. */
outsidePath(args: unknown): string | undefined {
if (!this.roots) return undefined
return writtenPaths(args).find((p) => !this.includes(p))
}
/** The system prompt section, empty for the whole workspace. `instructions` is the scoped
* folder's own instructions, already formatted. */
promptSection(instructions: string): string {
if (!this.roots) return ''
if (!this.roots.length) {
return `\n\nWORKING IN NO FOLDER:
The user selected no folder for this session. A create, edit, move, delete or deploy does not run: Windmill asks the user, who can allow it once or allow writes in that folder. When the task needs one, make the call directly rather than asking first. Read anything you need, and runs are not limited.`
}
const dirs = this.roots.map((r) => `\`${r}/\``).join(', ')
const one = this.roots.length === 1
return `\n\nWORKING IN ${dirs}:
The user scoped this session to ${dirs}.
- Create new items under ${one ? dirs : 'one of them (the one the task belongs to)'}, and change only items there. A create, edit, move, delete or deploy elsewhere does not run: Windmill asks the user, who can allow it once or allow writes in that folder from then on. When the task needs one, make the call directly rather than asking first, and never move a change to another folder to avoid the question.
- Read anything you need from any folder: a flow here can call scripts and use resources from other folders. Runs are not limited by the scope.
- list_workspace_items lists under ${dirs} unless you pass path_prefix; pass path_prefix "" to list the whole workspace when ${one ? 'the folder lacks' : 'they lack'} what you need.
- If the user cannot write a folder of the scope, creating there fails: say so and suggest another scope.${instructions ? `\n\nThe instructions of ${one ? 'the folder' : 'these folders'}, which apply to all your work in ${one ? 'it' : 'them'}:\n${instructions}` : ''}`
}
}
/** Whether the user can write under `root`, for the picker's read-only tag. Unknown folder
* rights count as writable, so a failed lookup marks nothing read only. */
export function canWriteRoot(root: string, identity: WorkingScopeIdentity | undefined): boolean {
if (!identity?.folders || identity.is_admin) return true
const [kind, name] = root.split('/')
if (kind === 'u') return name === identity.username
return identity.folders.includes(name)
}
/** What the user answered on the block row. Stopping the turn leaves it unanswered. */
export type ScopeDecision = 'once' | 'add'
/** What the model is told after the user let a call through, so it neither says the call
* needed no confirmation nor assumes the next one is allowed too. */
export function scopeAllowedNote(
path: string,
root: string,
scope: string,
decision: ScopeDecision
): string {
return decision === 'once'
? `The user allowed this one change to ${path}, outside ${scope}: the next change outside ${scope} asks again.`
: `The user allowed writes in ${root} for the rest of this session: changes there no longer ask.`
}
/** The tool result of a call the turn was stopped on. */
export function scopeStoppedResult(path: string, scope: string): string {
return `Not done: ${path} is outside ${scope}, where this session works, and the user stopped instead of allowing it. Nothing was changed.`
}
export type ScopeOption = {
root: string
/** The user cannot write here, so creating fails. */
readOnly: boolean
instructions: string[]
skills: string[]
mcpServers: string[]
}
export type ScopeResources = {
instructions: readonly { path: string }[]
skills: readonly { path: string }[]
mcpServers: readonly { path: string }[]
}
/** The roots the picker offers: the user's own space, then every folder they can read. */
export function scopeOptions(
folders: readonly string[],
identity: WorkingScopeIdentity | undefined,
resources: ScopeResources
): ScopeOption[] {
const roots = [
...(identity?.username ? [`u/${identity.username}`] : []),
...[...folders].sort().map((f) => `f/${f}`)
]
return roots.map((root) => scopeOption(root, identity, resources))
}
export function scopeOption(
root: string,
identity: WorkingScopeIdentity | undefined,
resources: ScopeResources
): ScopeOption {
const under = (list: readonly { path: string }[]) =>
list.filter((r) => ownerRoot(r.path) === root).map((r) => r.path)
return {
root,
readOnly: !canWriteRoot(root, identity),
instructions: under(resources.instructions),
skills: under(resources.skills),
mcpServers: under(resources.mcpServers)
}
}
function plural(n: number, word: string): string {
return `${n} ${word}${n === 1 ? '' : 's'}`
}
/** `1 instruction · 2 skills · 1 MCP`, empty when the root carries none. */
export function scopeBadge(option: ScopeOption): string {
return [
...(option.instructions.length ? [plural(option.instructions.length, 'instruction')] : []),
...(option.skills.length ? [plural(option.skills.length, 'skill')] : []),
...(option.mcpServers.length ? [`${option.mcpServers.length} MCP`] : [])
].join(' · ')
}
/** How a folder's instructions and skills reach the AI, in the one wording the picker and the
* tree badge share. */
export function scopeRule(root: string): string {
return `Working in ${root} puts its instructions in the AI's prompt and keeps its skills on; skills from other folders are off. Outside it, the AI gets a folder's instructions the first time it touches that folder.`
}
export type ScopeKind = 'workspace' | 'none' | 'folder' | 'user_space' | 'several'
export type ScopeSource = 'default' | 'preset' | 'manual'
export function scopeKind(roots: readonly string[] | undefined): ScopeKind {
if (!roots) return 'workspace'
if (!roots.length) return 'none'
if (roots.length > 1) return 'several'
return roots[0].startsWith('u/') ? 'user_space' : 'folder'
}
/** Closed vocabulary for the `ai_session`/`working_folders` counter: a scope a turn was sent
* in, a block's outcome, and how many folders a whole-workspace session wrote to (`1`, then
* `2+` once it reaches a second). */
export type WorkingScopeEvent =
| `scope:${ScopeKind}:${ScopeSource}`
| `block:${'once' | 'add' | 'none'}`
| `written:${'1' | '2+'}`
export function logWorkingScope(key: WorkingScopeEvent, workspace: string | undefined): void {
logFeatureUsage('ai_session', 'working_folders', { key, workspace })
}
@@ -816,7 +816,6 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac
handleToolConfirmation = (_toolId: string, confirmed: boolean) => {
this.#answer(confirmed)
}
handleScopeDecision = () => {}
hasPendingRunForm = false
isRunFormPending = () => false
@@ -1,75 +0,0 @@
<!--
@component
What a folder or user row carries for the assistant: its instructions, skills and MCP servers,
counted on the row and named in a popover.
-->
<script lang="ts">
import { Button } from '$lib/components/common'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import { BookOpen, ExternalLink } from 'lucide-svelte'
import { homeComposerContext } from '../sessions/homeComposerContext.svelte'
import { scopeBadge, scopeOption, scopeRule } from '../copilot/chat/workingScope'
let { root }: { root: string } = $props()
const manager = $derived(homeComposerContext.runtime?.manager)
const row = $derived(
manager ? scopeOption(root, manager.scopeIdentity, manager.scopeResources) : undefined
)
const badge = $derived(row ? scopeBadge(row) : '')
</script>
{#if row && badge}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div onclick={(e) => e.stopPropagation()}>
<Popover placement="bottom-end" contentClasses="p-3 w-72 flex flex-col gap-2 text-xs">
{#snippet trigger()}
<Button
variant="subtle"
unifiedSize="2xs"
startIcon={{ icon: BookOpen }}
nonCaptureEvent
>
{badge}
</Button>
{/snippet}
{#snippet content()}
{#if row.instructions.length}
<div>
<p class="text-2xs text-secondary">Instructions</p>
{#each row.instructions as path (path)}
<p class="font-mono text-primary">{path}</p>
{/each}
</div>
{/if}
{#if row.skills.length}
<div>
<p class="text-2xs text-secondary">Skills</p>
{#each row.skills as path (path)}
<p class="font-mono text-primary">{path}</p>
{/each}
</div>
{/if}
{#if row.mcpServers.length}
<div>
<p class="text-2xs text-secondary">MCP servers</p>
{#each row.mcpServers as path (path)}
<p class="font-mono text-primary">{path}</p>
{/each}
</div>
{/if}
<p class="text-2xs text-secondary">{scopeRule(root)}</p>
<Button
variant="subtle"
unifiedSize="xs"
endIcon={{ icon: ExternalLink }}
href="/resources?owner={encodeURIComponent(root)}"
btnClasses="!justify-start !px-0"
>
Open {root} in Resources
</Button>
{/snippet}
</Popover>
</div>
{/if}
@@ -20,8 +20,6 @@
detail: Snippet
/** Controls rendered next to the name. Clicks on them do not toggle the row. */
actions?: Snippet
/** Always-visible controls before the chevron. They stop their own clicks. */
trailing?: Snippet
}
let {
@@ -32,8 +30,7 @@
indent = 0,
toggleLabel,
detail,
actions,
trailing
actions
}: Props = $props()
</script>
@@ -72,14 +69,9 @@
</div>
</div>
</div>
{#if trailing}
<div class="shrink-0 ml-auto pr-3">
{@render trailing()}
</div>
{/if}
<!-- Keyboard access only: its click bubbles to the row, which does the toggling. -->
<button
class="{trailing ? 'shrink-0' : 'w-full'} flex flex-row-reverse"
class="w-full flex flex-row-reverse"
aria-expanded={opened}
aria-label={toggleLabel ?? name}
>
@@ -7,7 +7,6 @@
import { userStore } from '$lib/stores'
import Dropdown from '$lib/components/DropdownV2.svelte'
import TreeOwnerRow from './TreeOwnerRow.svelte'
import HomeFolderBadge from './HomeFolderBadge.svelte'
import PipelineRow from '../common/table/PipelineRow.svelte'
import Item from './Item.svelte'
import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils'
@@ -99,14 +98,6 @@
const isFolderItem = (i: typeof item): i is FolderItem => i && 'folderName' in i
const isFolder = isFolderItem
const isUser = (i: typeof item): i is UserItem => i && 'username' in i
// A nested folder row is a path inside its parent's root, which carries the badge.
const badgeRoot = $derived(
isUser(item)
? `u/${item.username}`
: isFolder(item) && depth === 0
? `f/${item.folderName}`
: undefined
)
// Hidden while searching: pipelines aren't part of the text filter (the list
// view hides their rows on a query too), so a folder matching the search
@@ -285,12 +276,6 @@
}
</script>
{#snippet folderBadge()}
{#if badgeRoot}
<HomeFolderBadge root={badgeRoot} />
{/if}
{/snippet}
{#snippet manageFolderMenu()}
{#if isFolder(item)}
{@const folderName = item.folderName}
@@ -323,7 +308,6 @@
onToggle={toggleOwner}
indent={visualDepth * 16}
actions={onManageFolder && depth === 0 && isFolder(item) ? manageFolderMenu : undefined}
trailing={badgeRoot ? folderBadge : undefined}
>
{#snippet detail()}
{#if ownerCount != undefined}
@@ -94,16 +94,6 @@
runtime
})
})
onMount(() => {
const manager = runtime.manager
// What the tree's folder badges count. The send path loads these, and Home has not sent.
if (!manager.loading && !manager.sendInFlight) {
void manager.refreshGlobalIdentity()
void manager.refreshGlobalFolderInstructions()
void manager.refreshGlobalSkills()
void manager.refreshMcpServers()
}
})
</script>
<!-- Until a config has loaded the chat reads "AI not configured" and would flash its disabled
@@ -48,8 +48,8 @@ export const homeComposerContext = {
get available(): boolean {
return registered !== undefined
},
/** The runtime of the draft in Home's composer, whose chat manager the tree's folder badges
* read. Read from here because Home must not import the runtime's code (it reaches monaco). */
/** The runtime of the draft in Home's composer, whose preview tabs Home's panel shows. Read
* from here because Home must not import the runtime's code (it reaches monaco). */
get runtime(): SessionRuntime | undefined {
return registered?.runtime
},
@@ -63,7 +63,6 @@ import {
setDraftsDiscardedHandler,
setSendUnderWayCheck,
setSessionWorkMode,
setSessionWorkingIn,
type Session
} from './sessionState.svelte'
import {
@@ -440,13 +439,6 @@ function createRuntime(session: Session): SessionRuntime {
manager.sessionId = session.id
manager.workMode = session.workMode ?? AIWorkMode.BUILD
manager.onWorkModeChanged = (mode) => setSessionWorkMode(session.id, mode)
manager.workingInResolver = () => {
const s = sessionState.sessions.find((x) => x.id === session.id)
// Read from the browser's store, so only a list counts.
const roots = Array.isArray(s?.workingIn) ? s.workingIn : undefined
return { roots, source: roots ? (s?.workingInSource ?? 'default') : 'default' }
}
manager.onWorkingInChanged = (roots, source) => setSessionWorkingIn(session.id, roots, source)
// Cross-tab awareness: heartbeat while this tab runs a turn, composer lock
// (and send refusal) while another tab does. The chat id is read at turn
// end, not captured at start — the turn may have rotated it, and the other
@@ -160,11 +160,6 @@ export type Session = {
previewSize?: number
// Use or Build, as the chat's mode picker last left it. Absent reads as Build.
workMode?: AIWorkMode.USE | AIWorkMode.BUILD
// The owner roots (`f/<folder>`, `u/<user>`) the AI changes items in, sorted. Empty: none,
// so every change asks. Absent: the whole workspace. Per browser, like workMode: the backup leaves it out.
workingIn?: string[]
// How the scope was set, for its usage counter. Absent: the default.
workingInSource?: 'preset' | 'manual'
// Unsent composer text for a pending (uncommitted) session, persisted with
// the record so each parallel draft restores its own typed-but-unsent prompt.
// Only tracked while unsent; cleared once the workspace commits at first send.
@@ -1402,21 +1397,6 @@ export function setSessionWorkMode(id: string, mode: AIWorkMode): void {
persistTouched(s)
}
/** Not a touch: picking a scope on Home's untouched draft must not keep it in the sidebar. */
export function setSessionWorkingIn(
id: string,
roots: readonly string[] | undefined,
source: 'preset' | 'manual' | undefined
): void {
const s = sessionState.sessions.find((x) => x.id === id)
if (!s) return
if (roots) s.workingIn = [...new Set(roots)].sort()
else delete s.workingIn
if (source) s.workingInSource = source
else delete s.workingInSource
if (!s.transient) void putSession(s)
}
export function selectSession(id: string) {
sessionState.currentSessionId = id
}
@@ -16,7 +16,6 @@ import {
setNewSessionWorkspace,
setSessionDraftPrompt,
setSessionPendingWorkspace,
setSessionWorkingIn,
showOnHome,
syncWorkspaceTo,
type Session,
@@ -30,7 +29,6 @@ import { homeComposerContext } from './homeComposerContext.svelte'
// navigation seam (see the dynamic import in openEditorInSession).
import type { OpenInSessionSource } from './OpenInSessionButton.svelte'
import type { AppDomSelectorElement } from '../copilot/chat/context'
import { presetScopeFor } from '../copilot/chat/workingScope'
// `seedDomElement` rides only with `autoSend`: it is the chip of the prompt being sent.
// `untilStarted` keeps the session out of storage until the user starts it, for an item that
@@ -146,8 +144,7 @@ export async function openEditorInSession(
await openInSession(
withPreviewParams(sessionTargetHref(target), previewParams),
workspaceId,
opts,
presetScopeFor(target.path)
opts
)
}
@@ -165,10 +162,9 @@ export async function openPageInSession(
async function openInSession(
url: string | undefined,
workspaceId?: string,
opts?: SeedOpts,
workingIn?: string[]
opts?: SeedOpts
): Promise<void> {
await goto(await sessionHrefFor(url, workspaceId, opts, workingIn))
await goto(await sessionHrefFor(url, workspaceId, opts))
}
/** A fresh session's page, with an editor in its preview. For a `load` that sends the
@@ -178,19 +174,13 @@ export function editorSessionHref(
workspaceId?: string,
previewParams?: Record<string, string>
): Promise<string> {
return sessionHrefFor(
withPreviewParams(sessionTargetHref(target), previewParams),
workspaceId,
undefined,
presetScopeFor(target.path)
)
return sessionHrefFor(withPreviewParams(sessionTargetHref(target), previewParams), workspaceId)
}
async function sessionHrefFor(
url: string | undefined,
workspaceId?: string,
opts?: SeedOpts,
workingIn?: string[]
opts?: SeedOpts
): Promise<string> {
// Seed the fresh session's preview with a single tab on `url` so it opens
// straight onto what the caller wants (resetSessionPreviewTabs also writes
@@ -200,8 +190,6 @@ async function sessionHrefFor(
holdSessionUntilStarted(session.id)
if (workspaceId) setNewSessionWorkspace(session.id, workspaceId)
} else if (workspaceId) setSessionPendingWorkspace(session.id, workspaceId)
// A reused blank may carry a scope picked on it; the item's folder, or none, replaces it.
setSessionWorkingIn(session.id, workingIn, workingIn ? 'preset' : undefined)
if (opts?.seedPrompt) {
setSessionDraftPrompt(session.id, opts.seedPrompt)
if (opts.autoSend) setSessionAutoSend(session.id, opts.seedDomElement)