fix: use the session's AI config in session editor tabs (#12593)

* fix: AI features in session editor tabs use the session's AI config

* fix: hide the completion toggle until the session's AI config loads
This commit is contained in:
AlexRV12
2026-11-23 21:27:27 +01:00
committed by GitHub
parent 1fe3704515
commit 3ceff81e72
28 changed files with 246 additions and 81 deletions
@@ -7,7 +7,7 @@
import TestConnection from './TestConnection.svelte'
import TestAiKey from './copilot/TestAIKey.svelte'
import { aiResourceProvider } from './copilot/aiResourceProvider'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './copilot/chat/aiChatManagerContext'
import Popover from './meltComponents/Popover.svelte'
import Button from './common/button/Button.svelte'
import { Loader2 } from 'lucide-svelte'
@@ -60,6 +60,8 @@
onSynced = undefined
}: Props = $props()
const aiChat = getAiChatManager()
let aiProvider = $derived(aiResourceProvider(resourceType, args))
let schema = $state(emptySchema())
@@ -225,7 +227,7 @@
{aiProvider}
workspace={workspace ?? $operatingWorkspace}
resourceValue={args}
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
model={aiChat.aiInfo?.aiModels.find((m) => m.provider === aiProvider)?.model}
/>
{/if}
{#if resourceType == 'postgresql'}
+16 -4
View File
@@ -15,7 +15,9 @@
import type { Script } from '$lib/gen'
import Select from './select/Select.svelte'
import type { DiffAiReview, DiffVersionOption } from './diff_drawer'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
import { untrack } from 'svelte'
import AiReview from './deploymentRequest/AiReview.svelte'
import type { ReviewScope } from './deploymentRequest/aiReview'
@@ -61,9 +63,15 @@
interface Props {
restoreDeployed?: () => Promise<void>
isFlow?: boolean
/** The session's chat manager, for a session editor view that mounts this drawer outside
* the session's context. */
aiChat?: AIChatManager
}
let { restoreDeployed = undefined, isFlow = false }: Props = $props()
let { restoreDeployed = undefined, isFlow = false, aiChat: sessionChat }: Props = $props()
const aiChat = untrack(() => sessionChat) ?? getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let data:
| {
@@ -386,11 +394,15 @@
<Drawer bind:this={diffViewer} size="1200px" on:close>
<DrawerContent title="Diff" on:close={diffViewer.closeDrawer}>
<div class="flex flex-col gap-4 h-full">
{#if data && aiReviewScope && $copilotInfo.enabled}
{#if data && aiReviewScope && aiInfo?.enabled}
<div class="max-h-[40vh] overflow-y-auto shrink-0">
<!-- A new diff is a new review: a result never carries over to it. -->
{#key aiReviewScope}
<AiReview scope={aiReviewScope} source="draft_diff" />
<AiReview
scope={aiReviewScope}
source="draft_diff"
info={aiChat.loadedSessionAiTarget?.info}
/>
{/key}
</div>
{/if}
@@ -17,7 +17,7 @@
import TestConnection from './TestConnection.svelte'
import TestAiKey from './copilot/TestAIKey.svelte'
import { aiResourceProvider, isTokenVertexResource } from './copilot/aiResourceProvider'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './copilot/chat/aiChatManagerContext'
import GfmMarkdown from './GfmMarkdown.svelte'
import TestTriggerConnection from './triggers/TestTriggerConnection.svelte'
import GitHubAppIntegration from './GitHubAppIntegration.svelte'
@@ -94,6 +94,8 @@
onCredentialStored
}: Props = $props()
const aiChat = getAiChatManager()
let ws = $derived(workspace ?? $operatingWorkspace)
let aiProvider = $derived(aiResourceProvider(resource_type, args))
@@ -325,7 +327,7 @@
{aiProvider}
workspace={ws}
resourceValue={args}
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
model={aiChat.aiInfo?.aiModels.find((m) => m.provider === aiProvider)?.model}
/>
{/if}
{#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)}
@@ -4,7 +4,7 @@
import { slide } from 'svelte/transition'
import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { logFeatureUsage } from '$lib/utils/featureUsage'
interface Props {
@@ -19,6 +19,9 @@
const { onEditInstructions, instructions, runnableType, path }: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
const operatingWorkspace = useOperatingWorkspace()
let expanded = $state(false)
@@ -46,7 +49,7 @@
<OpenInSessionButton source={sessionSource} btnProps={{ unifiedSize }} deferToHeader />
{/snippet}
{#if $copilotInfo.workspaceDisabled}
{#if !aiInfo || aiInfo.workspaceDisabled}
<!-- The workspace hid the assistant. -->
{:else if instructions}
<div class="my-2 flex flex-col gap-1">
@@ -1,7 +1,7 @@
<script lang="ts">
import TextInput from '../text_input/TextInput.svelte'
import SettingToggle from '../itemSettings/SettingToggle.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
interface Props {
prompt?: string | undefined
@@ -10,12 +10,15 @@
let { prompt = $bindable(), type = 'script' }: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// An empty prompt is stored as undefined, so the row keeps its own open state to show the field
// between turning the toggle on and typing.
let open = $state(false)
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<SettingToggle
setting="ai-prompt"
label="AI prompt"
@@ -1,15 +1,18 @@
<script lang="ts">
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { codeCompletionSessionEnabled, CODE_COMPLETION_SETTING_NAME } from '$lib/stores'
import { storeLocalSetting } from '$lib/utils'
import Toggle from '../Toggle.svelte'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
function storeSetting() {
storeLocalSetting(CODE_COMPLETION_SETTING_NAME, $codeCompletionSessionEnabled.toString())
}
</script>
{#if $copilotInfo.enabled && $copilotInfo.codeCompletionModel}
{#if aiInfo?.enabled && aiInfo.codeCompletionModel}
<Toggle
size="xs"
bind:checked={$codeCompletionSessionEnabled}
@@ -18,7 +21,7 @@
}}
options={{ right: 'AI code completion' }}
/>
{:else}
{:else if aiInfo}
<Toggle
disabled
size="xs"
@@ -0,0 +1,69 @@
import { afterEach, expect, it, vi } from 'vitest'
import { flushSync, mount, tick, unmount } from 'svelte'
import type { AIConfig } from '$lib/gen'
import { loadWorkspaceCopilotInfo, setCopilotInfo } from '$lib/aiStore'
import { AIChatManager } from './chat/AIChatManager.svelte'
import CronGen from './CronGen.svelte'
import { getNonStreamingMetadataCompletion } from './lib'
vi.mock('$app/navigation', () => ({
goto: vi.fn(),
afterNavigate: vi.fn(),
beforeNavigate: vi.fn()
}))
vi.mock('monaco-editor', () => ({ Selection: class Selection {} }))
vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() }))
vi.mock('./lib', async (importOriginal) => ({
...(await importOriginal<typeof import('./lib')>()),
getNonStreamingMetadataCompletion: vi.fn(async () => '0 0 * * 1')
}))
const CONFIGS: Record<string, AIConfig> = {
staging: {
providers: { anthropic: { resource_path: 'u/admin/a', models: ['claude-x'] } },
default_model: { provider: 'anthropic', model: 'claude-x' }
},
fork: {
providers: { mistral: { resource_path: 'u/admin/m', models: ['fork-z'] } },
default_model: { provider: 'mistral', model: 'fork-z' }
}
}
vi.mock('$lib/gen', async (importOriginal) => ({
...(await importOriginal<typeof import('$lib/gen')>()),
WorkspaceService: {
getCopilotInfo: async ({ workspace }: { workspace: string }) => CONFIGS[workspace]
}
}))
let component: ReturnType<typeof mount> | undefined
afterEach(() => component && unmount(component))
it("a generator in a session's editor sends with the session's workspace, not the tab's", async () => {
// The tab's copy holds staging; the session works in its fork.
setCopilotInfo(CONFIGS.staging)
const manager = new AIChatManager()
manager.isSessionChat = true
manager.workspaceResolver = () => 'fork'
await loadWorkspaceCopilotInfo('fork')
component = mount(CronGen, {
target: document.body,
props: { schedule: '', cronVersion: 'v2' },
context: new Map([['aiChatManager', manager]])
})
flushSync()
document.querySelector<HTMLButtonElement>('button[title="AI Assistant"]')!.click()
await tick()
const input = document.querySelector<HTMLInputElement>(
'input[placeholder="CRON schedule description"]'
)!
input.value = 'every monday'
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new KeyboardEvent('keypress', { key: 'Enter', bubbles: true }))
await tick()
const target = vi.mocked(getNonStreamingMetadataCompletion).mock.calls[0]?.[2]
expect(target?.workspace).toBe('fork')
expect(target?.info.defaultModel?.model).toBe('fork-z')
})
@@ -6,8 +6,11 @@
import { sendUserToast } from '$lib/toast'
import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
import { copilotInfo } from '$lib/aiStore'
import { untrack } from 'svelte'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
interface Props {
schedule: string
@@ -53,7 +56,11 @@
}
]
const response = await getNonStreamingMetadataCompletion(messages, abortController)
const response = await getNonStreamingMetadataCompletion(
messages,
abortController,
aiChat.loadedSessionAiTarget
)
if (response.startsWith('ERROR:')) {
throw response.replace('ERROR:', '').trim()
@@ -78,7 +85,7 @@
})
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}>
{#snippet trigger()}
<Button
@@ -95,7 +102,7 @@
{/snippet}
{#snippet content({ close })}
<div class="border rounded-lg shadow-lg p-4 bg-surface">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex w-96">
<input
bind:this={instructionsField}
@@ -10,7 +10,10 @@
import { dfs } from '../flows/dfs'
import { yamlStringifyExceptKeys } from './utils'
import { stepInputCompletionEnabled } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let generatedContent = $state('')
let loading = $state(false)
@@ -69,7 +72,8 @@ Only output the expression, do not explain or discuss.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
} catch (err) {
if (!abortController.signal.aborted) {
@@ -81,7 +85,7 @@ Only output the expression, do not explain or discuss.`
}
export function onKeyUp(event: KeyboardEvent) {
if (!$copilotInfo.enabled || !$stepInputCompletionEnabled) {
if (!aiInfo?.enabled || !$stepInputCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -120,7 +124,7 @@ Only output the expression, do not explain or discuss.`
})
$effect(() => {
if ($copilotInfo.enabled && $stepInputCompletionEnabled && focused) {
if (aiInfo?.enabled && $stepInputCompletionEnabled && focused) {
untrack(() => {
automaticGeneration()
})
@@ -3,7 +3,8 @@
import { isInitialCode } from '$lib/script_helpers'
import { Check, Loader2, Wand2 } from 'lucide-svelte'
import { metadataCompletionEnabled } from '$lib/stores'
import { copilotInfo, getMetadataModel } from '$lib/aiStore'
import { getMetadataModel, resolveMetadataModelFor } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
import { onDestroy, untrack } from 'svelte'
import { sendUserToast } from '$lib/toast'
import { twMerge } from 'tailwind-merge'
@@ -20,6 +21,9 @@
} from '../text_input/TextInput.svelte'
import { AIBtnClasses } from './chat/AIButtonStyle'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
type PromptConfig = {
system: string
user: string
@@ -176,8 +180,11 @@ Generate a tool name for the script below:
content: config.user.replace(`{${config.placeholderName}}`, placeholderContent)
}
]
const target = aiChat.loadedSessionAiTarget
const response = await getCompletion(messages, abortController, undefined, {
forceModelProvider: getMetadataModel()
forceModelProvider: target ? resolveMetadataModelFor(target.info) : getMetadataModel(),
workspace: target?.workspace,
info: target?.info
})
generatedContent = ''
for await (const chunk of response) {
@@ -197,7 +204,7 @@ Generate a tool name for the script below:
}
if (
$copilotInfo.enabled &&
aiInfo?.enabled &&
$metadataCompletionEnabled &&
untrack(() => generateOnAppear) &&
!content &&
@@ -216,7 +223,7 @@ Generate a tool name for the script below:
$effect(() => {
active =
$copilotInfo.enabled &&
!!aiInfo?.enabled &&
$metadataCompletionEnabled &&
!content &&
(loading || focused || !!generatedContent) &&
@@ -267,7 +274,7 @@ Generate a tool name for the script below:
}
}}
onkeydown={(event) => {
if (!$copilotInfo.enabled || !$metadataCompletionEnabled) {
if (!aiInfo?.enabled || !$metadataCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -13,9 +13,12 @@
import { stepInputCompletionEnabled } from '$lib/stores'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import type { Flow } from '$lib/gen'
import { copilotInfo } from '$lib/aiStore'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { twMerge } from 'tailwind-merge'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let loading = $state(false)
interface Props {
@@ -75,7 +78,8 @@ Only return the expression without any wrapper. Do not explain or discuss.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
dispatch('setExpr', result)
@@ -90,7 +94,7 @@ Only return the expression without any wrapper. Do not explain or discuss.`
}
</script>
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<Popover
floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}
contentClasses="p-4 flex w-96"
@@ -10,7 +10,10 @@
import { autoPlacement } from '@floating-ui/core'
import { ExternalLink, HistoryIcon, Wand2 } from 'lucide-svelte'
import { createEventDispatcher } from 'svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// state
let funcDesc: string = $state('')
@@ -39,7 +42,8 @@
content: funcDesc
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
dispatch('gen', { res: res, prompt: funcDesc })
funcDesc = ''
@@ -92,7 +96,7 @@
}
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover
floatingConfig={{
middleware: [
@@ -118,7 +122,7 @@
{/snippet}
{#snippet content({ close })}
<div class="block text-primary p-4">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex flex-col gap-4">
<div class="flex w-96">
<input
@@ -5,8 +5,11 @@
import Popover from '$lib/components/meltComponents/Popover.svelte'
import { sendUserToast } from '$lib/toast'
import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
import { copilotInfo } from '$lib/aiStore'
import type { Schema } from '$lib/common'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
interface Props {
args: Record<string, any>
@@ -94,7 +97,11 @@
}
]
let response = await getNonStreamingMetadataCompletion(messages, abortController)
let response = await getNonStreamingMetadataCompletion(
messages,
abortController,
aiChat.loadedSessionAiTarget
)
// Strip markdown fences if present
response = response.trim()
@@ -118,7 +125,7 @@
})
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}>
{#snippet trigger()}
<Button
@@ -137,7 +144,7 @@
{/snippet}
{#snippet content({ close })}
<div class="border rounded-lg shadow-lg p-4 bg-surface">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex flex-col w-80 gap-2">
<textarea
bind:this={instructionsField}
@@ -5,7 +5,7 @@
import type { SupportedLanguage } from '$lib/common'
import { WandSparkles } from 'lucide-svelte'
import type { AIChatManager } from './chat/AIChatManager.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte'
import { getOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext'
import { AIBtnClasses } from './chat/AIButtonStyle'
@@ -30,6 +30,9 @@
moduleId?: string
} = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// The enclosing editor's "Open in AI session" hand-off (ScriptEditor for a
// standalone script, FlowBuilder for a step).
const handoff = getOpenInSessionHandoff()
@@ -74,7 +77,7 @@
const sessionScopedManager = getContext<AIChatManager | undefined>('aiChatManager')
</script>
{#if SUPPORTED_LANGUAGES.has(lang) && !$copilotInfo.workspaceDisabled}
{#if SUPPORTED_LANGUAGES.has(lang) && aiInfo && !aiInfo.workspaceDisabled}
{#if sessionScopedManager}
<Button
title="Fix the failing run in this chat"
@@ -1,5 +1,5 @@
<script lang="ts">
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { ScriptService, type ListableScript } from '$lib/gen'
import { Wand2, Loader2 } from 'lucide-svelte'
@@ -29,8 +29,11 @@
disableAi = false,
filteredItems = $bindable([])
}: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let prefilteredItems = $derived(scripts ?? [])
let aiHidden = $derived(disableAi || $copilotInfo.workspaceDisabled)
let aiHidden = $derived(disableAi || !aiInfo || aiInfo.workspaceDisabled)
const dispatch = createEventDispatcher()
@@ -14,12 +14,15 @@
import { stepInputCompletionEnabled } from '$lib/stores'
import type { SchemaProperty } from '$lib/common'
import FlowCopilotInputsModal from './FlowCopilotInputsModal.svelte'
import { copilotInfo } from '$lib/aiStore'
import Button from '../common/button/Button.svelte'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { Check, Wand2 } from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import { newFlowInputOf, newFlowInputsInstruction } from './stepInputFlowInputs'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let generatedContent = $state('')
let loading = $state(false)
@@ -119,7 +122,8 @@ Only return the expression without any wrapper.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
const newInput = newFlowInputOf(generatedContent, pickableProperties)
@@ -137,7 +141,7 @@ Only return the expression without any wrapper.`
}
export function onKeyUp(event: KeyboardEvent) {
if (!$copilotInfo.enabled || !$stepInputCompletionEnabled) {
if (!aiInfo?.enabled || !$stepInputCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -206,7 +210,7 @@ Only return the expression without any wrapper.`
}
</script>
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<FlowCopilotInputsModal
on:confirmed={async () => {
createFlowInput()
@@ -14,7 +14,6 @@
import { logStepInputFill } from './stepInputFillTelemetry'
import { Check, ExternalLink, Loader2, Wand2 } from 'lucide-svelte'
import { stepInputCompletionEnabled } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import type { SchemaProperty, Schema } from '$lib/common'
import FlowCopilotInputsModal from './FlowCopilotInputsModal.svelte'
@@ -22,6 +21,10 @@
import { twMerge } from 'tailwind-merge'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { newFlowInputOf, newFlowInputsInstruction } from './stepInputFlowInputs'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let loading = $state(false)
interface Props {
@@ -101,7 +104,8 @@ input_name2: expression2
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
parsedInputs = generatedContent.split('\n').map((x) => x.split(': '))
@@ -191,7 +195,7 @@ input_name2: expression2
</script>
<div class="flex flex-row justify-end">
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<FlowCopilotInputsModal
on:confirmed={async () => {
createFlowInputs()
@@ -225,7 +229,7 @@ input_name2: expression2
Fill inputs
{/if}
</Button>
{:else if !$copilotInfo.workspaceDisabled}
{:else if aiInfo && !aiInfo.workspaceDisabled}
<Popover
floatingConfig={{
placement: 'top-end'
@@ -248,7 +252,7 @@ input_name2: expression2
{#snippet content({ close })}
<div class="p-4">
<p class="text-sm">
{#if !$copilotInfo.enabled}
{#if !aiInfo?.enabled}
Enable Windmill AI in the{' '}
<a
href="/workspace_settings?tab=ai"
@@ -3,7 +3,7 @@
import { FlaskConical, FormInput, LayoutDashboard, MessageSquare, Pen } from 'lucide-svelte'
import { resource } from 'runed'
import { goto } from '$lib/navigation'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import AgentEvalsModal from '$lib/components/flows/content/AgentEvalsModal.svelte'
import AgentUsePanel from '$lib/components/flows/content/AgentUsePanel.svelte'
import { SlackAgentsService } from '$lib/gen'
@@ -77,6 +77,9 @@
openConversation = undefined
}: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// Every workspace-scoped call below and in the drawers this page opens (the summary's save,
// permissions, history) targets `workspace`, not the nav store: a session shows the agent of its
// own workspace, which a fork makes a different one.
@@ -394,7 +397,7 @@
bind:this={host}
{path}
workspace={ws}
enableAi={$copilotInfo.enabled}
enableAi={!!aiInfo?.enabled}
view
onOpenConfig={() => configModal?.open()}
onRunStarted={embedded || pendingRun ? runStarted : undefined}
@@ -23,7 +23,7 @@
import DefaultScriptsInner from '$lib/components/DefaultScriptsInner.svelte'
import GenAiQuick from './GenAiQuick.svelte'
import FlowToplevelNode from '../pickers/FlowToplevelNode.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import {
canHavePreprocessor,
canHaveTrigger,
@@ -71,6 +71,9 @@
refreshCount = 0
}: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
if ($operatingWorkspace && cachedOwners?.[$operatingWorkspace]) {
owners = cachedOwners[$operatingWorkspace]
}
@@ -119,7 +122,7 @@
}
async function onGenerate() {
if (!$copilotInfo.enabled) {
if (!aiInfo?.enabled) {
sendUserToast(
'Windmill AI is not enabled, you can activate it in the workspace settings',
true
@@ -259,7 +262,8 @@
// on indices that render nothing.
let showAiRows = $derived(
!disableAi &&
!$copilotInfo.workspaceDisabled &&
!!aiInfo &&
!aiInfo.workspaceDisabled &&
!composeOnlyFlows &&
funcDesc?.length > 0 &&
kind != 'failure' &&
@@ -23,7 +23,6 @@ import { findNextAvailablePath } from '$lib/path'
import type { ExtendedOpenFlow } from './types'
import { emptySchema, type StateStore } from '$lib/utils'
import { loadStoredConfig } from '../aiProviderStorage'
import { copilotInfo } from '$lib/aiStore'
import { stepSettingDefaults } from './flowStepSettings'
import type { InlineScript, InsertKind } from '$lib/components/graph/graphBuilder.svelte'
import {
@@ -510,7 +509,7 @@ export async function createNewModule(
workspace
)
} else if (kind == 'forloop') {
;[module, state] = await createLoop(module.id, !disableAi && get(copilotInfo).enabled)
;[module, state] = await createLoop(module.id, !disableAi)
} else if (kind == 'whileloop') {
;[module, state] = await createWhileLoop(module.id)
} else if (kind == 'branchone') {
@@ -53,6 +53,7 @@
moduleToStructureNode
} from '$lib/components/graph/flowStructure'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
const operatingWorkspace = useOperatingWorkspace()
@@ -112,6 +113,10 @@
flowHasChanged
}: Props = $props()
const aiChat = getAiChatManager()
// The session workspace's config in a session pane, so new loops match the IteratorGen shown.
const aiOff = $derived(disableAi || !aiChat.aiInfo?.enabled)
const { customUi, selectionManager, history, flowStateStore, flowStore, pathStore, opWorkspace } =
getContext<FlowEditorContext>('FlowEditorContext')
@@ -157,7 +162,7 @@
inlineScript,
agentPath,
opWs,
disableAi
aiOff
)
}
@@ -174,14 +179,7 @@
const agentMod = findModuleInFlow(flowStore.val.value, agentId)
const agentValue = agentMod?.value as { tools?: AgentTool[] } | undefined
if (agentValue) {
const id = await insertAgentTool(
flowStore,
flowStateStore,
agentValue,
detail,
opWs,
disableAi
)
const id = await insertAgentTool(flowStore, flowStateStore, agentValue, detail, opWs, aiOff)
// Reveal the new tool's config right away — in modal (unanchored) panel mode its editor
// is otherwise hidden behind the graph.
if (id) selectionManager.selectId(id, { openPanel: true })
@@ -211,7 +209,7 @@
inlineScript,
toolKind,
opWs,
disableAi
aiOff
)
}
@@ -61,7 +61,7 @@
import { captureScale, MAX_IMAGE_EDGE } from '../copilot/chat/imageUtils'
import { rawAppLintStore } from './lintStore'
import { dbSchemas, userStore } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { useActingUser } from '$lib/actingUser.svelte'
import { appPreviewOnBehalfOf } from '$lib/utils/previewOnBehalfOf'
import RawAppSdkConsent from './RawAppSdkConsent.svelte'
@@ -280,6 +280,9 @@
draftBaseVersion = undefined
}: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// Workspace this editor operates on: the session's acting workspace when
// embedded in a session preview (autosaveWorkspace), else the navigation
// workspace. Deploy/save/background-runner must target it, not the navigation one.
@@ -2990,7 +2993,7 @@ addEventListener('message', function (e) {
>
{bundlerType}
</Button>
{/if}
{/if}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Button
variant="subtle"
@@ -24,6 +24,7 @@
import { Alert, Badge } from '$lib/components/common'
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
import { loadCopilot } from '$lib/components/copilot/loadCopilot'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { BUILDER_FRAMEWORK_TEMPLATES, FRAMEWORK_TEMPLATES } from './templates'
import { conformBuilderAppPolicy } from './builderAppPolicy'
import type { Runnable } from './rawAppPolicy'
@@ -278,17 +279,27 @@
// `enabled` alone cannot tell "no providers" from "not loaded yet" and the modal
// would announce AI as unconfigured while it is merely unknown. Gate on the
// config describing opWs, and load it here so the claim owns its own evidence.
const aiConfigLoaded = $derived(!!opWs && $copilotWorkspace === opWs)
const isAiEnabled = $derived(aiConfigLoaded && $copilotInfo.enabled)
const aiChat = getAiChatManager()
const aiInfo = $derived(
aiChat.isSessionChat
? aiChat.aiInfo
: !!opWs && $copilotWorkspace === opWs
? $copilotInfo
: undefined
)
const aiConfigLoaded = $derived(!!aiInfo)
const isAiEnabled = $derived(!!aiInfo?.enabled)
$effect(() => {
if (open && opWs && !aiConfigLoaded) {
if (open && opWs && $copilotWorkspace !== opWs) {
loadCopilot(opWs)
}
})
// With AI turned off for the workspace there is nothing to choose between.
const aiOffered = $derived(!$copilotInfo.workspaceDisabled)
const aiOffered = $derived(
aiChat.isSessionChat ? !!aiInfo && !aiInfo.workspaceDisabled : !$copilotInfo.workspaceDisabled
)
const canStart = $derived(
!!templates[selectedTemplateIndex] && !newSchemaAlreadyExists && rolesSettled && accessSettled
@@ -73,7 +73,7 @@
</script>
{#if cell.saved.val}
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} isFlow />
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} aiChat={runtime.manager} isFlow />
{/if}
<SessionEditorTarget
{runtime}
@@ -2,7 +2,6 @@
import { setContext, untrack } from 'svelte'
import { Loader2 } from 'lucide-svelte'
import { enterpriseLicense } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import { resource } from 'runed'
import { Button } from '$lib/components/common'
import { lookupPageItem } from './pageItemLookup'
@@ -34,6 +33,8 @@
reloadNonce?: number
} = $props()
const aiInfo = $derived(runtime.manager.aiInfo)
// Mounted in the preview panel, outside the chat's own subtree: chat-aware components
// below would otherwise resolve the app-wide manager rather than this session's.
// Captured at init, as SessionEditorTarget does: descendants rely on its presence.
@@ -184,7 +185,7 @@
layout="pane"
fixedTarget={{ path: item.path, workspace: workspaceId }}
owns={() => false}
enableAi={$copilotInfo.enabled}
enableAi={!!aiInfo?.enabled}
onClose={closeTab}
onRenamed={(_, to) => onSaved(to)}
onSummary={(summary) => runtime.previewTabs.stampAgentTab(item, summary)}
@@ -1,6 +1,6 @@
<script lang="ts">
import { resource } from 'runed'
import { onDestroy, tick, untrack } from 'svelte'
import { onDestroy, setContext, tick, untrack } from 'svelte'
import { Loader2, Save, Workflow } from 'lucide-svelte'
import PipelineGraphEditor from '$lib/components/assets/AssetGraph/PipelineGraphEditor.svelte'
import PipelineTriggerEditors from '$lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte'
@@ -27,6 +27,7 @@
import PipelineDeployTriggersModal from '$lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte'
import AutosaveIndicator from '$lib/components/AutosaveIndicator.svelte'
import { Button } from '$lib/components/common'
import { setOperatingWorkspace } from '../operatingWorkspace.svelte'
import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte'
import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths'
import type { DeployResult } from '$lib/utils_workspace_deploy'
@@ -59,6 +60,10 @@
// register the pipeline tools (build_pipeline_node / edit_pipeline_node) on the
// wrong chat — leaving this session's chat unable to build canvas nodes.
const aiChatManager = runtime.manager
// For the same reason, the AI features of the nodes' editors would read the tab's AI settings,
// which may be another workspace's, rather than this session's.
setContext('aiChatManager', aiChatManager)
setOperatingWorkspace(() => workspaceId)
// Only the foreground tab of the foreground session runs the live-badge poll.
const engaged = $derived(isActiveSession && active)
@@ -362,7 +362,7 @@
</script>
{#if cell.saved.val}
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} />
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} aiChat={runtime.manager} />
{/if}
<SessionEditorTarget
{runtime}
@@ -79,7 +79,7 @@
</script>
{#if cell.saved.val}
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} />
<DiffDrawer bind:this={diffDrawer} {restoreDeployed} aiChat={runtime.manager} />
{/if}
<SessionEditorTarget
{runtime}