From febbb40df99fc9935ad71eaa9bb492a6cfae5d2e Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Fri, 30 Oct 2026 06:00:53 -0700 Subject: [PATCH] feat: add working folders and folder instructions to ai sessions Co-Authored-By: Claude Opus 5.5 --- backend/ee-repo-ref.txt | 2 +- .../common/modal/PagedContent.svelte | 5 +- .../copilot/chat/AIChatDisplay.svelte | 41 ++ .../copilot/chat/AIChatManager.svelte.ts | 222 +++++- .../chat/AssistantInstructionsSection.svelte | 683 +++++++++++++++--- .../copilot/chat/AssistantMcpSection.svelte | 13 +- .../chat/AssistantSettingsModal.svelte | 15 +- .../chat/AssistantSkillsSection.svelte | 26 +- .../copilot/chat/OutOfScopeFooter.svelte | 47 ++ .../copilot/chat/ToolDiffCard.svelte | 34 +- .../copilot/chat/ToolExecutionDisplay.svelte | 34 +- .../copilot/chat/WorkingInPicker.svelte | 176 +++++ .../components/copilot/chat/chatViewHost.ts | 2 + .../copilot/chat/folderInstructions.ts | 77 +- .../components/copilot/chat/global/core.ts | 43 +- .../copilot/chat/global/globalAssembly.ts | 5 + .../chat/readOnlyChatViewHost.svelte.ts | 1 + .../components/copilot/chat/shared.test.ts | 56 +- .../src/lib/components/copilot/chat/shared.ts | 96 ++- .../copilot/chat/toolGroups.test.ts | 10 + .../lib/components/copilot/chat/toolGroups.ts | 1 + .../copilot/chat/workingInOptions.svelte.ts | 36 + .../copilot/chat/workingScope.test.ts | 42 ++ .../components/copilot/chat/workingScope.ts | 250 +++++++ .../conversations/flowChatViewHost.svelte.ts | 1 + .../components/home/HomeFolderBadge.svelte | 75 ++ .../lib/components/home/TreeOwnerRow.svelte | 12 +- .../src/lib/components/home/TreeView.svelte | 16 + .../sessions/HomeSessionStarter.svelte | 10 + .../sessions/homeComposerContext.svelte.ts | 4 +- .../sessions/sessionRuntime.svelte.ts | 8 + .../sessions/sessionState.svelte.ts | 20 + .../sessions/sessionSwitch.svelte.ts | 22 +- 33 files changed, 1930 insertions(+), 155 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/OutOfScopeFooter.svelte create mode 100644 frontend/src/lib/components/copilot/chat/WorkingInPicker.svelte create mode 100644 frontend/src/lib/components/copilot/chat/workingInOptions.svelte.ts create mode 100644 frontend/src/lib/components/copilot/chat/workingScope.test.ts create mode 100644 frontend/src/lib/components/copilot/chat/workingScope.ts create mode 100644 frontend/src/lib/components/home/HomeFolderBadge.svelte diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 17bdde30cb..2cdc0ee8b1 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -26663361632280a25b964e6f3944e503dca2a366 +9084bd523e19c5de1f43568714c6aeaf6a466368 diff --git a/frontend/src/lib/components/common/modal/PagedContent.svelte b/frontend/src/lib/components/common/modal/PagedContent.svelte index bfae0473f1..eb6ff116b6 100644 --- a/frontend/src/lib/components/common/modal/PagedContent.svelte +++ b/frontend/src/lib/components/common/modal/PagedContent.svelte @@ -179,10 +179,11 @@ 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. --> - +
{ + 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() + 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. @@ -885,6 +912,13 @@ 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)} +

+ Now working in {#if root}{root}{:else}the whole + workspace{/if} +

+ {/if} />
{/if} +
{outOfScopeAnnouncement}
@@ -1075,6 +1110,9 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> {onSent} > {#snippet collapsedControls()} + {#if chatHost.mode === AIMode.GLOBAL} + + {/if} {#if chatHost.supportsModelSettings} {/if} @@ -1318,6 +1356,9 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> {/snippet} {/if} + {#if chatHost.mode === AIMode.GLOBAL} + + {/if} {#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled} {/if} diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index c490459d5e..9ab0d9173a 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -157,10 +157,21 @@ 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, @@ -914,6 +925,9 @@ export class AIChatManager implements ChatViewHost { { resolve: (value: boolean) => void; toolName?: string } >() private userQuestionCallbacks = new Map void>() + // Kept apart from confirmationCallbacks: YOLO answers those, and never answers these. + // Resolved undefined when the turn stops first. + private scopeCallbacks = new Map 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 @@ -935,6 +949,96 @@ 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 ": 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() + #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 @@ -1500,7 +1604,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: FolderInstruction[] = [] + private globalFolderInstructions = $state([]) private globalFolderInstructionsRefreshId = 0 private folderInstructionsDeliveredBy = new Map() @@ -1541,7 +1645,7 @@ export class AIChatManager implements ChatViewHost { // those by path and the submit path declines to guess between them. sessionCommands: ChatCommandItem[] = $derived([ ...this.sessionBuiltinCommands, - ...this.globalSkills + ...this.#loadedSkills() .filter((s) => !this.sessionBuiltinCommands.some((b) => b.name === s.name)) .map((s) => ({ ...s, kind: 'skill' as const })) ]) @@ -2051,6 +2155,33 @@ export class AIChatManager implements ChatViewHost { }) } + requestScopeDecision = (toolId: string): Promise => + 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) @@ -2805,16 +2936,21 @@ export class AIChatManager implements ChatViewHost { this.syncArtifactsSession() } - 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() - }) + 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() + } + } #sessionPromptContext = (): SessionPromptContext | undefined => { const ctx = this.sessionContextResolver?.() @@ -2857,6 +2993,34 @@ 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() } @@ -2961,8 +3125,9 @@ 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 byPath = this.globalSkills.find((s) => s.path === match[1]) - const matches = byPath ? [byPath] : this.globalSkills.filter((s) => s.name === match[1]) + const skills = this.#loadedSkills() + const byPath = skills.find((s) => s.path === match[1]) + const matches = byPath ? [byPath] : skills.filter((s) => s.name === match[1]) if (matches.length !== 1) { return instructions } @@ -3895,6 +4060,11 @@ 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, { @@ -3906,6 +4076,7 @@ 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 } ] @@ -3919,6 +4090,7 @@ 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 { @@ -3958,6 +4130,13 @@ 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 ?? ''), @@ -4409,7 +4588,14 @@ export class AIChatManager implements ChatViewHost { onJobDetached: (jobId) => this.markJobDetached(jobId), folderInstructions: { list: () => this.globalFolderInstructions, - deliveredBy: this.folderInstructionsDeliveredBy + deliveredBy: this.folderInstructionsDeliveredBy, + inPrompt: () => this.#currentScopeInstructions()?.paths ?? [] + }, + workingScope: { + scope: this.#workingScope, + requestDecision: this.requestScopeDecision, + add: this.#addToScope, + recordWrite: this.#recordWrite } } : {}), @@ -4671,6 +4857,7 @@ 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() @@ -4725,6 +4912,11 @@ 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) } diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 324082e3e0..08fbac7eb0 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -1,29 +1,61 @@ + + + +{#snippet listPage()} + +
+
+ {#snippet action()} +
+ {#if isAdmin} + + {/if} + +
+ {/snippet} + +
+ {@render block('workspace')} + {@render block('user')} + {#each tree as node (node.path)} + {@render folder(node, true)} + {/each} +
+ {#if folderLoadError} +
+ Failed to load folder instructions: {folderLoadError} +
+ {:else if !loading && folderRows.length === 0} +

+ No folder has instructions yet. A folder's instructions are followed for every item in it. +

+ {/if} +
+
+{/snippet} + +{#snippet block(kind: 'workspace' | 'user')} + {@const saved = kind === 'workspace' ? workspaceSaved : userSaved} + {@const changed = kind === 'workspace' ? workspaceChanged : userChanged} + {#snippet icon()} + {#if kind === 'workspace'} + + {:else} + + {/if} + {/snippet} + {#snippet title()} + {kind === 'workspace' ? 'Workspace' : 'You'} + {/snippet} + {#snippet subtitle()} + {#if changed} + Unsaved changes · + {/if} + {preview(saved) ?? (kind === 'workspace' ? `None set for ${ws}` : 'None set')} + {/snippet} + openBlock(kind)} /> +{/snippet} + + +{#snippet folder(node: SkillTreeNode, root: boolean)} +
+ + {#if !collapsed[node.path]} +
+ {#each node.children as child (child.path)} + {@render folder(child, false)} + {/each} + {#each node.skills as row (row.path)} + {@render instruction(row)} + {/each} +
+ {/if} +
+{/snippet} + +{#snippet instruction(row: FolderInstructionRow)} + {#snippet icon()} + + {/snippet} + {#snippet title()} + {row.name} + {/snippet} + {#snippet subtitle()} + {#if folderChanged && detail?.kind === 'folder' && detail.row.path === row.path} + Unsaved changes · + {/if} + {@const inScope = aiChatManager.workingScope?.roots?.find((r) => `${r}/`.startsWith(row.scope))} + {#if inScope} + In the prompt while working in {inScope} · + {/if} + Followed for every item under {row.scope} + {/snippet} + openFolder(row)} /> +{/snippet} + {#snippet field(p: { value: string; readOnly: boolean; onInput: (v: string) => void })}
p.onInput(e.currentTarget.value) }} @@ -290,68 +678,191 @@ writes whichever of the two changed, including the tab that is not on screen.
{/snippet} -
- {#snippet action()} -
- {#if isAdmin} - - {/if} +{#snippet detailPage()} + +
+ +
- {/snippet} - - - - - {#snippet content()} - -
- {note} - {#if workspaceReadOnly && tab === 'workspace'} - - {readOnlyReason} - - {/if} - - + {#if detail?.kind === 'workspace' || detail?.kind === 'user'} + {@const kind = detail.kind} +
+ {#snippet action()} + + {/snippet} + + {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.'} + + {#if kind === 'workspace'} + {#if workspaceReadOnly} + + {readOnlyReason} + + {/if} {@render field({ value: workspaceDraft, readOnly: workspaceReadOnly, onInput: (v) => (workspaceDraft = v) })} - - - {@render field({ - value: userDraft, - readOnly: false, - onInput: (v) => (userDraft = v) - })} - -
- {/snippet} -
-
+ {:else} + {@render field({ value: userDraft, readOnly: false, onInput: (v) => (userDraft = v) })} + {/if} + + {/if} + +
+
+ {#snippet action()} + {#if detail?.kind === 'folder'} +
+ + {#snippet children({ item })} + + + {/snippet} + +
+ {/if} + {/snippet} +
+ {#if detail?.kind === 'folder'} + + Followed for every item under {detail.row.scope}, delivered the first time the + assistant works on one of them. + + {/if} +
+
+ {#if folderContent.trim()} + + {:else} + Empty. + {/if} +
+
+
+ {#if detail?.kind === 'new'} + + {/if} +
+ +
+
+
+ {#if detail?.kind === 'folder'} + {@const row = detail.row} + + {/if} +
+
+ + +
+
+
+
+
+
+ +{/snippet} + + { + const row = toDelete + toDelete = undefined + if (row) await removeFolder(row) + }} + onCanceled={() => (toDelete = undefined)} +> + + This deletes the resource at {toDelete?.path}, so the + assistant stops following it for everyone. + + diff --git a/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte index c8d360e0f9..1a0cb075f2 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte @@ -36,6 +36,7 @@ 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, @@ -487,7 +488,15 @@ switch that decides whether this chat carries its tools. {#snippet title()} {server.path} {/snippet} - {#snippet subtitle()}{server.description}{/snippet} + {@const scopeRoots = aiChatManager.workingScope?.roots} + {@const fromRoot = scopeRoots?.find((r) => ownerRoot(server.path) === r)} + {@const fromScope = !!fromRoot} + {#snippet subtitle()} + {#if fromRoot} + From {fromRoot}, where this session works. + {/if} + {server.description} + {/snippet} {#snippet trailing()} openServer(server)} /> {/each} diff --git a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte index 534e550b89..c030fe5c9d 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte @@ -208,6 +208,11 @@ callers that already know which section they mean, such as the "+" menu's Manage {#snippet headerLeft()}

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 {aiChatManager.workingScope.label}. + {/if}

{/snippet} @@ -234,9 +239,9 @@ callers that already know which section they mean, such as the "+" menu's Manage
+ 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. -->
{#snippet action()}
@@ -962,7 +974,15 @@ What the assistant should do when this skill applies. {!grouped && ambiguous.has(skill.name) ? skill.path : skill.name} {/snippet} - {#snippet subtitle()}{skill.description}{/snippet} + {@const note = scopeNote(skill.path)} + {#snippet subtitle()} + {#if note?.off} + Off while working in {note.root}. + {:else if note} + From {note.root}, where this session works. + {/if} + {skill.description} + {/snippet} {#snippet trailing()} highlight.hovered(entryIndexByKey.get(skillKey(skill.path)) ?? -1)} - subtitle={skill.description ? subtitle : undefined} + subtitle={skill.description || note ? subtitle : undefined} onClick={() => openSkill(skill)} /> {/snippet} diff --git a/frontend/src/lib/components/copilot/chat/OutOfScopeFooter.svelte b/frontend/src/lib/components/copilot/chat/OutOfScopeFooter.svelte new file mode 100644 index 0000000000..128d9f3697 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/OutOfScopeFooter.svelte @@ -0,0 +1,47 @@ + + + + +
+

+ This would {verb} {path}, outside + {scope}. +

+
+ + +
+
diff --git a/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte b/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte index eb0fc1194b..ff03c561df 100644 --- a/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte @@ -4,6 +4,7 @@ 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, @@ -24,8 +25,15 @@ 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) || awaitingConfirmation) + const hasBody = $derived(hasDiff || Boolean(message.error) || awaitingAnswer) // 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 @@ -35,9 +43,12 @@ // 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 || + (message.error && !declined) || (hasDiff && !diffIsWholeFile(message) && (message.isLoading || message.isQueued || message.isStreamingArguments)) @@ -50,7 +61,7 @@ }) // The Apply/Reject footer is inside the body, so a pending confirmation keeps it open. const expanded = $derived( - awaitingConfirmation || + awaitingAnswer || (hasBody && (toggled?.id === toggleKey ? toggled.open : opensByDefault)) ) const lines = $derived(diff && expanded ? toolDiffLines(diff, isStreaming) : undefined) @@ -62,7 +73,7 @@ : undefined ) - const isRunning = $derived(Boolean(message.isLoading && !message.needsConfirmation)) + const isRunning = $derived(Boolean(message.isLoading && !awaitingAnswer)) const showPreviewChip = $derived( Boolean(!hidePreviewChip && message.previewCard && !message.isLoading && !message.error) ) @@ -86,7 +97,7 @@ label={message.content} {expanded} onToggle={() => (toggled = { id: toggleKey, open: !expanded })} - toggleable={hasBody && !awaitingConfirmation} + toggleable={hasBody && !awaitingAnswer} shimmer={isRunning} class={message.isQueued && !message.error ? 'opacity-60 hover:opacity-100 transition-opacity' @@ -107,10 +118,21 @@ confirmLabel="Apply" confirmIcon={Check} /> + {:else if pendingOutOfScope} + {/if} {#if message.error}
diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 1b267472c8..a7ca9a93cc 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -52,6 +52,7 @@ 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 { @@ -123,7 +124,14 @@ // Executing right now, as opposed to queued behind another tool or waiting on // the user — the only state that gets the shimmer. - const isRunning = $derived(Boolean(message.isLoading && !message.needsConfirmation)) + const pendingOutOfScope = $derived( + message.isLoading && message.outOfScope && !message.outOfScope.decision + ? message.outOfScope + : undefined + ) + const isRunning = $derived( + Boolean(message.isLoading && !message.needsConfirmation && !pendingOutOfScope) + ) // An errored tool must be expandable even if it never opted into details, // otherwise the error set on its status would be invisible. @@ -138,6 +146,7 @@ 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( @@ -356,7 +365,7 @@ class={message.isQueued && !message.error ? 'opacity-60 hover:opacity-100 transition-opacity' : ''} - headerClass={message.needsConfirmation ? 'opacity-80' : ''} + headerClass={message.needsConfirmation || pendingOutOfScope ? 'opacity-80' : ''} labelClass={showPreviewChip ? 'truncate' : ''} contentClass="space-y-3" headerRight={showPreviewChip ? previewChip : message.jobId ? jobLink : undefined} @@ -376,8 +385,8 @@ {/snippet} - {#if hasParameters || message.needsConfirmation} -
+ {#if hasParameters || message.needsConfirmation || pendingOutOfScope} +
+ {:else if pendingOutOfScope} + {:else if !message.isStreamingArguments} @@ -424,3 +441,12 @@ {/if} {/if} + + +{#if message.outOfScope?.decision} +

+ {message.outOfScope.decision === 'once' + ? `You allowed this ${message.outOfScope.verb} outside ${message.outOfScope.scope}.` + : `You allowed writes in ${message.outOfScope.root} for this session.`} +

+{/if} diff --git a/frontend/src/lib/components/copilot/chat/WorkingInPicker.svelte b/frontend/src/lib/components/copilot/chat/WorkingInPicker.svelte new file mode 100644 index 0000000000..b9742ef878 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/WorkingInPicker.svelte @@ -0,0 +1,176 @@ + + + +{#snippet sectionTitle(title: string)} +

{title}

+{/snippet} + +{#snippet option(item: MeltItem, o: ScopeOption)} + {@const caption = [o.readOnly ? 'Read only' : '', scopeBadge(o)].filter(Boolean).join(' · ')} + toggle(o.root)}> +
+

{o.root}

+ {#if caption} +

{caption}

+ {/if} +
+ {#if picked(o.root)} + + {/if} +
+{/snippet} + +{#if aiChatManager.supportsWorkingIn && !aiChatManager.useModeActive && (current || !onlyWhenScoped)} + (query = '')} + > + {#snippet buttonReplacement()} + + {/snippet} + {#snippet menu({ item })} +
+
+

Allow writes in

+

Writes anywhere else ask you first.

+
+ {#if searchable} +
+ { + if (e.key !== 'Escape') e.stopPropagation() + } + }} + /> +
+ {/if} +
+ aiChatManager.setWorkingIn(undefined)} + > + Select all + + aiChatManager.setWorkingIn([])}> + Deselect all + +
+
+ {#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} +
+ {/if} + {@render sectionTitle('Folders')} + {#each folders as o (o.root)} + {@render option(item, o)} + {/each} + {/if} + {#if !shown.length} +

No folder matches

+ {/if} +
+
+ {/snippet} +
+{/if} diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index 5e94f39311..fc0b2c863d 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -8,6 +8,7 @@ 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' @@ -110,6 +111,7 @@ export interface ChatViewHost { ) => void | Promise 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 diff --git a/frontend/src/lib/components/copilot/chat/folderInstructions.ts b/frontend/src/lib/components/copilot/chat/folderInstructions.ts index ec74576d54..3d33757756 100644 --- a/frontend/src/lib/components/copilot/chat/folderInstructions.ts +++ b/frontend/src/lib/components/copilot/chat/folderInstructions.ts @@ -1,4 +1,8 @@ -import { ResourceService } from '$lib/gen' +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 { folderInstructionScope, folderInstructionsOpeningTag as openingTag, @@ -31,14 +35,12 @@ const PAGE_SIZE = 100 /** Guard against a paging bug looping forever, not a product cap. */ const MAX_PAGES = 20 -/** 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( +async function listInstructionResources( workspace: string, - resourceType: string = FOLDER_INSTRUCTIONS_RESOURCE_TYPE -): Promise { + resourceType: string +): Promise { if (!workspace) return [] - const rows: FolderInstruction[] = [] + const rows: ListableResource[] = [] for (let page = 1; page <= MAX_PAGES; page++) { const resources = await ResourceService.listResource({ workspace, @@ -46,12 +48,64 @@ export async function listFolderInstructions( page, perPage: PAGE_SIZE }) - rows.push(...resources.map((r) => ({ path: r.path, scope: folderInstructionScope(r.path) }))) + rows.push(...resources) 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 { + 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 { + 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 { + 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. */ @@ -78,6 +132,8 @@ export function workspacePathsInArgs(args: unknown, depth = 0): string[] { export type FolderInstructionsContext = { list: () => readonly FolderInstruction[] deliveredBy: Map + /** 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 @@ -128,7 +184,10 @@ export async function pendingFolderInstructions( const paths = workspacePathsInArgs(args) if (paths.length === 0) return undefined const { read, thisBatch } = deliveredIn(ctx, messages, workspace) - const pending = instructionsCovering(ctx.list(), paths).filter((i) => !read.has(i.path)) + const inPrompt = new Set(ctx.inPrompt?.() ?? []) + const pending = instructionsCovering(ctx.list(), paths).filter( + (i) => !read.has(i.path) && !inPrompt.has(i.path) + ) const inBatch = pending.filter((i) => thisBatch.has(i.path)) const blocks = ( await Promise.all( diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index b0a5383b6c..2fac52e784 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -3261,7 +3261,8 @@ export const readSkillTool: SessionTool<{}> = { const isSkill = (await listSkillResources(workspace)).skills.some( (s) => s.path === parsed.path ) - if (!isSkill || !isSkillEnabled(workspace, parsed.path)) { + const suspended = toolCallbacks.workingScope?.scope()?.loadsSkill(parsed.path) === false + if (!isSkill || !isSkillEnabled(workspace, parsed.path) || suspended) { 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.` } @@ -4278,13 +4279,26 @@ export const globalTools: SessionTool<{}>[] = [ ).filter((row) => itemMatches(row, parsed.query)) const byKey = new Map() - const workspaceItems = await listWorkspaceItems( - types, - workspace, - parsed.path_prefix, - Math.min(limit, MAX_LIST_LIMIT), - parsed.page - ) + // 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() for (const item of workspaceItems) { byKey.set(getWorkspaceItemKey(item.type, item.path, item.triggerKind), item) } @@ -4296,7 +4310,7 @@ export const globalTools: SessionTool<{}>[] = [ // (it filters before the cap; query filters after). if ((parsed.page ?? 1) === 1) { const draftCountByType = new Map() - const prefix = parsed.path_prefix + const narrowing = prefixes.filter((p): p is string => !!p) 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 @@ -4304,7 +4318,10 @@ 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 (prefix && !draft.path.startsWith(prefix) && !draft.draftPath?.startsWith(prefix)) + if ( + narrowing.length && + !narrowing.some((p) => draft.path.startsWith(p) || draft.draftPath?.startsWith(p)) + ) continue const count = draftCountByType.get(draft.type) ?? 0 if (count >= limit) continue @@ -4328,7 +4345,10 @@ export const globalTools: SessionTool<{}>[] = [ toolCallbacks.setToolStatus(toolId, { content: `Listed ${results.length} workspace item(s)` }) - return JSON.stringify(results, null, 2) + 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 } }, { @@ -5276,6 +5296,7 @@ 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) => { diff --git a/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts b/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts index d1fe80f13d..c17630b775 100644 --- a/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts +++ b/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts @@ -14,6 +14,7 @@ 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 @@ -24,6 +25,9 @@ export type GlobalAssemblyOpts = NonNullable false, handleToolConfirmation: noop, + handleScopeDecision: noop, hasPendingRunForm: false, isRunFormPending: () => false, diff --git a/frontend/src/lib/components/copilot/chat/shared.test.ts b/frontend/src/lib/components/copilot/chat/shared.test.ts index 5a3427006e..88a5efb7c5 100644 --- a/frontend/src/lib/components/copilot/chat/shared.test.ts +++ b/frontend/src/lib/components/copilot/chat/shared.test.ts @@ -224,7 +224,8 @@ describe('processToolCall', () => { { path: 'f/other/AGENTS', scope: 'f/other/' }, { path: 'g/ops/AGENTS', scope: 'g/ops/' } ], - deliveredBy: new Map() + deliveredBy: new Map(), + inPrompt: undefined as (() => string[]) | undefined } const messages: any[] = [] const call = async ( @@ -307,6 +308,59 @@ 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 () => { diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index ef1c9077a6..50b159e5d9 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -64,6 +64,16 @@ 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' @@ -503,6 +513,8 @@ 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 = @@ -717,6 +729,17 @@ 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 @@ -829,7 +852,10 @@ export function pendingUserActionDetail( if (isActiveRunForm(message)) { return { action: 'confirmation', toolCallId: message.tool_call_id } } - if (message.needsConfirmation && message.isLoading) { + if ( + (message.needsConfirmation || (message.outOfScope && !message.outOfScope.decision)) && + message.isLoading + ) { return { action: 'confirmation', toolCallId: message.tool_call_id } } } @@ -1132,6 +1158,58 @@ export async function processToolCall({ } } + // 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. @@ -1220,6 +1298,7 @@ export async function processToolCall({ toolId: toolCall.id }) logToolOutcome(settledInsideTool ?? 'ok') + if (writes && !settledInsideTool) workingScope?.recordWrite(writtenPaths(args)) toolCallbacks.setToolStatus(toolCall.id, { isLoading: false, isStreamingArguments: false @@ -1238,7 +1317,7 @@ export async function processToolCall({ const toAdd = { role: 'tool' as const, tool_call_id: toolCall.id, - content: folderInstructions ? `${result}\n\n${folderInstructions.text}` : result + content: [result, scopeNote, folderInstructions?.text].filter(Boolean).join('\n\n') } return toAdd } catch (err) { @@ -1318,6 +1397,9 @@ export interface Tool { schemaFor?: (helpers: any) => Promise /** 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. */ @@ -1483,6 +1565,16 @@ export interface ToolCallbacks { onReasoningStart?: () => void requestConfirmation?: (toolId: string, toolName?: string) => Promise 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 + /** 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 diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts index d0f14e1f52..d643b07e2c 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts @@ -79,6 +79,16 @@ 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), diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.ts b/frontend/src/lib/components/copilot/chat/toolGroups.ts index 5c0a8c2e1e..d87bc9acb5 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.ts @@ -114,6 +114,7 @@ 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. diff --git a/frontend/src/lib/components/copilot/chat/workingInOptions.svelte.ts b/frontend/src/lib/components/copilot/chat/workingInOptions.svelte.ts new file mode 100644 index 0000000000..0554b84e6b --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workingInOptions.svelte.ts @@ -0,0 +1,36 @@ +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) + } + } +} diff --git a/frontend/src/lib/components/copilot/chat/workingScope.test.ts b/frontend/src/lib/components/copilot/chat/workingScope.test.ts new file mode 100644 index 0000000000..fc608ccf88 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workingScope.test.ts @@ -0,0 +1,42 @@ +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) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/workingScope.ts b/frontend/src/lib/components/copilot/chat/workingScope.ts new file mode 100644 index 0000000000..30ae5becc7 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workingScope.ts @@ -0,0 +1,250 @@ +import { logFeatureUsage } from '$lib/utils/featureUsage' + +/** + * Working in: the owner roots, `f/` or `u/`, 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 }) +} diff --git a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts index d9ff62d8e3..0ab9b026c3 100644 --- a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts +++ b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts @@ -816,6 +816,7 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender { this.#answer(confirmed) } + handleScopeDecision = () => {} hasPendingRunForm = false isRunFormPending = () => false diff --git a/frontend/src/lib/components/home/HomeFolderBadge.svelte b/frontend/src/lib/components/home/HomeFolderBadge.svelte new file mode 100644 index 0000000000..7014fe62a0 --- /dev/null +++ b/frontend/src/lib/components/home/HomeFolderBadge.svelte @@ -0,0 +1,75 @@ + + + +{#if row && badge} + + +
e.stopPropagation()}> + + {#snippet trigger()} + + {/snippet} + {#snippet content()} + {#if row.instructions.length} +
+

Instructions

+ {#each row.instructions as path (path)} +

{path}

+ {/each} +
+ {/if} + {#if row.skills.length} +
+

Skills

+ {#each row.skills as path (path)} +

{path}

+ {/each} +
+ {/if} + {#if row.mcpServers.length} +
+

MCP servers

+ {#each row.mcpServers as path (path)} +

{path}

+ {/each} +
+ {/if} +

{scopeRule(root)}

+ + {/snippet} +
+
+{/if} diff --git a/frontend/src/lib/components/home/TreeOwnerRow.svelte b/frontend/src/lib/components/home/TreeOwnerRow.svelte index 29a055fa59..1339639af9 100644 --- a/frontend/src/lib/components/home/TreeOwnerRow.svelte +++ b/frontend/src/lib/components/home/TreeOwnerRow.svelte @@ -20,6 +20,8 @@ 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 { @@ -30,7 +32,8 @@ indent = 0, toggleLabel, detail, - actions + actions, + trailing }: Props = $props() @@ -69,9 +72,14 @@
+ {#if trailing} +
+ {@render trailing()} +
+ {/if}