From 00e354dade598ed9f434576ef616b53e0cf6b543 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:46:39 +0100 Subject: [PATCH 01/26] fix: match flow step pickers to the role and keep picked settings (#12654) * fix: hide hub and inline code from roles that cannot add them to flows * fix: list scripts of the requested kind for roles without code * fix: keep trigger and approval settings of empty step picks * test: run the operator flow tests one at a time --- .../tests/operator_builder_flows.rs | 50 +++++ backend/windmill-api-scripts/src/scripts.rs | 17 +- .../flows/content/FlowInputs.svelte | 176 ++++++++++-------- .../flows/content/FlowModuleWrapper.svelte | 2 +- .../components/triggers/CaptureSection.svelte | 47 +++-- 5 files changed, 183 insertions(+), 109 deletions(-) diff --git a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs index 6bed27eca5..e204ab8e52 100644 --- a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs +++ b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs @@ -1,7 +1,10 @@ use serde_json::json; +use serial_test::serial; use sqlx::{Pool, Postgres}; use windmill_test_utils::*; +/// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id +/// alone, so parallel tests under this same id read each other's rights. const WS: &str = "test-workspace"; fn operator_client() -> reqwest::Client { @@ -82,6 +85,7 @@ fn inline_code_flow(path: &str) -> serde_json::Value { /// already deployed and nothing more, and the endpoints that author code stay shut whether or not /// it is granted. #[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] async fn test_operator_builder_flows_boundary(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; @@ -477,3 +481,49 @@ async fn check_builder_agents( Ok(()) } + +/// Each slot of a flow picks scripts of its own kind. A role without `code` gets the kind it asks +/// for, preprocessors without a main included, and still no library. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_operator_lists_scripts_of_the_requested_kind( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + let c = operator_client(); + + add_script(&db, 5001, "u/operator/action", "operator").await?; + add_script(&db, 5002, "u/operator/library", "operator").await?; + add_script(&db, 5003, "u/operator/prep", "operator").await?; + sqlx::query( + "UPDATE script SET auto_kind = 'lib', + kind = CASE WHEN hash = 5003 THEN 'preprocessor' ELSE kind END + WHERE hash IN (5002, 5003)", + ) + .execute(&db) + .await?; + + for (query, expected) in [ + ("", vec!["u/operator/action"]), + ("&kinds=preprocessor", vec!["u/operator/prep"]), + ( + "&kinds=script,preprocessor", + vec!["u/operator/action", "u/operator/prep"], + ), + ] { + let scripts: Vec = c + .get(format!("{api}/scripts/list?path_start=u/operator/{query}")) + .send() + .await? + .error_for_status()? + .json() + .await?; + let mut paths: Vec<&str> = scripts.iter().filter_map(|s| s["path"].as_str()).collect(); + paths.sort(); + assert_eq!(paths, expected, "scripts listed for `{query}`"); + } + Ok(()) +} diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index f8159c22eb..e063874533 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -194,7 +194,7 @@ async fn list_scripts( Query(pagination): Query, Query(lq): Query, ) -> JsonResult> { - // A role that cannot write code lists only what it can run: no libraries, no drafts. + // A role that cannot write code lists only what it can run or compose: no libraries, no drafts. let cannot_code = !windmill_common::roles::caller_capabilities(&db, &w_id, &authed) .await? .code; @@ -259,16 +259,19 @@ async fn list_scripts( .limit(per_page) .clone(); - let lowercased_kinds: Option> = lq + let mut lowercased_kinds: Option> = lq .kinds .map(|x| x.split(",").map(&str::to_lowercase).collect()); - if (!lq.include_without_main.unwrap_or(false) + if cannot_code { + lowercased_kinds.get_or_insert_with(|| vec!["script".to_string()]); + // A preprocessor has no main, so it is a 'lib' that a composed flow can still use. + sqlb.and_where("(o.auto_kind IS NULL OR o.auto_kind <> 'lib' OR o.kind = 'preprocessor')"); + } else if !lq.include_without_main.unwrap_or(false) && lowercased_kinds .as_ref() .map(|x| !x.contains(&"preprocessor".to_string())) - .unwrap_or(true)) - || cannot_code + .unwrap_or(true) { // only include scripts that have a runnable entrypoint. Use a // deny-list: anything that isn't a 'lib' (library script without @@ -325,9 +328,7 @@ async fn list_scripts( ); } } - if cannot_code { - sqlb.and_where_eq("kind", quote("script")); - } else if let Some(lowercased_kinds) = lowercased_kinds { + if let Some(lowercased_kinds) = lowercased_kinds { let safe_kinds = lowercased_kinds .into_iter() .map(sql_builder::quote) diff --git a/frontend/src/lib/components/flows/content/FlowInputs.svelte b/frontend/src/lib/components/flows/content/FlowInputs.svelte index 41d860530a..7b72cac858 100644 --- a/frontend/src/lib/components/flows/content/FlowInputs.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputs.svelte @@ -12,12 +12,16 @@ import { Check, Code, Zap } from 'lucide-svelte' import SuspendDrawer from './SuspendDrawer.svelte' import { defaultScripts } from '$lib/stores' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { defaultScriptLanguages, processInlineLangs } from '$lib/scripts' import type { SupportedLanguage } from '$lib/common' import DefaultScripts from '$lib/components/DefaultScripts.svelte' import type { FlowBuilderWhitelabelCustomUi } from '$lib/components/custom_ui' import { canHavePreprocessor } from '$lib/script_helpers' + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') + interface Props { failureModule: boolean preprocessorModule: boolean @@ -51,6 +55,13 @@ ) let pick_existing: 'workspace' | 'hub' = $state('hub') let filter = $state('') + // The server adds a hub path only for a role that has code, whatever its flows level. + let showHub = $derived($roleCaps.code) + + // The pickers return no reliable kind, and the step's trigger or approval settings depend on it. + function pick(e: CustomEvent) { + dispatch('pick', { ...e.detail, kind: scriptKind }) + } let langs = $derived( processInlineLangs(undefined, $defaultScripts?.order ?? Object.keys(defaultScriptLanguages)) @@ -220,90 +231,93 @@ > {/if} {/if} -

-
- Inline new {scriptKind == 'script' ? 'action' : scriptKind} +
+ Inline new {scriptKind == 'script' ? 'action' : scriptKind} + script + + Embed {scriptKind == 'script' ? 'action' : scriptKind} script directly inside + a flow instead of saving the script into your workspace for reuse. You can always save an + inline script to your workspace later. + +
+ +

+ {#if noEditor} +
Pick a summary first, it will be used to create a separate file whose name will be + derived from the summary
- script - - Embed {scriptKind == 'script' ? 'action' : scriptKind} script directly inside - a flow instead of saving the script into your workspace for reuse. You can always save an inline - script to your workspace later. - + +
+ {/if} +
+ {#each langs.filter((lang) => customUi?.languages == undefined || customUi?.languages?.includes(lang?.[1])) as [label, lang] (lang)} + {#if displayLang(lang, scriptKind)} + { + dispatch('new', { + language: lang == 'docker' ? 'bash' : lang, + kind: scriptKind, + subkind: + lang == 'docker' ? 'docker' : preprocessorModule ? 'preprocessor' : 'flow', + summary + }) + }} + /> + {/if} + {/each}
- - - {#if noEditor} -
Pick a summary first, it will be used to create a separate file whose name will be derived - from the summary
- -
- {/if} -
- {#each langs.filter((lang) => customUi?.languages == undefined || customUi?.languages?.includes(lang?.[1])) as [label, lang] (lang)} - {#if displayLang(lang, scriptKind)} + + {#if !failureModule && !preprocessorModule && customUi?.aiSandbox != false} +

AI Sandbox

+
{ dispatch('new', { - language: lang == 'docker' ? 'bash' : lang, - kind: scriptKind, - subkind: lang == 'docker' ? 'docker' : preprocessorModule ? 'preprocessor' : 'flow', + language: 'bun', + kind, + subkind: 'claudesandbox', summary }) }} /> - {/if} - {/each} -
- - {#if !failureModule && !preprocessorModule && customUi?.aiSandbox != false} -

AI Sandbox

-
- { - dispatch('new', { - language: 'bun', - kind, - subkind: 'claudesandbox', - summary - }) - }} - /> - { - dispatch('new', { - language: 'bun', - kind, - subkind: 'pisandbox', - summary - }) - }} - /> -
+ { + dispatch('new', { + language: 'bun', + kind, + subkind: 'pisandbox', + summary + }) + }} + /> +
+ {/if} {/if}

{#if preprocessorModule} - - {:else if pick_existing == 'hub'} - + + {:else if showHub && pick_existing == 'hub'} + {:else} - - + + {#if showHub} + + {/if} {/if} {/if} diff --git a/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte b/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte index af1ff81eaa..20d4fb6968 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte @@ -108,7 +108,7 @@ summary, flowModule.id, hash, - undefined, + kind, opWorkspace?.() ) diff --git a/frontend/src/lib/components/triggers/CaptureSection.svelte b/frontend/src/lib/components/triggers/CaptureSection.svelte index 4fa2fab5fb..2df509f95c 100644 --- a/frontend/src/lib/components/triggers/CaptureSection.svelte +++ b/frontend/src/lib/components/triggers/CaptureSection.svelte @@ -36,12 +36,13 @@ import { FlaskConical } from 'lucide-svelte' import Alert from '../common/alert/Alert.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() // Saving a capture config is a trigger write the server refuses to a withdrawn operator, so // every capture kind locks here rather than each editor passing it down. const triggerLock = useTriggerLock() + const roleCaps = useRoleCapabilities() interface Props { disabled?: boolean | undefined @@ -67,6 +68,9 @@ displayAlert = false }: Props = $props() + // The button inserts an inline script, which the server refuses in a compose-only role's flow. + const canAddInlinePreprocessor = $derived(!captureInfo.isFlow || $roleCaps.flows !== 'compose') + const testKind: 'preprocessor' | 'main' = $derived(hasPreprocessor ? 'preprocessor' : 'main') const dispatch = createEventDispatcher<{ @@ -482,7 +486,8 @@
- Add a preprocessor to use the raw payload data in the flow. + Add a preprocessor{canAddInlinePreprocessor ? '' : ' from the flow graph'} to use + the raw payload data in the flow.
-
- -
+ {#if canAddInlinePreprocessor} +
+ +
+ {/if}
{/if} From 29383dd814677465f98a02038b2fd2d83e117edd Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:46:55 +0100 Subject: [PATCH 02/26] fix: let the attached flow step panel scroll (#12652) --- .../lib/components/flows/FlowEditor.svelte | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/frontend/src/lib/components/flows/FlowEditor.svelte b/frontend/src/lib/components/flows/FlowEditor.svelte index 39c99f38cb..21104c7551 100644 --- a/frontend/src/lib/components/flows/FlowEditor.svelte +++ b/frontend/src/lib/components/flows/FlowEditor.svelte @@ -325,6 +325,13 @@ aiChatManager.changeMode(AIMode.NAVIGATOR) } }) + + // The docked scroller outlives the selection, so without this a step opens at the scroll + // position of the one selected before it. + function scrollToTopOnSelect(node: HTMLElement) { + selectionManager.getSelectedId() + node.scrollTop = 0 + } {#snippet panelBody()} @@ -435,9 +442,10 @@ {#if panelMode === 'docked'} - + {#if loading}
@@ -445,23 +453,21 @@
- {:else if modalPanel} + {:else}
- {#if detachClaims === 0} + {#if modalPanel && detachClaims === 0}
{/if} -
+
{@render panelBody()}
- {:else} - {@render panelBody()} {/if} {/if} From 772c0c30f1f47a84b2fd7ec6456882482c0759c5 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Wed, 25 Nov 2026 15:41:21 +0100 Subject: [PATCH 03/26] feat: pass MCP image results to the AI chat model as images (#12660) --- .../copilot/chat/AIChatManager.svelte.ts | 3 +- .../copilot/chat/AIChatManager.test.ts | 4 +- .../copilot/chat/ToolExecutionDisplay.svelte | 2 +- .../components/copilot/chat/global/core.ts | 5 +- .../copilot/chat/global/mcpTools.test.ts | 36 ++++- .../copilot/chat/global/mcpTools.ts | 125 +++++++++++++++--- .../components/copilot/chat/shared.test.ts | 7 +- .../src/lib/components/copilot/chat/shared.ts | 24 ++-- 8 files changed, 173 insertions(+), 33 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 6055705c8a..82461684cc 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -40,6 +40,7 @@ import { createJobUpdateReader, deriveChatJobStatus, pendingToolImagesMessage, + type ToolImage, trimJob } from './shared' import type { @@ -795,7 +796,7 @@ export class AIChatManager implements ChatViewHost { /** Images buffered by tools (e.g. take_screenshot) during the current tool batch, * keyed by toolId. Drained by appendPendingToolImages into a follow-up user message * after the batch. Cleared at each turn start so an aborted batch can't leak. */ - private pendingToolImages = new Map() + private pendingToolImages = new Map() /** Model of the most recent loop iteration, recorded via onBeforeIteration. * The selector stays switchable mid-flight, so when a request fails neither * the send-time nor the currently-selected model necessarily names the one diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 089afb5290..8e4716d275 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -2627,8 +2627,8 @@ describe('AIChatManager queued messages', () => { { role: 'tool' as const, tool_call_id: 'shot', content: 'Screenshot attached below' } ) config.callbacks.attachToolImage('shot', { - dataUrl: 'data:image/png;base64,iVBORw0KGgo=', - name: 'shot.png' + image: { dataUrl: 'data:image/png;base64,iVBORw0KGgo=', name: 'shot.png' }, + caption: 'Screenshot(s) of the app preview:' }) leavePage.forEach((fn) => fn()) return { diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 684c9c4dee..63ef5d1ef8 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -403,7 +403,7 @@
diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index ea5310231c..46d165814e 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -4830,7 +4830,10 @@ export const globalTools: SessionTool<{}>[] = [ // buffered here and flushed as a follow-up user image message once the tool batch // completes (see appendPendingToolImages). const image = await normalizeImageDataUrl(result.dataUrl) - ctx.toolCallbacks.attachToolImage?.(ctx.toolId, image) + ctx.toolCallbacks.attachToolImage?.(ctx.toolId, { + image, + caption: 'Screenshot(s) of the app preview:' + }) // The card shows the same copy the model gets; sharing the exact data URL // lets the history's blob store persist one copy for both. ctx.toolCallbacks.setToolStatus(ctx.toolId, { diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts index 30a4403746..8a95f6032a 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts @@ -22,12 +22,20 @@ vi.mock('$lib/gen', () => ({ } })) +vi.mock('$lib/aiStore', () => ({ tryGetCurrentModel: () => undefined })) + vi.mock('$lib/stores', () => ({ // Read at call time, so a test can switch accounts the way a logout does. userStore: { subscribe: (run: (v: unknown) => void) => (run({ ...session }), () => {}) } })) -import { clearMcpToolsCache, createMcpTools, loadMcpServers, type McpServer } from './mcpTools' +import { + clearMcpToolsCache, + createMcpTools, + loadMcpServers, + splitMcpResult, + type McpServer +} from './mcpTools' import { setMcpEnabled } from '$lib/components/mcp/enabledServers' const SERVERS: McpServer[] = [{ path: 'u/hugo/github_mcp' }] @@ -222,6 +230,32 @@ describe('call results', () => { expect(result.error).toBe('issue not found') }) + it('takes image blocks out of the text, and drops an oversized one whole', () => { + const small = 'iVBORw0KGgo=' + const huge = 'A'.repeat(11_000_000) + const { data, images, omitted } = splitMcpResult({ + content: [ + { type: 'text', text: 'Viewport of Blender' }, + { type: 'image', mimeType: 'image/png', data: small }, + { type: 'image', mimeType: 'image/png', data: huge } + ] + }) + expect(data).toBe('Viewport of Blender') + expect(images).toEqual([{ index: 0, mimeType: 'image/png', data: small }]) + expect(omitted).toEqual(['image 2 (image/png): larger than 8 MB']) + }) + + it('keeps structured content when images are taken out', () => { + const { data } = splitMcpResult({ + content: [ + { type: 'text', text: 'Rendered' }, + { type: 'image', mimeType: 'image/png', data: 'iVBORw0KGgo=' } + ], + structuredContent: { object_id: 'cube-17' } + }) + expect(data).toEqual({ object_id: 'cube-17' }) + }) + it('flattens text content on success', async () => { callMcpToolMock.mockResolvedValue({ content: [{ type: 'text', text: '{"number":42}' }] }) const result = await run('call_mcp_read_tool', { diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index b91df4c769..8917c6e23f 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -4,6 +4,10 @@ import { createToolDef } from '../shared' import { NONE, type SessionTool } from '../sessionCapabilities' import { enabledMcpPaths } from '$lib/components/mcp/enabledServers' import { isOwnOrSharedMcpPath, MCP_LIST_PER_PAGE, mcpViewer } from '$lib/components/mcp/ownServers' +import { MAX_ATTACHED_IMAGES, normalizeImageDataUrl, type AttachedImage } from '../imageUtils' +import { modelSupportsVision } from '../../modelConfig' +import { tryGetCurrentModel } from '$lib/aiStore' +import type { GlobalToolHelpers } from './core' /** * Access to the MCP servers the user has connected (resources of type `mcp`) @@ -20,6 +24,9 @@ export type McpServer = { path: string; editedAt?: string } const MAX_SEARCH_RESULTS = 10 const MAX_DESCRIPTION_CHARS = 1_000 const MAX_RESULT_CHARS = 20_000 +// Checked on the server's raw image, before it is decoded and downscaled: decoding +// allocates the full bitmap, so the cap has to bite first. +const MAX_IMAGE_BYTES = 8_000_000 // A server writes its own error text, and every enabled server can contribute // one, so search results are capped the same way call results are. const MAX_SERVER_ERROR_CHARS = 500 @@ -185,17 +192,72 @@ async function resolveTool( return { server, tool } } -/** Flatten the MCP content blocks into the text the model can act on. */ -function extractResultData(result: unknown): unknown { +/** `index` counts the result's image blocks, so a note names the one the server sent. */ +export type McpImage = { index: number; mimeType: string; data: string } + +/** Decoded bytes of base64 text, without decoding it. */ +function base64Size(b64: string): number { + const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0 + return Math.max(0, Math.floor((b64.length * 3) / 4) - padding) +} + +function describeImage(index: number, mimeType: string): string { + return `image ${index + 1} (${truncate(mimeType, 40)})` +} + +/** + * Split an MCP result into the data the model reads as text and the image blocks it + * is shown as images. Images never go into the text: base64 cut at the text cap is + * unreadable, so an image over the limits is dropped whole and named in `omitted`. + */ +export function splitMcpResult(result: unknown): { + data: unknown + images: McpImage[] + omitted: string[] +} { const content = (result as { content?: unknown })?.content - if (Array.isArray(content)) { - const texts = content - .filter((c) => (c as { type?: string })?.type === 'text') - .map((c) => (c as { text?: string }).text ?? '') - if (texts.length === content.length) return texts.join('\n') + const images: McpImage[] = [] + const omitted: string[] = [] + if (!Array.isArray(content)) { + const structured = (result as { structuredContent?: unknown })?.structuredContent + return { data: structured ?? content ?? result, images, omitted } } + let imageIndex = 0 + const rest = content.filter((c) => { + const block = c as { type?: string; data?: unknown; mimeType?: unknown } + if (block?.type !== 'image') return true + const index = imageIndex++ + const mimeType = typeof block.mimeType === 'string' ? block.mimeType : 'unknown type' + if (typeof block.data !== 'string' || !mimeType.startsWith('image/')) { + omitted.push(`${describeImage(index, mimeType)}: not a base64 image`) + } else if (base64Size(block.data) > MAX_IMAGE_BYTES) { + omitted.push( + `${describeImage(index, mimeType)}: larger than ${MAX_IMAGE_BYTES / 1_000_000} MB` + ) + } else if (images.length >= MAX_ATTACHED_IMAGES) { + omitted.push(`${describeImage(index, mimeType)}: over ${MAX_ATTACHED_IMAGES} images`) + } else { + images.push({ index, mimeType, data: block.data }) + } + return false + }) + const texts = rest + .filter((c) => (c as { type?: string })?.type === 'text') + .map((c) => (c as { text?: string }).text ?? '') const structured = (result as { structuredContent?: unknown })?.structuredContent - return structured ?? content ?? result + // A result that mixed in images was never read as text alone: its structured + // content is what carried the fields, so taking the images out must not drop it. + const textOnly = rest.length === content.length || structured === undefined + if (texts.length === rest.length && textOnly) return { data: texts.join('\n'), images, omitted } + return { data: structured ?? rest, images, omitted } +} + +/** What the model is told about the images a call returned, or undefined for none. */ +function imagesNote(attached: number, omitted: string[]): string | undefined { + const parts: string[] = [] + if (attached > 0) parts.push(`${attached} image(s) attached in the following message.`) + if (omitted.length > 0) parts.push(`Not shown: ${omitted.join('; ')}.`) + return parts.length > 0 ? truncate(parts.join(' '), MAX_SERVER_ERROR_CHARS) : undefined } async function executeTool( @@ -203,8 +265,9 @@ async function executeTool( server: McpServer, tool: McpToolDef, args: Record, - skippedConfirmation: boolean -): Promise { + skippedConfirmation: boolean, + canSeeImages: boolean +): Promise<{ result: string; images: AttachedImage[] }> { let raw: unknown try { raw = await ResourceService.callMcpTool({ @@ -228,7 +291,7 @@ async function executeTool( if (skippedConfirmation && status === 400 && /read-only/i.test(error)) { forgetServerTools(workspace, server.path) } - return bounded({ + const result = bounded({ success: false, ...(status ? { status } : {}), error, @@ -236,19 +299,36 @@ async function executeTool( // can self-correct on the next call without a separate schema tool. ...(status >= 400 && status < 500 ? { schema: tool.inputSchema } : {}) }) + return { result, images: [] } } - const data = extractResultData(raw) + const { data, images: rawImages, omitted } = splitMcpResult(raw) // A tool that ran but reported failure comes back as a success with isError set. if ((raw as { isError?: boolean })?.isError) { - return bounded({ + const result = bounded({ success: false, error: typeof data === 'string' ? data : JSON.stringify(data), schema: tool.inputSchema }) + return { result, images: [] } } - return bounded({ success: true, data }) + const images: AttachedImage[] = [] + for (const image of rawImages) { + const name = describeImage(image.index, image.mimeType) + // A text-only model would reject the follow-up image message and fail the turn. + if (!canSeeImages) { + omitted.push(`${name}: the current model cannot read images`) + continue + } + try { + images.push(await normalizeImageDataUrl(`data:${image.mimeType};base64,${image.data}`)) + } catch { + omitted.push(`${name}: could not be decoded`) + } + } + const note = imagesNote(images.length, omitted) + return { result: bounded({ success: true, data, ...(note ? { images: note } : {}) }), images } } /** @@ -260,6 +340,8 @@ function bounded(payload: { success: boolean data?: unknown error?: string + /** Already bounded; kept through truncation, since it says what the next message holds. */ + images?: string [k: string]: unknown }) { const full = JSON.stringify(payload) @@ -276,6 +358,7 @@ function bounded(payload: { success: payload.success, truncated: true, [payload.success ? 'data' : 'error']: text.slice(0, take), + ...(payload.images ? { images: payload.images } : {}), note: `Truncated to fit ${MAX_RESULT_CHARS} characters. Use filter or pagination parameters to narrow it.` }) take = Math.floor(take / 2) @@ -371,7 +454,7 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo confirmAction: 'run', confirmationMessage: (args: any) => `Call ${args?.tool ?? ''} on ${args?.server ?? ''}` }), - fn: async ({ args, workspace, toolId, toolCallbacks }) => { + fn: async ({ args, workspace, toolId, toolCallbacks, helpers }) => { const parsed = callMcpToolSchema.parse(args) // Marks the row with the provider it reaches. Recorded before the listing is // awaited, so an unreachable server still marks its own failure row, and taken @@ -401,17 +484,25 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo return bounded({ success: false, error }) } toolCallbacks.setToolStatus(toolId, { content: `Calling ${parsed.tool}...` }) - const result = await executeTool( + // Re-read per call: the session's model can change between turns. + const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi + const model = sessionAi ? sessionAi().model : tryGetCurrentModel() + const { result, images } = await executeTool( workspace, resolved.server, resolved.tool, parsed.arguments ?? {}, - isRead + isRead, + !model || modelSupportsVision(model.provider, model.model) ) + const caption = `Image(s) returned by ${parsed.tool} on ${resolved.server.path}:` + for (const image of images) toolCallbacks.attachToolImage?.(toolId, { image, caption }) const ok = JSON.parse(result).success === true toolCallbacks.setToolStatus(toolId, { content: ok ? `Called ${parsed.tool}` : `Call to ${parsed.tool} failed`, result, + // The card has room for one image; the model gets all of them. + ...(images.length > 0 ? { imageUrl: images[0].dataUrl } : {}), ...(ok ? {} : { error: `Call to ${parsed.tool} failed` }) }) return result diff --git a/frontend/src/lib/components/copilot/chat/shared.test.ts b/frontend/src/lib/components/copilot/chat/shared.test.ts index f4884a471d..8c512eb42c 100644 --- a/frontend/src/lib/components/copilot/chat/shared.test.ts +++ b/frontend/src/lib/components/copilot/chat/shared.test.ts @@ -1910,7 +1910,12 @@ describe('appendPendingToolImages', () => { // same screenshots again would duplicate them in history. it('appends one user message to both arrays and drains the buffer once', async () => { const { appendPendingToolImages } = await import('./shared') - let pending = [{ dataUrl: 'data:image/png;base64,SHOT', mediaType: 'image/png' as const }] + let pending = [ + { + image: { dataUrl: 'data:image/png;base64,SHOT', mediaType: 'image/png' as const }, + caption: 'Screenshot(s) of the app preview:' + } + ] const toolCallbacks = { setToolStatus: vi.fn(), takePendingToolImages: () => { diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 53b56141e5..7d17fd73ee 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -1,5 +1,6 @@ import { AI_DECISION_SCHEMA } from '../../flows/flowInfers' import type { + ChatCompletionContentPart, ChatCompletionFunctionTool, ChatCompletionMessageFunctionToolCall, ChatCompletionMessageParam @@ -1439,20 +1440,25 @@ export async function processToolCall({ * id is already answered by its tool result before this non-tool message. The image * parts ride the same `image_url` carrier that the provider converters translate. */ +/** An image a tool produced, with the line that tells the model what it shows. */ +export type ToolImage = { image: AttachedImage; caption: string } + /** The message that hands tool-produced images to the model, or undefined when * there are none. Split out so a snapshot of a turn still buffering them can * build the same message without draining the buffer the live turn still owns. */ export function pendingToolImagesMessage( - images: AttachedImage[] + images: ToolImage[] ): ChatCompletionMessageParam | undefined { if (images.length === 0) return undefined - return { - role: 'user', - content: [ - { type: 'text', text: 'Screenshot(s) of the app preview:' }, - ...images.map((img) => dataUrlToImagePart(img.dataUrl)) - ] + // One batch can mix tools, so each run of images is introduced by its own tool's caption. + const content: ChatCompletionContentPart[] = [] + let caption: string | undefined + for (const { image, caption: next } of images) { + if (next !== caption) content.push({ type: 'text', text: next }) + caption = next + content.push(dataUrlToImagePart(image.dataUrl)) } + return { role: 'user', content } } export function appendPendingToolImages( @@ -1730,9 +1736,9 @@ export interface ToolCallbacks { * appendPendingToolImages) — appending mid-batch would leave sibling tool_call ids * unanswered before a non-tool message. */ - attachToolImage?: (toolId: string, image: AttachedImage) => void + attachToolImage?: (toolId: string, image: ToolImage) => void /** Drain every image buffered this batch (insertion order), clearing the buffer. */ - takePendingToolImages?: () => AttachedImage[] + takePendingToolImages?: () => ToolImage[] /** Wired only by the global/sessions chat: delivers the folder instructions * covering the paths a tool call names, once per conversation. */ folderInstructions?: FolderInstructionsContext From 97dcc1a78b89b796bf743318919df92914b1c010 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Wed, 25 Nov 2026 16:51:57 +0100 Subject: [PATCH 04/26] chore: scope the PR review waiter to its own PR's runs (#12659) * fix(pr-skill): scope the review waiter to its own PR's runs The waiter waited on every PR Review Commands run after its trigger, from any PR, so one stuck reviewer elsewhere held every round to the 45-minute deadline. Match runs on the PR's title, and add waiting rules to the skill. Co-Authored-By: Claude Opus 5.5 * fix(pr-skill): keep a seen run from reading as missing, scope the manual check Co-Authored-By: Claude Opus 5.5 * chore(pr-skill): keep the trigger-time comment next to its line Co-Authored-By: Claude Opus 5.5 * fix(pr-skill): stop the waiter once verdicts are in, at 20 min name stuck jobs Co-Authored-By: Claude Opus 5.5 * chore(pr-skill): match verdicts on the bot author, refresh round durations Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .agents/skills/pr/SKILL.md | 7 ++- .agents/skills/pr/review-round.sh | 73 ++++++++++++++++++++++++------- 2 files changed, 62 insertions(+), 18 deletions(-) diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md index f2a9ec8dad..e83dca2b84 100644 --- a/.agents/skills/pr/SKILL.md +++ b/.agents/skills/pr/SKILL.md @@ -135,7 +135,7 @@ sufficient — see "Flip, or ask first" below. The one standing exception is an leave that PR in draft (usually so it can be tested first) — honour it for that PR, and don't carry it over to the next one. -1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes 10–30 min; you are woken when it exits — do not stop the session or poll in the foreground while it runs): +1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes about 10 min, 20 at most; you are woken when it exits — do not stop the session or poll in the foreground while it runs): ```bash bash .agents/skills/pr/review-round.sh @@ -143,6 +143,11 @@ carry it over to the next one. It comments `/review` on the PR — which runs the Codex, Claude and Pi CI reviewers even on a draft — waits for the spawned `PR Review Commands` workflow run(s) to complete, then prints one verdict line per reviewer and saves the full review comments to files. + Waiting rules — a session that breaks one sits idle on results the user can already see: + - **Use the waiter, not a loop of your own.** It always exits: as soon as the Codex, Claude and Pi verdicts are posted, once the round's run completes (failed jobs included), at a 20-minute deadline with whatever was posted, or non-zero when no run appeared or GitHub kept erroring — treat a non-zero exit as "look yourself", not "no reviews". A hand-written loop waiting for "a comment from each reviewer" never ends when one reviewer dies (capacity errors, cancelled jobs), since a dead job posts nothing. + - **If your harness does not wake you when a background command exits, run the waiter in the foreground** with a timeout of at least 25 minutes. Backgrounding it and ending your turn then means nobody ever reads the result. + - **Act on a missing reviewer immediately.** Reviewers that never start or hang are common. The waiter names each reviewer with no review and the jobs that did not finish cleanly; re-trigger each missing one at once with a `/codex`, `/claude` or `/pi` PR comment and run the waiter again, rather than waiting longer. + `/review` (and `/codex`) are **idempotent per head SHA**: if a running or successful review already covers the current head, they skip that agent and post nothing new — the waiter reads the existing verdict for that head, so a skipped agent is *not* a missing one. A cancelled/failed head run is re-run in place; a fresh run is launched only when nothing covers the head. So an unchanged-head re-review is a near no-op, not a new round — push a commit to get genuinely fresh reviews. 2. **Judge the round.** Codex is mandatory; Claude, Pi and cubic count whenever they posted. Every review starts with one of the three `REVIEW.md` verdicts: diff --git a/.agents/skills/pr/review-round.sh b/.agents/skills/pr/review-round.sh index abd94005f6..adc7c72214 100755 --- a/.agents/skills/pr/review-round.sh +++ b/.agents/skills/pr/review-round.sh @@ -7,19 +7,20 @@ # Comments `/review` on the PR (works on drafts), waits for the spawned # "PR Review Commands" workflow run(s) to complete, then prints one verdict # line per reviewer and saves each full review comment to a file. A round -# takes 10-30 minutes: run this in the background and act on its output when +# takes about 10 minutes, 20 at most: run this in the background and act on its output when # it exits, per the pr skill ("Review rounds"). set -euo pipefail REPO=${REPO:-$(gh repo view --json nameWithOwner --jq .nameWithOwner)} PR=${1:-$(gh pr view --json number --jq .number)} +PR_TITLE=$(gh pr view "$PR" --repo "$REPO" --json title --jq .title) # Timestamp of the trigger comment, straight from GitHub, so local clock skew # can't make the run/comment filters below miss part of the round. TRIGGER_TIME=$(gh api "repos/$REPO/issues/$PR/comments" -f body='/review' --jq .created_at) echo "Review round triggered on $REPO#$PR at $TRIGGER_TIME" -# Retry wrapper for one-off gh/API hiccups: a 45-minute wait must not die on +# Retry wrapper for one-off gh/API hiccups: a 20-minute wait must not die on # a single transient failure. retry() { local attempt @@ -31,21 +32,39 @@ retry() { } # The /review comment spawns one "PR Review Commands" run holding the -# claude/codex/pi jobs. Runs aren't linked to a PR, so wait on every run of -# that workflow created after the trigger: a concurrent round on another PR -# can only delay the answer, never truncate it. Every issue comment on any PR -# spawns a fast-completing parse run of the same workflow, so the round's own -# run may briefly lag the listing while unrelated runs already show completed: -# require the all-completed state to hold past a floor and across two -# consecutive polls before trusting it. -DEADLINE=$(( $(date +%s) + 45 * 60 )) +# claude/codex/pi jobs. Runs aren't linked to a PR, but an issue_comment run's +# display title is the PR's title: match on it, since waiting on every run +# after the trigger means a stuck reviewer on any other PR holds this round +# to the deadline. Every comment on this PR (the reviewers' own +# included) spawns a fast-completing parse run, so the round's own run may +# briefly lag the listing while those already show completed: require the +# all-completed state to hold past a floor and across two consecutive polls. +# +# Reviews land 6-10 minutes in. A reviewer that never starts or hangs is common +# and only a human re-trigger fixes it, so stop early: as soon as all three +# verdicts are posted, else at 20 minutes, naming the jobs still unfinished. +VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)' +# Claude edits a placeholder comment in place, hence updated_at. +all_verdicts_in() { + gh api "repos/$REPO/issues/$PR/comments?per_page=100" --paginate 2>/dev/null \ + | jq -s -e --arg t "$TRIGGER_TIME" --arg re "$VERDICT_RE" ' + [.[][] | select(.updated_at > $t) | select(.body // "" | test($re))] as $c + | ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Codex Review")))) + and ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Pi Review")))) + and ($c | any(.user.login == "claude[bot]"))' >/dev/null +} +DEADLINE=$(( $(date +%s) + 20 * 60 )) NO_RUN_DEADLINE=$(( $(date +%s) + 5 * 60 )) MIN_WAIT_UNTIL=$(( $(date +%s) + 3 * 60 )) STABLE=0 +SEEN=0 +ALL_IN=0 +ROUND_RUNS='[]' FAILURES=0 while :; do if RUNS=$(gh run list --repo "$REPO" --workflow=pr-review-commands.yml \ - --created ">=$TRIGGER_TIME" --limit 100 --json status); then + --created ">=$TRIGGER_TIME" --limit 500 --json databaseId,status,displayTitle \ + --jq "[.[] | select(.displayTitle == $(jq -Rn --arg t "$PR_TITLE" '$t'))]"); then FAILURES=0 else FAILURES=$(( FAILURES + 1 )) @@ -58,6 +77,13 @@ while :; do continue fi TOTAL=$(jq length <<<"$RUNS") + # The limit applies before the title filter, so on a busy repo this PR's run + # can age out of the listing: once seen, never report it as missing. + if [ "$TOTAL" -gt 0 ]; then SEEN=1; ROUND_RUNS=$RUNS; fi + if all_verdicts_in; then + ALL_IN=1 + break + fi PENDING=$(jq '[.[] | select(.status != "completed")] | length' <<<"$RUNS") NOW=$(date +%s) if [ "$TOTAL" -gt 0 ] && [ "$PENDING" -eq 0 ] && [ "$NOW" -gt "$MIN_WAIT_UNTIL" ]; then @@ -68,12 +94,12 @@ while :; do else STABLE=0 fi - if [ "$TOTAL" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then + if [ "$SEEN" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then echo "ERROR: no 'PR Review Commands' run appeared within 5 minutes of the /review comment; check that the comment author has write access and the workflow is enabled." >&2 exit 1 fi if [ "$NOW" -gt "$DEADLINE" ]; then - echo "WARNING: review round still pending after 45 minutes; reporting whatever has been posted so far." >&2 + echo "WARNING: review round still pending after 20 minutes; reporting whatever has been posted so far." >&2 break fi sleep 60 @@ -100,7 +126,7 @@ head_run_state() { # A re-run-in-place review lands on a head-tied run that finishes after the fast # pr-review-commands run, so let those settle before reading verdicts. for wf in codex-pr-review.yml pi-pr-review.yml pr-ready-review.yml; do - while :; do + while [ "$ALL_IN" -eq 0 ]; do case "$(head_run_state "$wf")" in ""|"completed "*) break ;; *) if [ "$(date +%s)" -gt "$DEADLINE" ]; then break; fi; sleep 30 ;; @@ -121,8 +147,6 @@ REVIEWS_RAW=$(retry gh api "repos/$REPO/pulls/$PR/reviews?per_page=100" --pagina jq -s --arg t "$TRIGGER_TIME" '[.[][] | select((.submitted_at // "") > $t)]' \ <<<"$REVIEWS_RAW" > "$OUT_DIR/pr-reviews.json" -VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)' - body_by_header() { # jq -r --arg h "$2" '[.[] | select(.body // "" | contains($h))] | last | .body // empty' "$1" } @@ -144,7 +168,11 @@ verdict_body() { # report() { # local name=$1 body=$2 verdict if [ -z "$body" ]; then - echo "$name: (no review posted for this head)" + if [ "$name" = cubic ]; then + echo "$name: (no review posted for this head)" + else + echo "$name: (no review posted for this head; re-trigger now with a '/$name' PR comment)" + fi return fi printf '%s\n' "$body" > "$OUT_DIR/$name.md" @@ -167,6 +195,17 @@ fi report cubic "$CUBIC_BODY" echo echo "Full round output: $OUT_DIR (comments.json, pr-reviews.json, one .md per reviewer)" +if [ "$ALL_IN" -eq 0 ]; then + UNFINISHED=$(for id in $(jq -r '.[].databaseId' <<<"$ROUND_RUNS"); do + gh run view "$id" --repo "$REPO" --json jobs --jq '.jobs[] + | select(.status != "completed" or (.conclusion | IN("success", "skipped") | not)) + | " \(.name): \(.status) \(.conclusion // "") since \(.startedAt // "-")"' 2>/dev/null || true + done) + if [ -n "$UNFINISHED" ]; then + echo "Review jobs that did not finish cleanly:" + printf '%s\n' "$UNFINISHED" + fi +fi if [ -z "$CODEX_BODY" ]; then echo "WARNING: no Codex verdict for $HEAD_SHA - its head run is not green (cancelled/failed/absent, not merely skipped-because-already-reviewed). Re-trigger with a '/codex' PR comment (re-runs the interrupted run in place, or launches one) and wait again." >&2 fi From 5953595d50a20fc08449bf1d0c7aa6b0c0a12b81 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 25 Nov 2026 20:02:35 +0000 Subject: [PATCH 05/26] fix: hold a volume's lease through sync-back and pull it in parallel (#12667) * fix: hold a volume's lease through sync-back and apply its deletions Co-Authored-By: Claude Opus 5.5 * fix: stream volume pulls and hashes, bound uploads by bytes in flight Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 42345ff86342a5d4c1a8be2cccd031cb77ad1146 This commit updates the EE repository reference after PR #1008 was merged in windmill-ee-private. Previous ee-repo-ref: 06627e55b4c3b1e4b8eab9a0ac0e1d01d6ad0a79 New ee-repo-ref: 42345ff86342a5d4c1a8be2cccd031cb77ad1146 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- ...0775b6da84dd53aeca8fb9b556f969aee29a.json} | 4 +- ...6771c3a1a2a5a67dd467ed263b3501c5d279.json} | 4 +- backend/ee-repo-ref.txt | 2 +- backend/windmill-worker-volumes/src/lib.rs | 41 ++++++++++++++++++- backend/windmill-worker/src/volume_oss.rs | 3 ++ backend/windmill-worker/src/worker.rs | 40 +++++++++--------- 6 files changed, 68 insertions(+), 26 deletions(-) rename backend/.sqlx/{query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json => query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json} (60%) rename backend/.sqlx/{query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json => query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json} (78%) diff --git a/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json b/backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json similarity index 60% rename from backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json rename to backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json index ca7a719231..cb94c5045b 100644 --- a/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json +++ b/backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n lease_until = NULL, leased_by = NULL,\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea" + "hash": "123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a" } diff --git a/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json b/backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json similarity index 78% rename from backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json rename to backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json index 4521496742..5f6c31d752 100644 --- a/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json +++ b/backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66" + "hash": "3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279" } diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index a1fc20442a..046fa30012 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -a403f3ce12fd150dd649098e61562eda1e6a4d81 +42345ff86342a5d4c1a8be2cccd031cb77ad1146 diff --git a/backend/windmill-worker-volumes/src/lib.rs b/backend/windmill-worker-volumes/src/lib.rs index f167676ea4..5fa3467e30 100644 --- a/backend/windmill-worker-volumes/src/lib.rs +++ b/backend/windmill-worker-volumes/src/lib.rs @@ -12,6 +12,41 @@ use std::path::PathBuf; pub const MAX_VOLUMES_PER_JOB: usize = 10; +/// Object requests a pull or a sync-back keeps in flight for one volume. +pub const VOLUME_TRANSFER_CONCURRENCY: usize = 16; + +/// An upload holds its whole file in memory, so a sync-back bounds the bytes of the uploads in +/// flight as well as their count: a file at least this large is uploaded alone. +pub const VOLUME_UPLOAD_BYTES_IN_FLIGHT: u64 = 256 * 1024 * 1024; + +/// Deletes `paths` concurrently, an object already gone counting as deleted. Returns how many +/// were deleted, or the first failure and how many failed: a delete is never assumed to succeed. +pub async fn delete_objects( + client: &dyn object_store::ObjectStore, + paths: Vec, +) -> Result { + use futures::StreamExt; + let results: Vec> = futures::stream::iter(paths) + .map(|path| async move { + match client.delete(&path).await { + Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), + Err(e) => Err(format!("{path}: {e}")), + } + }) + .buffer_unordered(VOLUME_TRANSFER_CONCURRENCY) + .collect() + .await; + let total = results.len(); + let failures: Vec = results.into_iter().filter_map(Result::err).collect(); + match failures.first() { + None => Ok(total), + Some(first) => Err(format!( + "failed to delete {} of {total} removed file(s), first: {first}", + failures.len() + )), + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FileEntry { pub size: u64, @@ -25,7 +60,10 @@ pub struct FileEntry { pub fn compute_md5_hex(data: &[u8]) -> String { use md5::{Digest, Md5}; - let result = Md5::digest(data); + md5_digest_hex(&Md5::digest(data)) +} + +pub fn md5_digest_hex(result: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut hex = String::with_capacity(32); for &b in result.iter() { @@ -112,6 +150,7 @@ pub struct SyncStats { pub file_count: usize, pub uploaded: usize, pub skipped: usize, + pub deleted: usize, } pub fn validate_volume_name(name: &str) -> Result<(), String> { diff --git a/backend/windmill-worker/src/volume_oss.rs b/backend/windmill-worker/src/volume_oss.rs index 3736e83485..c5e32fd8e1 100644 --- a/backend/windmill-worker/src/volume_oss.rs +++ b/backend/windmill-worker/src/volume_oss.rs @@ -3,6 +3,7 @@ pub(crate) use crate::volume_ee::*; #[cfg(not(feature = "private"))] #[cfg(feature = "parquet")] +#[derive(Default)] pub(crate) struct LeaseRenewalGuard(pub Option>); #[cfg(not(feature = "private"))] @@ -94,6 +95,7 @@ pub(crate) async fn sync_volumes_sql_worker( _worker_name: &str, _conn: &windmill_common::worker::Connection, _job_succeeded: bool, + _lease_renewal: LeaseRenewalGuard, ) { } @@ -108,5 +110,6 @@ pub(crate) async fn sync_volumes_http_worker( _worker_name: &str, _conn: &windmill_common::worker::Connection, _job_succeeded: bool, + _lease_renewal: LeaseRenewalGuard, ) { } diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index 2333585c90..cfddc5aa0c 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -7072,7 +7072,7 @@ mount {{ states: Vec::new(), writable: Vec::new(), client: None, - lease_renewal: crate::volume_oss::LeaseRenewalGuard(None), + lease_renewal: Default::default(), }; #[cfg(feature = "parquet")] @@ -7617,11 +7617,9 @@ mount {{ // Volume sync-back and lease release #[cfg(feature = "parquet")] if !volume_setup.states.is_empty() { - // Stop lease renewal before sync-back - volume_setup.lease_renewal.0.take().map(|h| h.abort()); - - if let Some(ref vol_client) = volume_setup.client { - if let Connection::Sql(db) = conn { + let lease_renewal = std::mem::take(&mut volume_setup.lease_renewal); + match (conn, volume_setup.client.as_ref()) { + (Connection::Sql(db), Some(vol_client)) => { Box::pin(crate::volume_oss::sync_volumes_sql_worker( &volume_setup.states, &volume_setup.writable, @@ -7632,23 +7630,25 @@ mount {{ worker_name, conn, result.is_ok(), + lease_renewal, )) .await; } - } - - if let Connection::Http(http) = conn { - Box::pin(crate::volume_oss::sync_volumes_http_worker( - &volume_setup.states, - &volume_setup.writable, - http, - &job.workspace_id, - job.id, - worker_name, - conn, - result.is_ok(), - )) - .await; + (Connection::Http(http), _) => { + Box::pin(crate::volume_oss::sync_volumes_http_worker( + &volume_setup.states, + &volume_setup.writable, + http, + &job.workspace_id, + job.id, + worker_name, + conn, + result.is_ok(), + lease_renewal, + )) + .await; + } + (Connection::Sql(_), None) => {} } // Clean up absolute-path symlinks created by setup_volume_mount_paths From 8f637d58d6654740bca41f32a3462e5951ff8f4c Mon Sep 17 00:00:00 2001 From: Guilhem Date: Wed, 25 Nov 2026 21:02:48 +0100 Subject: [PATCH 06/26] fix: log in on the live session when the browser sends two token cookies (#12663) * fix: authenticate on the live session when several token cookies are sent Co-Authored-By: Claude Opus 5.5 * fix: cache the duplicate session cookie pick and cap the candidates Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- backend/tests/duplicate_session_cookie.rs | 38 ++++++++++ backend/windmill-api-auth/src/auth.rs | 88 ++++++++++++++++++++--- 2 files changed, 118 insertions(+), 8 deletions(-) create mode 100644 backend/tests/duplicate_session_cookie.rs diff --git a/backend/tests/duplicate_session_cookie.rs b/backend/tests/duplicate_session_cookie.rs new file mode 100644 index 0000000000..8122e27b6d --- /dev/null +++ b/backend/tests/duplicate_session_cookie.rs @@ -0,0 +1,38 @@ +//! A browser can send two `token` cookies: this instance's, and one a parent-domain instance set +//! with `Domain=` (app.windmill.dev on `.windmill.dev`, seen from a tenant subdomain). Safari +//! sends the host's cookie first and Chrome last, so the request must authenticate on whichever +//! is a live session here, in either order. + +use reqwest::StatusCode; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_duplicate_session_cookie_uses_the_live_one(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let client = reqwest::Client::new(); + let url = format!( + "http://localhost:{}/api/workspaces/users", + server.addr.port() + ); + let status = |cookie: &'static str| { + let req = client.get(&url).header("Cookie", cookie); + async move { anyhow::Ok(req.send().await?.status()) } + }; + + assert_eq!( + status("token=FOREIGN_INSTANCE_TOKEN; token=SECRET_TOKEN").await?, + StatusCode::OK + ); + assert_eq!( + status("token=SECRET_TOKEN; token=FOREIGN_INSTANCE_TOKEN").await?, + StatusCode::OK + ); + assert_eq!( + status("token=FOREIGN_INSTANCE_TOKEN; token=OTHER_FOREIGN_TOKEN").await?, + StatusCode::UNAUTHORIZED + ); + Ok(()) +} diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 889f1f09a0..32b31f771a 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -41,6 +41,8 @@ lazy_static::lazy_static! { pub static ref AUTH_CACHE: Cache<(String, String), ExpiringAuthCache> = Cache::new(300); // Cache for token -> email lookups (for non-workspace-member authenticated users) static ref TOKEN_EMAIL_CACHE: Cache, std::time::Instant)> = Cache::new(500); + // Joined hashes of a request's duplicate `token` cookies -> index of the live one. + static ref PICKED_SESSION_CACHE: Cache, std::time::Instant)> = Cache::new(500); } /// A token keeps its identity when a superadmin moves the account to another address, so entries @@ -956,6 +958,69 @@ async fn admit_and_record_guest_jwt(db: &DB, w_id: &str, email: &str, app_path: true } +/// Browsers send one or two; checking more would let one request try many guessed tokens +/// while `BRUTE_FORCE_COUNTER` counts a single failure. +const MAX_SESSION_COOKIES: usize = 4; + +/// The first `token` cookie values, parsed the way `Cookies` parses them, in the order sent. +fn session_cookie_values(parts: &Parts) -> Vec { + parts + .headers + .get_all(http::header::COOKIE) + .iter() + .filter_map(|h| h.to_str().ok()) + .flat_map(|h| h.split(';')) + .filter_map(|c| tower_cookies::Cookie::parse_encoded(c).ok()) + .filter(|c| c.name() == COOKIE_NAME) + .map(|c| c.value_trimmed().to_owned()) + .take(MAX_SESSION_COOKIES) + .collect() +} + +/// A browser can hold two `token` cookies for one host: this instance's, and one a parent-domain +/// instance set with `Domain=` (app.windmill.dev on `.windmill.dev`), which JS cannot clear since +/// it is HttpOnly. Browsers disagree on their order (Safari sends the host's first, Chrome last), +/// so neither position can be trusted: keep the first one that is a live session here. +async fn pick_live_session_token( + parts: &mut Parts, + state: &S, + candidates: Vec, +) -> Option { + // `Cookies::get` keeps the last duplicate: the pick when nothing can be checked. + let fallback = candidates.last().cloned(); + let Ok(Extension(cache)) = Extension::>::from_request_parts(parts, state).await + else { + return fallback; + }; + let hashes: Vec = candidates.iter().map(|t| hash_token(t)).collect(); + // A browser keeps sending the same pair on every request, so the pick is cached. A token + // revoked within the TTL can still be picked, and then fails authentication as revoked. + let key = hashes.join(","); + if let Some((picked, at)) = PICKED_SESSION_CACHE.get(&key) { + if at.elapsed().as_secs() < TOKEN_EMAIL_CACHE_TTL_SECS { + return picked.map(|i| candidates[i].clone()).or(fallback); + } + } + let live: Vec = match sqlx::query_scalar( + "SELECT h FROM unnest($1::text[]) AS h \ + WHERE EXISTS (SELECT 1 FROM token WHERE token_hash = h \ + AND (expiration > NOW() OR expiration IS NULL))", + ) + .bind(&hashes) + .fetch_all(&cache.db) + .await + { + Ok(live) => live, + Err(e) => { + tracing::error!("checking duplicate session cookies: {e:#}"); + return fallback; + } + }; + let picked = hashes.iter().position(|h| live.contains(h)); + PICKED_SESSION_CACHE.insert(key, (picked, std::time::Instant::now())); + picked.map(|i| candidates[i].clone()).or(fallback) +} + pub(crate) async fn extract_token(parts: &mut Parts, state: &S) -> Option { let auth_header = parts .headers @@ -965,14 +1030,21 @@ pub(crate) async fn extract_token(parts: &mut Parts, state: &S) let from_cookie = match auth_header { Some(x) => Some(x.to_owned()), - None => Extension::::from_request_parts(parts, state) - .await - .ok() - .and_then(|cookies| { - cookies - .get(COOKIE_NAME) - .map(|c| c.value_trimmed().to_owned()) - }), + None => { + let candidates = session_cookie_values(parts); + if candidates.len() > 1 { + pick_live_session_token(parts, state, candidates).await + } else { + Extension::::from_request_parts(parts, state) + .await + .ok() + .and_then(|cookies| { + cookies + .get(COOKIE_NAME) + .map(|c| c.value_trimmed().to_owned()) + }) + } + } }; #[derive(Deserialize)] From 5d4820d3736fa6f307fb4838e525e32c4dc24838 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:03:05 +0100 Subject: [PATCH 07/26] =?UTF-8?q?feat:=20hand=20the=20code=20selected=20wi?= =?UTF-8?q?th=20=E2=8C=98K=20and=20Ctrl+L=20to=20an=20AI=20session=20(#126?= =?UTF-8?q?61)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: hand the code selected with ⌘K and Ctrl+L to an AI session * fix: leave the composer's picks alone when resending a message stored without context --- ai_evals/README.md | 16 + .../frontend/core/global/globalEvalRunner.ts | 8 +- ai_evals/cases/global.yaml | 39 ++ ai_evals/core/types.ts | 10 + ai_evals/modes/global.ts | 1 + frontend/src/lib/components/Editor.svelte | 160 ++++---- .../src/lib/components/FlowBuilder.svelte | 21 +- .../src/lib/components/ScriptBuilder.svelte | 12 +- .../src/lib/components/ScriptEditor.svelte | 4 + .../copilot/FlowInlineScriptAIButton.svelte | 25 +- .../copilot/chat/AIChatInlineWidget.svelte | 281 +++----------- .../copilot/chat/AIChatInput.svelte | 92 ++--- .../copilot/chat/AIChatManager.svelte.ts | 365 ++++++------------ .../copilot/chat/AIChatManager.test.ts | 129 ++++++- .../copilot/chat/ContextElementBadge.svelte | 2 + .../copilot/chat/ContextManager.svelte.ts | 95 ++--- .../chat/InlinePrompt.svelte} | 52 ++- .../lib/components/copilot/chat/chatDraft.ts | 3 +- .../components/copilot/chat/chatViewHost.ts | 7 +- .../lib/components/copilot/chat/context.ts | 73 ++++ .../lib/components/copilot/chat/flow/core.ts | 33 +- .../copilot/chat/global/core.test.ts | 14 + .../components/copilot/chat/global/core.ts | 34 +- .../components/copilot/chat/script/core.ts | 96 ----- .../src/lib/components/copilot/chat/shared.ts | 54 +-- .../src/lib/components/dbt/DbtEditor.svelte | 9 + .../flows/content/FlowModuleComponent.svelte | 14 +- .../flows/map/FlowModuleSchemaMap.svelte | 8 +- .../components/raw_apps/RawAppEditor.svelte | 22 +- .../raw_apps/RawAppInlineScriptEditor.svelte | 2 + .../sessions/RawAppEditorView.svelte | 33 +- .../sessions/SessionWrapper.dom.test.ts | 35 +- .../components/sessions/SessionWrapper.svelte | 6 +- .../sessions/openInSessionContext.ts | 20 +- .../components/sessions/pageDrawerSession.ts | 6 + .../components/sessions/sessionMirrorPlan.ts | 2 +- .../sessions/sessionState.svelte.ts | 22 +- .../sessions/sessionSwitch.svelte.ts | 10 +- .../components/sessions/sessionSwitch.test.ts | 8 +- 39 files changed, 842 insertions(+), 981 deletions(-) rename frontend/src/lib/components/{raw_apps/InlineElementPrompt.svelte => copilot/chat/InlinePrompt.svelte} (51%) diff --git a/ai_evals/README.md b/ai_evals/README.md index 3c123e2579..824354a257 100644 --- a/ai_evals/README.md +++ b/ai_evals/README.md @@ -254,6 +254,22 @@ secretRequests: and the resource are created in the workspace, deployed, and the model reads the result the chat would give it. `check` is reported as is; no connection test runs. +`runtime.codeSelections` attaches code to the prompt of a global case, as the chips of code +selected in an editor do. `source` names the item (`script`, `flow`, `raw_app` or `agent`) and +optionally its `part` (a flow step, app runnable, agent tool or script module file), and +`content` is the code from `startLine` to `endLine`: + +```yaml +codeSelections: + - source: { kind: flow, path: f/evals/global/process_refund, part: calculate_total } + lang: bun + startLine: 1 + endLine: 2 + content: |- + export async function main(subtotal: number) { + return { subtotal, total: subtotal } +``` + `runtime.profile` runs a session-chat case (`sessionChat: true`) as a non-admin role instead of full access: the prompt, toolset and tool schemas are cut as production's `capabilitiesForRole` cuts them, and the workspace's `operator_settings` are seeded for the diff --git a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts index f3d025626c..c7b6080d59 100644 --- a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts @@ -4,6 +4,7 @@ import { globalToolsFor, prepareGlobalUserMessage, } from "../../../../../frontend/src/lib/components/copilot/chat/global/core"; +import { createCodeSelection } from "../../../../../frontend/src/lib/components/copilot/chat/context"; import { assembleGlobalSystemMessage } from "../../../../../frontend/src/lib/components/copilot/chat/global/globalAssembly"; import { canBuild, @@ -46,6 +47,7 @@ import { type EvalPreviewTabFixture, } from "./evalPreviewTabs"; import type { + EvalCaseCodeSelection, EvalCaseProfile, EvalSecretRequestAnswer, ModeRunContext, @@ -145,6 +147,7 @@ export interface GlobalEvalOptions { // Start in plan mode: the gate refuses every tool without `planModeSafe`, and the two plan // tools are offered. Needs sessionChat, which is what plan mode is gated on in production. planMode?: boolean; + codeSelections?: EvalCaseCodeSelection[]; // The user's rights, resolved as a session resolves them; unset keeps full access. profile?: EvalCaseProfile; // Run the pipeline the chat drafted once it is over (`validate.pipelineRun`). @@ -286,6 +289,9 @@ export async function runGlobalEval( pipelineFolders: pipelineEditors?.folders(), }); const baseSystemMessage = assembleSystemMessage(); + const codeSelections = (options.codeSelections ?? []).map(({ source, ...selection }) => + createCodeSelection(source, selection), + ); const helpers = { ...evalArtifacts.helpers, // A standalone chat has no session: the tools that behave differently in one (a pipeline @@ -317,7 +323,7 @@ export async function runGlobalEval( isToolAvailable: (name) => (!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) && (planMode?.isToolAvailable?.(name) ?? true), - userMessage: prepareGlobalUserMessage(userPrompt, [], { + userMessage: prepareGlobalUserMessage(userPrompt, codeSelections, { ...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}), activePreview: panel?.activePreview(), resourceTypeSync: await resolveResourceTypeSync(workspaceRoot, []), diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index 1976004840..a5093b3409 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -519,6 +519,45 @@ - returns subtotal, tax, and total from the updated flow logic - leaves the result as a draft only +- id: global-code-selection-names-its-item + prompt: |- + Throw an error here when the subtotal is negative. + Keep the change as a draft. + initial: ai_evals/fixtures/frontend/global/initial/current_invoice_live_flow.json + runtime: + maxTurns: 10 + codeSelections: + - source: + kind: flow + path: f/evals/global/process_refund + part: calculate_total + lang: bun + startLine: 1 + endLine: 2 + content: |- + export async function main(subtotal: number) { + return { subtotal, total: subtotal } + validate: + # The open flow's own draft, which must stay as it was, and the edited one. + draftCountExactly: 2 + requiredDrafts: + - type: flow + path: f/evals/global/process_refund + valueIncludes: + - calculate_total + - throw + forbiddenDrafts: + - type: flow + path: f/evals/global/process_invoice + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - edits the calculate_total step of the process_refund flow, which the selected code belongs to, not the flow open in the editor + - throws when the subtotal is negative and keeps the rest of the step as it was + - leaves the result as a draft only + - id: global-test14-current-without-live-editor-asks-question prompt: |- Please update this script so it returns `ok`. diff --git a/ai_evals/core/types.ts b/ai_evals/core/types.ts index 7caa2d5fb8..e9e4d0cede 100644 --- a/ai_evals/core/types.ts +++ b/ai_evals/core/types.ts @@ -38,6 +38,8 @@ export interface EvalCaseRuntimeSpec { secretRequests?: EvalSecretRequestAnswer[]; backendPreview?: EvalCaseRuntimeBackendPreview; appContext?: EvalCaseRuntimeAppContextSpec; + // Global mode: code the user selected in an editor and attached to the prompt. + codeSelections?: EvalCaseCodeSelection[]; // Global mode: run as a session chat (preview tools + session prompt) vs the standalone chat. sessionChat?: boolean; // Global session chats: start the case in plan mode, so the workspace-changing tools are @@ -60,6 +62,14 @@ export interface EvalSecretRequestAnswer { check?: { ok: true } | { ok: false; error: string }; } +export interface EvalCaseCodeSelection { + source: { kind: "script" | "flow" | "raw_app" | "agent"; path: string; part?: string }; + lang: "bun" | "python3" | "bash" | "postgresql"; + startLine: number; + endLine: number; + content: string; +} + export interface EvalCaseProfile { operator: boolean; operatorSettings?: { diff --git a/ai_evals/modes/global.ts b/ai_evals/modes/global.ts index 71d4dae1da..cabed79045 100644 --- a/ai_evals/modes/global.ts +++ b/ai_evals/modes/global.ts @@ -55,6 +55,7 @@ export function createGlobalModeRunner( previewTabs: initial?.previewTabs, sessionChat: context.evalCase?.runtime?.sessionChat, planMode: context.evalCase?.runtime?.planMode, + codeSelections: context.evalCase?.runtime?.codeSelections, profile: context.evalCase?.runtime?.profile, pipelineRun: context.executionOnly ? undefined diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index da930c03f4..f1af18bf1c 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -112,10 +112,12 @@ import { editorPositionMap } from '$lib/utils' import { extToLang, langToExt } from '$lib/editorLangUtils' import { aiChatManager, type AIChatManager } from './copilot/chat/AIChatManager.svelte' - import type { Selection } from 'monaco-editor' import { canHavePreprocessor, getPreprocessorModuleCode } from '$lib/script_helpers' import { setMonacoTypescriptOptions } from './monacoLanguagesOptions' import { copilotInfo } from '$lib/aiStore' + import { createCodeSelection, type CodeSelection, type CodeSource } from './copilot/chat/context' + import { getOpenInSessionHandoff, withEditorFlush } from './sessions/openInSessionContext' + import { openSourceInSession } from './sessions/sessionSwitch.svelte' import { getDbSchemas } from './apps/components/display/dbtable/metadata' import { rawAppLintStore, type MonacoLintError } from './raw_apps/lintStore' import { MarkerSeverity } from 'monaco-editor' @@ -168,7 +170,10 @@ loadAsync?: boolean key?: string | undefined class?: string | undefined - moduleId?: string + /** The item an AI session is told the selected code belongs to. Unset for code of no item. */ + codeSource?: CodeSource + /** The language an AI session is told the code is in, when `scriptLang` only colours it. */ + codeSourceLang?: CodeSelection['lang'] enablePreprocessorSnippet?: boolean /** When set, enables raw app lint collection mode and reports Monaco markers to the lint store under this key */ rawAppRunnableKey?: string | undefined @@ -210,7 +215,8 @@ loadAsync = false, key = undefined, class: clazz = undefined, - moduleId = undefined, + codeSource = undefined, + codeSourceLang = undefined, enablePreprocessorSnippet = false, rawAppRunnableKey = undefined, preparedAssetsSqlQueries, @@ -282,6 +288,22 @@ const completionInfo = $derived( sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo ) + const sessionHandoff = getOpenInSessionHandoff() + const inIframe = BROWSER && window.self !== window.top + // The item's own hand-off: one of another kind is an outer editor's. + const handoffSource = $derived.by(() => { + if (!codeSource) return undefined + const source = sessionHandoff?.source( + codeSource.kind === 'flow' ? { moduleId: codeSource.part } : undefined + ) + return source?.target?.kind === codeSource.kind ? source : undefined + }) + // The path the item's draft is stored under, which the session's tools read it by. + const codePath = $derived(handoffSource?.target?.path || codeSource?.path) + // In a session, ⌘K goes to its chat instead. + const newSessionSource = $derived( + sessionScopedChatManager || inIframe || !$copilotInfo.enabled ? undefined : handoffSource + ) // let graphqlService: MonacoGraphQLAPI | undefined = undefined let fetchedDbSchema: DBSchema | undefined = $state(undefined) @@ -398,18 +420,56 @@ } } - export function getSelectedLines(): string | undefined { - if (editor) { - const selection = editor.getSelection() - if (selection) { - const range: IRange = { - startLineNumber: selection.startLineNumber, + /** The selected lines, whole, or the cursor's line. */ + function getCodeSelection(): CodeSelection | undefined { + const selection = editor?.getSelection() + const model = editor?.getModel() + if (!selection || !model || !codeSource || !codePath || !scriptLang) return undefined + const { startLineNumber: startLine, endLineNumber, endColumn } = selection + // A selection dragged to the start of a line holds none of it. + const endLine = + endColumn === 1 && endLineNumber > startLine ? endLineNumber - 1 : endLineNumber + return createCodeSelection( + { ...codeSource, path: codePath }, + { + startLine, + endLine, + content: model.getValueInRange({ + startLineNumber: startLine, startColumn: 1, - endLineNumber: selection.endLineNumber + 1, - endColumn: 1 - } - return editor.getModel()?.getValueInRange(range) + endLineNumber: endLine, + endColumn: model.getLineMaxColumn(endLine) + }), + lang: codeSourceLang ?? (scriptLang as CodeSelection['lang']) } + ) + } + + async function sendInlinePrompt(prompt: string): Promise { + const selection = getCodeSelection() + if (!selection || !newSessionSource) return false + try { + await openSourceInSession(withEditorFlush(newSessionSource, flushPendingChanges), { + seedPrompt: prompt, + autoSend: true, + seedPick: selection + }) + } catch (e) { + sendUserToast(e instanceof Error ? e.message : String(e), true) + return false + } + closeAIInlineWidget() + return true + } + + /** Go to the session's chat, with the selected lines. Outside a session no chat is on screen. */ + function attachSelectionToChat() { + if (!sessionScopedChatManager) return + const selection = editor?.getSelection()?.isEmpty() ? undefined : getCodeSelection() + if (selection) { + sessionScopedChatManager.attachCodeSelection(selection) + } else { + sessionScopedChatManager.focusInput() } } @@ -982,8 +1042,6 @@ // Inline ai chat widget let showInlineAIChat = $state(false) - let inlineAIChatSelection: Selection | null = $state(null) - let selectedCode = $state('') export async function reviewAndApplyCode(code: string, opts?: ReviewChangesOpts) { await aiChatEditorHandler?.reviewChanges(code, opts) @@ -1618,9 +1676,6 @@ editor?.addCommand(KeyMod.CtrlCmd | KeyCode.DownArrow, function () { if (aiChatManager.pendingNewCode) { aiChatManager.scriptEditorApplyCode?.(aiChatManager.pendingNewCode) - if (showInlineAIChat) { - closeAIInlineWidget() - } } }) @@ -1649,35 +1704,16 @@ }) editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyL, function () { - const selectedLines = getSelectedLines() - const selection = editor?.getSelection() - const hasSelection = - selection && - (selection.startLineNumber !== selection.endLineNumber || - selection.startColumn !== selection.endColumn) - // Only a session pane has a chat on screen to send the lines to. - const chat = sessionScopedChatManager - if (!chat) return - if (hasSelection && selectedLines) { - chat.addSelectedLinesToContext( - selectedLines, - selection.startLineNumber, - selection.endLineNumber, - moduleId - ) - } else { - chat.focusInput() - } + // Monaco runs a command for whichever editor has focus, this one or not. + if (editor?.hasWidgetFocus()) attachSelectionToChat() }) editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyK, function () { - if ($copilotInfo.enabled) { - aiChatEditorHandler?.rejectAll() - if (showInlineAIChat) { - closeAIInlineWidget() - } else { - showAIInlineWidget() - } + if (!editor?.hasWidgetFocus()) return + if (newSessionSource) { + showInlineAIChat = !showInlineAIChat + } else { + attachSelectionToChat() } }) @@ -1896,30 +1932,10 @@ }) } - function showAIInlineWidget() { - if (!editor) return - - inlineAIChatSelection = editor.getSelection() - if (!inlineAIChatSelection) { - return - } - const model = editor.getModel() - selectedCode = '' - if (model) { - selectedCode = model.getValueInRange(inlineAIChatSelection) - } - showInlineAIChat = true - aiChatInlineWidget?.focusInput() - } - function closeAIInlineWidget() { showInlineAIChat = false - inlineAIChatSelection = null - selectedCode = '' } - let aiChatInlineWidget: AIChatInlineWidget | null = $state(null) - $effect(() => { const fontSize = small ? editorFontSize.small : editorFontSize.regular if (editor) { @@ -2008,9 +2024,6 @@ rejectCodeChanges() } else if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowDown' && aiChatManager.pendingNewCode) { acceptCodeChanges() - if (showInlineAIChat) { - closeAIInlineWidget() - } } } $effect(() => { @@ -2250,14 +2263,15 @@ {/if} -{#if editor && $copilotInfo.enabled && aiChatEditorHandler} +{#if editor && showInlineAIChat && newSessionSource} { + closeAIInlineWidget() + if (refocus) editor?.focus() + }} /> {/if} diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 6a545423f8..b0c2e57b8b 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -138,6 +138,7 @@ import { editInForkAllowed, editInForkLabel, openEditInFork } from '$lib/utils/editInFork' import { isCloudHosted } from '$lib/cloud' import { UserDraft } from '$lib/userDraft.svelte' + import { assertDraftSaved } from './sessions/pageDrawerSession' import { setOpenInSessionHandoff } from './sessions/openInSessionContext' import { getEditorStoragePath, setEditorStoragePath } from './editorStoragePathContext' import { useEditRights, useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights' @@ -494,9 +495,15 @@ // discardIf baseline, safe only when there is none. async function persistDraftForSession(): Promise { await saveDraft() - if (opWorkspace && liveEditorDraftStoragePath && newFlow) { + if (!opWorkspace || !liveEditorDraftStoragePath) return + if (newFlow) { await UserDraft.forcePersist('flow', liveEditorDraftStoragePath, { workspace: opWorkspace }) } + assertDraftSaved({ + workspace: opWorkspace, + itemKind: 'flow', + path: liveEditorDraftStoragePath + }) } export function computeUnlockedSteps(flow: Flow) { @@ -1034,18 +1041,16 @@ const outerStoragePath = getEditorStoragePath() setEditorStoragePath(() => liveEditorDraftStoragePath ?? outerStoragePath?.()) - // "Open in AI session" target: the URL draft path the editor loads/saves by - // (which for a new flow differs from the live-edited friendly `$pathStore`), - // falling back to `$pathStore` in drawer mounts that carry no storage path. - const sessionTargetPath = $derived(liveEditorDraftStoragePath || $pathStore) - const aiBuilderShown = $derived(!disableAi && customUi?.topBar?.aiBuilder != false) const showFlowAiButton = $derived(aiBuilderShown && $roleCaps.flows !== 'compose') + // Targets the draft path the editor loads/saves by, which for a new flow differs from + // the live-edited friendly `$pathStore`. A drawer mount has none: its edits are in no + // draft, so leaving for a session would lose them. const sessionOpen = $derived( - sessionTargetPath + indicatorPath ? { - target: { kind: 'flow' as const, path: sessionTargetPath }, + target: { kind: 'flow' as const, path: indicatorPath }, workspaceId: opWorkspace ?? undefined, beforeOpen: persistDraftForSession } diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 29c5b79797..ed76ca4890 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -30,6 +30,7 @@ import OpenInSessionButton, { type OpenInSessionSource } from './sessions/OpenInSessionButton.svelte' + import { assertDraftSaved } from './sessions/pageDrawerSession' import { defaultScripts, enterpriseLicense, @@ -1071,17 +1072,19 @@ // discardIf baseline, safe only when there is none. async function persistDraftForSession(): Promise { await saveDraft() - if (opWorkspace && userDraftPath && savedScript?.no_deployed === true) { + if (!opWorkspace || !userDraftPath) return + if (savedScript?.no_deployed === true) { await UserDraft.forcePersist('script', userDraftPath, { workspace: opWorkspace }) } + assertDraftSaved({ workspace: opWorkspace, itemKind: 'script', path: userDraftPath }) } const sessionOpen: OpenInSessionSource | undefined = $derived( - userDraftPath + indicatorPath ? { - // URL draft path the editor loads/saves by, not the friendly + // Draft path the editor loads/saves by, not the friendly // `script.path` (a new script's has no row → "not found"). - target: { kind: 'script', path: userDraftPath }, + target: { kind: 'script', path: indicatorPath }, workspaceId: opWorkspace ?? undefined, beforeOpen: persistDraftForSession } @@ -2404,6 +2407,7 @@ bind:this={scriptEditor} bind:schema={script.schema} path={script.path} + storagePath={indicatorPath} bind:code={script.content} timeout={script.timeout} tag={script.tag} diff --git a/frontend/src/lib/components/ScriptEditor.svelte b/frontend/src/lib/components/ScriptEditor.svelte index 95d41a182f..31c442993e 100644 --- a/frontend/src/lib/components/ScriptEditor.svelte +++ b/frontend/src/lib/components/ScriptEditor.svelte @@ -2763,6 +2763,10 @@ lineNumbersMinChars={4} folding {path} + codeSource={customUi?.editorBar?.aiGen != false && + (inSessionPane || SUPPORTED_CHAT_SCRIPT_LANGUAGES.includes(lang ?? '')) + ? { kind: 'script', path: path ?? '', part: activeModuleTab ?? undefined } + : undefined} bind:code={editorCode} bind:websocketAlive bind:this={editor} diff --git a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte index b16f23bf00..25e7f079ef 100644 --- a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte +++ b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte @@ -1,15 +1,16 @@ diff --git a/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte b/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte index da1a1e26af..73ddcf1e28 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte @@ -1,239 +1,74 @@ -{#snippet pendingApplyHint()} - - {getModifierKey()}↓ to apply - -{/snippet} - -{#if show} -
- {#if processing} -
- -
- {/if} - { - show = false - }} - onSendRequest={async (instructions) => { - if (!selection || processing) { - return - } - - processing = true - - try { - const reply = await aiChatManager.sendInlineRequest(instructions, selectedCode, selection) - if (reply) { - await aiChatManager.applyScriptEditorCode(reply) - } - } catch (error) { - console.error('Inline AI request failed:', error) - if (error instanceof Error) { - sendUserToast('AI request failed: ' + error.message, true) - } else { - sendUserToast('AI request failed: Unknown error', true) - } - } finally { - processing = false - } - - focusInput() - }} - showContext={false} - className="-ml-2" - bottomRightSnippet={aiChatManager.pendingNewCode ? pendingApplyHint : undefined} - loading={processing} - onCancel={() => aiChatManager.cancelInlineRequest('user pressed stop')} - disabled={processing} - /> -
-{/if} +
onClose(false) }} +> + onClose(true)} + /> +
diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index fa2d676590..a38a63cb15 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -7,8 +7,8 @@ contextElementKey, createAttachedFileContextElement, isMentionContext, + isPickContext, isSameContextElement, - type AppDomSelectorElement, type ContextElement } from './context' import { AIMode } from './AIChatManager.svelte' @@ -85,19 +85,10 @@ onEditEnd?: () => void className?: string onClickOutside?: () => void - onSendRequest?: (instructions: string) => void showContext?: boolean - bottomRightSnippet?: Snippet /** Shows "Press Esc again to clear" next to the send button. */ clearHint?: boolean onKeyDown?: (e: KeyboardEvent) => void - // When provided, overrides `chatHost.loading` for the send/stop - // button — useful for callers driving their own request lifecycle - // (e.g. the inline ⌘K widget runs requests outside the global - // `chatHost.loading` flag). - loading?: boolean - // Called when the user clicks Stop. Defaults to `chatHost.cancel()`. - onCancel?: () => void // Observe the composer draft as it changes (the text is local state — // `chatHost.instructions` only carries programmatic prompts). Used by // sessions to persist the typed-but-unsent prompt with the session draft. @@ -144,13 +135,9 @@ onEditEnd = () => {}, className = '', onClickOutside = () => {}, - onSendRequest = undefined, showContext = true, - bottomRightSnippet, clearHint = false, onKeyDown = undefined, - loading, - onCancel, onDraftChange = undefined, initialAttachments = undefined, onAttachmentsChange = undefined, @@ -637,9 +624,7 @@ chatHost.mode === AIMode.GLOBAL ) - const domSelectorChips = $derived( - (selectedContext ?? []).filter((c): c is AppDomSelectorElement => c.type === 'app_dom_selector') - ) + const pickChips = $derived((selectedContext ?? []).filter(isPickContext)) const contextKey = contextElementKey @@ -984,6 +969,12 @@ chatManager.contextManager?.consumeMentionContext() } + /** Apart from the mentions, which an answer to a question consumes too: it carries no pick. */ + function consumePicksIfGlobal() { + if (chatHost.mode !== AIMode.GLOBAL) return + chatManager.contextManager?.consumePickContext() + } + /** `midTurn`: Ctrl/⌘+Enter, which sends a message queued behind a running turn into that * turn instead of after it (`ChatViewHost.sendQueuedMidTurn`). */ function sendRequest({ midTurn = false }: { midTurn?: boolean } = {}) { @@ -1036,6 +1027,7 @@ ) // Consumed at enqueue, not at flush: the entry above pinned them. consumeMentionsIfGlobal() + consumePicksIfGlobal() contextTextareaComponent?.clearForSend() } // With an empty composer, this marks what is already queued. @@ -1063,6 +1055,7 @@ // when given no override, and the consume below empties it. const carried = chatHost.mode === AIMode.GLOBAL ? [...selectedContext] : undefined consumeMentionsIfGlobal() + consumePicksIfGlobal() // A host that refuses the turn puts the draft back itself (see AIChatManager's // restoreToInput and FlowChatViewHost's upload failure): restoring here too // would double the text and every attachment. @@ -1072,8 +1065,7 @@ images: sent.images, files: sent.files, blobs: sent.blobs, - contextOverride: carried, - contextOverrideOrigin: carried ? 'pinned' : undefined + contextOverride: carried }) // clearForSend() pre-zaps the textarea's mention-sync so the wipe doesn't // drop `selectedContext` before the send has settled its context: the pin @@ -1086,9 +1078,6 @@ } } - // A custom `onSendRequest` consumer (e.g. the inline ⌘K widget) has no chip - // display, so it gets the fully expanded text; the default path keeps tokens - // for the conversation bubble and expands them for the LLM inside the manager. /** Enter in a plain textarea. Ctrl/⌘ sends without stopping, and that press stops here for * the same reason as in `ContextTextarea`: pages bind their own Ctrl/⌘+Enter on the window. */ function sendFromEnter(e: KeyboardEvent) { @@ -1098,14 +1087,6 @@ sendRequest({ midTurn }) } - function submitRequest(options: { midTurn?: boolean } = {}) { - if (onSendRequest) { - onSendRequest(expanded(chatDraft(draft.text, draft.pastes))) - } else { - sendRequest(options) - } - } - $effect(() => { if (editingMessageIndex !== null) { focusInput() @@ -1342,12 +1323,11 @@ - {@const isLoading = (loading ?? chatHost.loading) && !questionAnsweredBySend} + {@const isLoading = chatHost.loading && !questionAnsweredBySend} {@const emptyDraft = draft.isEmpty} + parity — mirrors the sendRequest guard. Editor copilots need content. --> {@const needsText = chatHost.requiresMessageText && draft.text.trim() === ''} @@ -1359,10 +1339,7 @@ pendingBlobs > 0 || ingestionHolds > 0 || needsText || - (emptyDraft && - (onSendRequest !== undefined || - chatHost.mode !== AIMode.GLOBAL || - selectedContext.length === 0))} + (emptyDraft && (chatHost.mode !== AIMode.GLOBAL || selectedContext.length === 0))}
@@ -1389,9 +1366,9 @@ disabled={!isLoading && sendDisabled} on:click={() => { if (isLoading) { - onCancel ? onCancel() : chatHost.cancel() + chatHost.cancel() } else if (!sendDisabled) { - submitRequest() + sendRequest() } }} /> @@ -1399,11 +1376,11 @@ {/snippet} {#snippet badgeRow()} - {@const contextChips = showContext ? selectedContext : domSelectorChips} + {@const contextChips = showContext ? selectedContext : pickChips} {#if contextChips.length > 0 || draft.files.length > 0 || pendingFiles > 0 || draft.blobs.length > 0 || pendingBlobs > 0}
{#each contextChips as element (contextKey(element))} @@ -1502,7 +1479,6 @@ !e.defaultPrevented && e.target instanceof HTMLTextAreaElement && editingMessageIndex === null && - onSendRequest === undefined && draft.isEmpty && pendingImages === 0 && pendingFiles === 0 && @@ -1515,9 +1491,8 @@ // Empty means no attachment still decoding/reading either — // recalling over an attachments-only draft would clobber it. // Textarea only — ArrowUp on the wrapper's buttons/badges must not - // mutate the composer; and main composer only — the edit input and - // custom-send consumers (inline widget) have their own history - // semantics. + // mutate the composer; and main composer only — the edit input has + // its own history semantics. if ( chatHost.queuedMessage || chatHost.queuedImages.length > 0 || @@ -1564,7 +1539,7 @@ if (disabled) { return } - submitRequest({ midTurn: withModifier }) + sendRequest({ midTurn: withModifier }) }} {disabled} {onKeyDown} @@ -1582,7 +1557,7 @@ {@render toolbarRow()} {/snippet} - {#if !bottomRightSnippet && !toolbarInBox} + {#if !toolbarInBox}
{@render sendStopButton()}
@@ -1623,11 +1598,9 @@ class={twMerge('resize-none', CHAT_INPUT_PADDING)} {disabled} > - {#if !bottomRightSnippet} -
- {@render sendStopButton()} -
- {/if} +
+ {@render sendStopButton()} +
{#if showAppContextTooltip} @@ -1681,20 +1654,13 @@ class={twMerge('resize-none', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING)} {disabled} > - {#if !bottomRightSnippet} -
- {@render sendStopButton()} -
- {/if} +
+ {@render sendStopButton()} +
{/if} {#if toolbar && !toolbarInBox}
{@render toolbar()}
{/if} - {#if bottomRightSnippet} -
- {@render bottomRightSnippet()} -
- {/if} diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 82461684cc..a86d8e30e4 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -47,11 +47,7 @@ import type { ChatCompletionMessageParam, ChatCompletionSystemMessageParam } from 'openai/resources/chat/completions.mjs' -import { - prepareInlineChatSystemPrompt, - prepareScriptSystemMessage, - prepareScriptTools -} from './script/core' +import { prepareScriptSystemMessage, prepareScriptTools } from './script/core' import type { ScriptLintResult } from './shared' import { navigatorTools, prepareNavigatorSystemMessage } from './navigator/core' import { loadApiTools } from './api/apiTools' @@ -127,11 +123,13 @@ import { createAppFrontendFileContextElement, flattenDatatablesToAppContextElements, isMentionContext, + isPickContext, isSameContextElement, + type CodeSelection, type ContextElement, + type PickContext, type AppDatatableElement } from './context' -import type { Selection } from 'monaco-editor' import type AIChatInput from './AIChatInput.svelte' import { prepareApiSystemMessage, prepareApiUserMessage } from './api/core' import { @@ -471,7 +469,7 @@ function refreshFreeTierUsage(workspace: string | undefined) { * context snapshot always move together so a flush can't drop one. */ type QueuedEntry = { draft: DraftSnapshot - context: ContextElement[] | undefined + context: ContextElement[] } /** Plan mode's view of the chat it runs in. A function rather than an object literal in the @@ -537,7 +535,6 @@ export class AIChatManager implements ChatViewHost { /** Markdown artifacts the copilot created for the current session. */ artifacts = new SessionArtifactsStore() abortController: AbortController | undefined = undefined - inlineAbortController: AbortController | undefined = undefined // Flag to skip Responses API if it's not available (e.g., Azure region doesn't support it) skipResponsesApi = $state(false) @@ -2881,7 +2878,8 @@ export class AIChatManager implements ChatViewHost { #takeQueue(): QueuedEntry { const taken = { draft: this.#queuedDraft.take(), - context: this.queuedContext + // Not undefined, which would send the live selection: that of the next message. + context: this.queuedContext ?? [] } this.queuedContext = undefined this.#queueSendsMidTurnIn = undefined @@ -2913,7 +2911,7 @@ export class AIChatManager implements ChatViewHost { images: queued.draft.images, files: queued.draft.files }) - if (queued.context?.length) { + if (queued.context.length) { const merged = [...queued.context] for (const c of this.queuedContext ?? []) { if (!merged.some((m) => isSameContextElement(m, c))) { @@ -2924,33 +2922,23 @@ export class AIChatManager implements ChatViewHost { } } - /** Put a draft's pinned DOM selector chips back as the live selection, so the - * restored draft and the selection stay coherent (its instruction targets the - * element it was written for). No-op when the draft pinned no DOM chips, so a - * plain-text draft leaves the live selection untouched. + /** Put a draft's pinned picks back as the live selection, so the restored draft and the + * selection stay coherent (its instruction targets what it was written for). No-op when + * the draft pinned none, so a plain-text draft leaves the live selection untouched. * * `keepExisting` when the restored text was merged into a draft the user was * already writing: that draft's own chips must survive alongside, or its - * instruction — still sitting in the composer — would be retargeted at this - * draft's element. Otherwise the restore replaces, since any chip selected - * since belongs to a draft that is being replaced too. */ - #restoreDomContext(context: ContextElement[] | undefined, keepExisting = false) { - const domChips = (context ?? []).filter((c) => c.type === 'app_dom_selector') - if (domChips.length === 0) return - const existing = keepExisting - ? (this.contextManager?.getSelectedContext().filter((c) => c.type === 'app_dom_selector') ?? - []) - : [] - this.contextManager?.clearSelectedDomElements() - // addSelectedDomElement dedups on (selector, appPath), so a chip both drafts - // share collapses to one. - for (const c of [...domChips, ...existing]) { - this.contextManager?.addSelectedDomElement(c) - } + * instruction, still sitting in the composer, would be retargeted at this + * draft's pick. Otherwise the restore replaces preview elements, since any + * selected since belongs to a draft that is being replaced too. */ + #restorePickContext(context: ContextElement[] | undefined, keepExisting = false) { + const picks = (context ?? []).filter(isPickContext) + if (picks.length === 0) return + this.contextManager?.restorePickContext(picks, keepExisting) } /** Give back the mentions a send carried when its text returns to the composer, - * so its `@` tokens still have entries to bind to. Additive, unlike the DOM + * so its `@` tokens still have entries to bind to. Additive, unlike the pick * restore above: dropping the entries this send did not carry would strand the * tokens naming them in a draft whose text now shares the same composer. * @@ -2976,7 +2964,9 @@ export class AIChatManager implements ChatViewHost { * * Gated on `sendInFlight` as well as `loading`: `loading` only rises after a * send's attachment upkeep, so between the two a click would slip past. */ - sendOrQueue(text: string, context?: ContextElement[]) { + sendOrQueue(text: string, picks: PickContext[] = []) { + // The composer's own picks stay there: they belong to the draft being written in it. + const context = [...this.#contextWithoutPicks(), ...picks] if (this.loading || this.sendInFlight || this.sendPending) { this.queueMessage(text, [], context) return @@ -2984,6 +2974,10 @@ export class AIChatManager implements ChatViewHost { void this.sendRequest({ instructions: text, contextOverride: context }) } + #contextWithoutPicks(): ContextElement[] { + return this.contextManager.getSelectedContext().filter((c) => !isPickContext(c)) + } + /** Remove the queued message and put it back into the input, images included. */ dequeueMessage() { if (!this.#hasQueuedMessage()) { @@ -2999,27 +2993,31 @@ export class AIChatManager implements ChatViewHost { // the composer targets the element the draft was written for, not whatever // is selected now. If its text was prepended onto an existing draft, that // draft's chips are kept too — both instructions now share one composer. - this.#restoreDomContext(queued.context, mergedIntoDraft) + this.#restorePickContext(queued.context, mergedIntoDraft) // The queue aggregates several enqueues into one entry and records no // originating mode, so the mode now is the closest signal available. A // recall after a mid-turn mode switch can therefore miss a restore. this.#restoreMentionContext(queued.context, this.mode) } - /** Put what the user typed back where they can see it: into the input - * when it's mounted, otherwise back into the queue so it reappears with - * the chat panel instead of being silently dropped. */ + /** Put what the user typed back where they can see it, with its picks: into the input + * when it's mounted, beside the picks there, otherwise back into the queue so it reappears + * with the chat panel instead of being silently dropped. */ private restoreToInput( text: string, images: AttachedImage[] = [], - files: AttachedTextFile[] = [] + files: AttachedTextFile[] = [], + context: ContextElement[] = [] ): boolean { if (this.aiChatInput) { - return this.aiChatInput.prependText(text, images, files) === true + const mergedIntoDraft = this.aiChatInput.prependText(text, images, files) === true + this.#restorePickContext(context, true) + return mergedIntoDraft } // Merge onto anything already queued (see #restoreQueue) — replacing would // silently drop a message queued while this one was in flight. - this.#queuedDraft.prepend({ text, images, files }) + const draft = { text, images, files, pastes: [], blobs: [] } + this.#restoreQueue({ draft, context }) return false } @@ -3593,29 +3591,28 @@ export class AIChatManager implements ChatViewHost { } } - // Roll a turn that produced nothing usable back out of the transcript and - // hand its text back to the composer for editing/resending. `restoreToInput` - // is false when a queued message is about to take over (a user cancel with - // something queued) — then the rolled-back prompt is dropped rather than - // shoved back into the input, so the handoff to the queued message is clean. - private restoreUnsentTurn = async ( - displayLenAfterUser: number, - modelLenAfterUser: number, - instructions: string, - pastes: PasteAttachment[], - restoreToInput: boolean = true, - images: AttachedImage[] = [], - files: AttachedTextFile[] = [] - ): Promise => { + /** Hand a rolled-back message back to the composer with its picks and mentions, or with none + * of them: on a draft that declined the text, they would retarget what is being written. */ + #returnToComposer( + draft: Pick, + context: ContextElement[] | undefined, + originMode: AIMode, + { replacePicks = false } = {} + ) { + const { text, pastes, images, files } = draft + if (!this.aiChatInput?.restoreInstructions(text, pastes, images, files)) return + this.#restorePickContext(context, !replacePicks) + this.#restoreMentionContext(context, originMode) + } + + // Roll a turn that produced nothing usable back out of the transcript. + #dropUnsentTurn(displayLenAfterUser: number, modelLenAfterUser: number) { this.displayMessages = this.displayMessages.slice(0, displayLenAfterUser - 1) this.messages = this.messages.slice(0, modelLenAfterUser - 1) // The rolled-back turn's files must not stay registered: the message // referencing them is gone, so leaving them would keep stale content // readable by the tools on later turns. this.#syncMessageFiles() - if (!restoreToInput) return false - // An occupied composer declines the restore and keeps its own draft. - return this.aiChatInput?.restoreInstructions(instructions, pastes, images, files) === true } // Bytes each live composer has staged toward its next send (committed @@ -3912,92 +3909,6 @@ export class AIChatManager implements ChatViewHost { } } - sendInlineRequest = async (instructions: string, selectedCode: string, selection: Selection) => { - // Validate inputs - if (!instructions.trim()) { - throw new Error('Instructions are required') - } - // Use a separate abort controller for inline requests to avoid interfering with main chat - this.inlineAbortController = new AbortController() - const lang = this.scriptEditorOptions?.lang ?? 'bun' - const selectedContext: ContextElement[] = [...this.contextManager.getSelectedContext()] - const startLine = selection.startLineNumber - const endLine = selection.endLineNumber - selectedContext.push({ - type: 'code_piece', - lang, - title: `L${startLine}-L${endLine}`, - startLine, - endLine, - content: selectedCode - }) - - const systemMessage: ChatCompletionSystemMessageParam = { - role: 'system', - content: prepareInlineChatSystemPrompt(lang, { - workflowAsCode: this.scriptEditorOptions?.workflowAsCode ?? false - }) - } - - let reply = '' - - try { - const userMessage = prepareScriptUserMessage(instructions, selectedContext) - const messages = [userMessage] - - const params = { - messages, - abortController: this.inlineAbortController, - callbacks: { - onNewToken: (token: string) => { - reply += token - }, - onMessageEnd: () => {}, - setToolStatus: () => {}, - removeToolStatus: () => {} - }, - systemMessage - } - - await this.chatRequest({ ...params }) - - // Validate we received a response - if (!reply.trim()) { - throw new Error('AI response was empty') - } - - // Try to extract new code from response - const newCodeMatch = reply.match(/([\s\S]*?)<\/new_code>/i) - if (newCodeMatch && newCodeMatch[1]) { - const code = newCodeMatch[1].trim() - if (!code) { - throw new Error('AI response contained empty code block') - } - return code - } - - // Fallback: try to take everything after the last tag - const lastNewCodeMatch = reply.match(/([\s\S]*)/i) - if (lastNewCodeMatch && lastNewCodeMatch[1]) { - const code = lastNewCodeMatch[1].trim().replace(/```/g, '') - if (!code) { - throw new Error('AI response contained empty code block') - } - return code - } - - // If no code tags found, throw error with helpful message - throw new Error('AI response did not contain valid code. Please try rephrasing your request.') - } catch (error) { - // if abort controller is aborted, don't throw an error - if (this.inlineAbortController?.signal.aborted) { - return - } - console.error('Unexpected error in sendInlineRequest:', error) - throw new Error('An unexpected error occurred. Please try again.') - } - } - // Optional pre-flight hook called once per send, after the user's message // bubble + loading indicator are shown optimistically but before the request // goes out. Sessions use this to commit/materialise the workspace (creating a @@ -4115,13 +4026,7 @@ export class AIChatManager implements ChatViewHost { return undefined } - const { draft, context = [] } = this.#takeQueue() - // Pinned at enqueue, so consumed from the live selection as any pinned send does. - for (const c of context) { - if (c.type === 'app_dom_selector') { - this.contextManager?.removeSelectedDomElement(c.selector, c.appPath) - } - } + const { draft, context } = this.#takeQueue() if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) { this.contextManager?.updateContextOnRequest({}) } @@ -4175,8 +4080,7 @@ export class AIChatManager implements ChatViewHost { } // The shared manager has no chat on screen: turns render only in a session's own chat. // One started here would still stream, spend tokens and apply tool calls, entirely - // off-screen, so refuse it. `sendInlineRequest` is exempt: the ⌘K widget renders its own - // composer inside Monaco. + // off-screen, so refuse it. if (this === aiChatManager) { console.error('sendRequest called with no chat UI mounted; dropping the turn') sendUserToast('This action needs the AI chat. Start an AI session to continue.', true) @@ -4212,7 +4116,8 @@ export class AIChatManager implements ChatViewHost { this.restoreToInput( expanded(chatDraft(options.instructions ?? this.instructions, options.pastes ?? [])), options.images, - options.files + options.files, + options.contextOverride ) } sendUserToast( @@ -4248,12 +4153,6 @@ export class AIChatManager implements ChatViewHost { // contextManager. Set whenever a send settles its context ahead of the // turn: a composer submit at the click, a queued message at enqueue. contextOverride?: ContextElement[] - /** Where `contextOverride` came from. 'pinned' (default): the chips were - * selected for THIS message, so they are consumed from the live selection - * on send. 'replay': an edit/retry resending an older message's context — - * those chips were consumed long ago, and removing them again would strip - * an identical selection the user has since made in the composer. */ - contextOverrideOrigin?: 'pinned' | 'replay' /** Auto-send of a queued draft: on preflight failure the caller re-queues * it, so the composer restore must not also fire (the draft would exist * twice — queue chip and composer). */ @@ -4327,6 +4226,8 @@ export class AIChatManager implements ChatViewHost { // resolved to `/clear` or `/compact` must not strand its resend reservation. if (COMPACT_COMMAND_RE.test(trimmed) || CLEAR_COMMAND_RE.test(trimmed)) { this.#releaseOutgoingReservation(reservationKey) + // It carries no pick either. + this.#restorePickContext(options.contextOverride, true) } // `/compact`: summarize the conversation locally to free up context. if (COMPACT_COMMAND_RE.test(trimmed)) { @@ -4396,17 +4297,16 @@ export class AIChatManager implements ChatViewHost { // restore is keyed to requestedMode: a GLOBAL submit whose mode // flipped during the upkeep awaits above still gets its mentions // back, while a send that started outside GLOBAL consumed none. - const taken = - this.aiChatInput?.restoreInstructions( - this.instructions, + this.#returnToComposer( + { + text: this.instructions, pastes, - options.images ?? [], - options.files ?? [] - ) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + images: options.images ?? [], + files: options.files ?? [] + }, + options.contextOverride, + requestedMode + ) } return false } @@ -4434,7 +4334,7 @@ export class AIChatManager implements ChatViewHost { // that does not write a token would break that and need one here. if (!this.instructions.trim() && files.length === 0) { sendUserToast(`${sendModel.model} can't read images. Switch to a vision model first.`, true) - if (!options.queued) this.restoreToInput('', requestedImages) + if (!options.queued) this.restoreToInput('', requestedImages, [], options.contextOverride) return false } sendUserToast( @@ -4459,7 +4359,12 @@ export class AIChatManager implements ChatViewHost { // awaits above occupies the composer, and this restore must merge // into it (or queue), never be refused by it. if (!options.queued) { - this.restoreToInput(expanded(chatDraft(this.instructions, pastes)), images, files) + this.restoreToInput( + expanded(chatDraft(this.instructions, pastes)), + images, + files, + options.contextOverride + ) } sendUserToast('This session is running in another tab. Your message was kept.', true) } @@ -4517,16 +4422,11 @@ export class AIChatManager implements ChatViewHost { console.error('AIChatManager beforeSend hook failed', e) rollbackOptimisticSend() if (!options.queued) { - // Mentions were consumed at submit, so they come back with the text or - // not at all. Only when the composer took it: it declines when the - // user has started a new draft, and restoring then would put these - // mentions on that draft and every turn after it. - const taken = - this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + this.#returnToComposer( + { text: this.instructions, pastes, images, files }, + options.contextOverride, + requestedMode + ) } sendUserToast( `Could not prepare the session before sending: ${ @@ -4584,14 +4484,11 @@ export class AIChatManager implements ChatViewHost { }) if (accepted === false) this.#restoreQueue(next) } else { - // Same pairing as the beforeSend catch above: mentions ride back with the - // text, only if the composer took it. - const taken = - this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + this.#returnToComposer( + { text: this.instructions, pastes, images, files }, + options.contextOverride, + requestedMode + ) } return true } @@ -4692,27 +4589,16 @@ export class AIChatManager implements ChatViewHost { // it belongs to whatever the user has selected since. Otherwise read the // current selection. const oldSelectedContext = - options.contextOverride ?? this.contextManager?.getSelectedContext() ?? [] - // DOM selector chips are one-shot: they ride with this message (captured in + options.contextOverride ?? + (options.synthetic + ? this.#contextWithoutPicks() + : (this.contextManager?.getSelectedContext() ?? [])) + // Pick chips are one-shot: they ride with this message (captured in // oldSelectedContext) and render above it, but must not persist in the input - // for the next turn. Clearing here leaves oldSelectedContext untouched. - if (options.contextOverrideOrigin === 'replay') { - // Edit/retry: the override is a copy of an already-sent message's - // context, consumed on its original send. The live selection belongs to - // the composer's own draft — touching it here would strip it. - } else if (options.contextOverride) { - // A pinned submit consumes only the chips it carried. Drop just those - // from the live selection (still there if the user didn't re-select); a - // newer selection made since is left intact. - for (const c of options.contextOverride) { - if (c.type === 'app_dom_selector') { - // Match appPath too: another app's live chip can share this - // selector, and dropping it would discard a newer selection. - this.contextManager?.removeSelectedDomElement(c.selector, c.appPath) - } - } - } else { - this.contextManager?.clearSelectedDomElements() + // for the next turn. Whoever pinned a snapshot has already taken them out: what + // is live then, or when the client sends, is the composer's next message's. + if (!options.contextOverride && !options.synthetic) { + this.contextManager?.consumePickContext() } if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) { this.contextManager?.updateContextOnRequest(options) @@ -4793,7 +4679,7 @@ export class AIChatManager implements ChatViewHost { } : m ) - // For restoreUnsentTurn: the compact composer form (with paste tokens), + // For the restore after a rollback: the compact composer form (with paste tokens), // not the expanded LLM text, plus the rollback anchor after the user turn. const sentInstructions = this.instructions const sentPastes = pastes @@ -4872,7 +4758,7 @@ export class AIChatManager implements ChatViewHost { this.modifiedItems ? [...this.modifiedItems] : undefined ) } - // Rollback anchors for restoreUnsentTurn: captured after compaction so + // Rollback anchors for #dropUnsentTurn: captured after compaction so // they index into the (possibly compacted) stored history. The summary // path shrinks displayMessages too, so the display anchor must also be // read here, not before compaction. @@ -5107,27 +4993,16 @@ export class AIChatManager implements ChatViewHost { // about to auto-send (see the flush below) — drop the rolled-back // prompt instead of restoring it to the input so the handoff is clean. const willAutoSendQueued = this.wasCancelledByUser() && this.#hasQueuedMessage() - const textRestored = await this.restoreUnsentTurn( - displayLenAfterUser, - modelLenAfterUser, - sentInstructions, - sentPastes, - !willAutoSendQueued, - sentImages, - files - ) - // restoreUnsentTurn hands the text/pastes/images back for a resend, but - // the DOM selector chips were already consumed from the live selection - // before the request went out. Restore this turn's own chips so the - // resend keeps its element scope — replacing (not merging) any chips - // selected during the stream, so the restored draft stays coherent. - // Only when the composer actually took the text back: on a queued-message - // handoff, or when a draft typed during the stream made the composer - // decline, this prompt is dropped — restoring its chips would then - // retarget whatever draft is sitting there. - if (textRestored) { - this.#restoreDomContext(oldSelectedContext) - this.#restoreMentionContext(oldSelectedContext, requestedMode) + this.#dropUnsentTurn(displayLenAfterUser, modelLenAfterUser) + if (!willAutoSendQueued) { + // Elements picked during the stream are replaced, so that the restored + // draft stays coherent. + this.#returnToComposer( + { text: sentInstructions, pastes: sentPastes, images: sentImages, files }, + oldSelectedContext, + requestedMode, + { replacePicks: true } + ) } if (this.displayMessages.length === 0) { // saveChat no-ops on an empty transcript; the chat persisted earlier @@ -5329,15 +5204,6 @@ export class AIChatManager implements ChatViewHost { this.cancelLoadingTools() } - cancelInlineRequest = (reason?: string) => { - const cancelReason = reason ?? 'inline_cancelled' - console.log('cancelling inline request:', { - reason: cancelReason, - inlineAbortController: this.inlineAbortController - }) - this.inlineAbortController?.abort(cancelReason) - } - /** * The images of a stored user turn as the model saw them. Anything resending * a turn (retry, edit) must read them from here, never from the transcript @@ -5443,16 +5309,15 @@ export class AIChatManager implements ChatViewHost { // the element the message was about. An edit passes `editedContext` (the edit // box was seeded from this message's chips and the user may have changed // them); a bare Retry passes nothing and falls back to the original - // contextElements. `undefined` for modes that don't attach context leaves the - // live-selection behavior. An empty array is a deliberate "no context". + // contextElements. A message stored without any gets an empty array, as `undefined` + // would send the live selection, which is the composer's. this.instructions = newContent ?? userMessage.content // Prune the truncated messages' file registrations BEFORE the resend // re-registers its own — the other way around would delete the fresh rows. this.#syncMessageFiles() this.sendRequest({ pastes: pastes ?? userMessage.pastes, - contextOverride: editedContext ?? userMessage.contextElements, - contextOverrideOrigin: 'replay', + contextOverride: editedContext ?? userMessage.contextElements ?? [], images: images ?? sentImages, // The bubble copy is authoritative for files: the API message carries // only a reference (content lives in the store), so nothing ever strips @@ -5462,16 +5327,8 @@ export class AIChatManager implements ChatViewHost { }) } - addSelectedLinesToContext = ( - lines: string, - startLine: number, - endLine: number, - moduleId?: string - ) => { - if (!moduleId) { - this.changeMode(AIMode.SCRIPT) - } - this.contextManager?.addSelectedLinesToContext(lines, startLine, endLine, moduleId) + attachCodeSelection(selection: CodeSelection) { + this.contextManager.addCodeSelection(selection) this.focusInput() } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 8e4716d275..ff79739f1a 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -9,6 +9,7 @@ import type { DisplayMessage } from './shared' import type { AttachedImage } from './imageUtils' import { AIChatManager, AIMode, AIAutonomyMode, aiChatManager } from './AIChatManager.svelte' import { AIWorkMode, USE_MODE_WITHDRAWN } from './workMode' +import { createAppDomSelectorElement, createCodeSelection } from './context' import { makePasteToken } from './pasteTokens' import { PLAN_MODE_MESSAGES } from './planModeMessages' import { runChatLoop } from './chatLoop' @@ -1323,6 +1324,17 @@ describe('AIChatManager user questions', () => { }) }) +function pick(content: string, line = 1) { + return createCodeSelection( + { kind: 'script', path: 'f/a/b' }, + { content, startLine: line, endLine: line, lang: 'bun' } + ) +} + +function element(selector: string) { + return createAppDomSelectorElement({ selector, appPath: 'f/app', tagName: 'div' }) +} + describe('AIChatManager queued messages', () => { const model = { provider: 'openai', model: 'gpt-4o' } @@ -1639,6 +1651,14 @@ describe('AIChatManager queued messages', () => { .filter((c) => c.type === 'app_dom_selector') .map((c) => c.selector) ).toEqual(['div.a']) + + // Nor when the message was stored without context. + seed() + delete (manager.displayMessages[0] as any).contextElements + manager.restartGeneration(0) + await vi.waitFor(() => expect(manager.displayMessages[0]).toHaveProperty('contextElements')) + expect(sentChipSelectors()).toEqual([]) + expect(cm.getSelectedContext()).toEqual([chipA]) }) // The loop, not the send, owns the vision strip: it re-applies it per iteration @@ -2528,7 +2548,7 @@ describe('AIChatManager queued messages', () => { const input = createInputMock() const manager = createManager(input) replyWith('done') - // cancel before any usable output → the rollback (restoreUnsentTurn) path + // cancel before any usable output → the rollback path mocks.runChatLoop.mockImplementationOnce(async ({ abortController }: any) => { abortController.abort('user_cancelled') throw new Error('aborted') @@ -2950,8 +2970,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'why does this retry', - contextOverride: carried, - contextOverrideOrigin: 'pinned' + contextOverride: carried }) expect(cm.getSelectedContext()).toEqual([mention]) @@ -2975,8 +2994,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'why does this retry', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(cm.getSelectedContext()).toEqual([mention]) @@ -2995,8 +3013,7 @@ describe('AIChatManager queued messages', () => { const pending = manager.sendRequest({ instructions: 'describe this image', images: [{ id: 'img-1', dataUrl: 'data:image/png;base64,AAAA' } as any], - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) manager.mode = AIMode.SCRIPT await pending @@ -3037,6 +3054,73 @@ describe('AIChatManager queued messages', () => { expect(chips.map((c) => c.selector)).toEqual(['div.a']) }) + it('carries code attached in a session on its next message, and only there', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + const selection = pick('return 1', 2) + manager.listenForContextChange({}, 'parent') + manager.attachCodeSelection(selection) + // The composer's context is rebuilt whenever the page's workspace or its schemas change. + manager.listenForContextChange({}, 'parent') + manager.listenForContextChange({}, 'fork') + expect(manager.mode).toBe(AIMode.GLOBAL) + + await manager.sendRequest({ instructions: 'make it 2' }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('path: f/a/b, lines 2-2:\n```bun\nreturn 1\n```') + expect(manager.contextManager.getSelectedContext()).toEqual([]) + }) + + it('sends a queued message with its own picks and leaves the next one its own', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + manager.queueMessage('first', [], [pick('before')]) + // The lines change and are queued again, then picked once more as they were at first. + manager.queueMessage('second', [], [pick('after')]) + manager.attachCodeSelection(pick('before')) + + await manager.sendRequest({ instructions: 'running', contextOverride: [] }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('before') + expect(messages.at(-1).content).toContain('after') + expect(manager.contextManager.getSelectedContext()).toEqual([pick('before')]) + }) + + it('leaves what is attached for the next message out of one queued without it', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + const selection = pick('return 1', 2) + manager.queueMessage('queued') + manager.attachCodeSelection(selection) + + await manager.sendRequest({ instructions: 'running', contextOverride: [] }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('queued') + expect(messages.at(-1).content).not.toContain('SELECTED CODE') + expect(manager.contextManager.getSelectedContext()).toEqual([selection]) + }) + + it('leaves code attached in the composer there when a prompt sent past it comes back', () => { + const manager = createManager(createInputMock()) + manager.attachCodeSelection(pick('for the composer')) + manager.loading = true + manager.sendOrQueue('make it red', [element('div.prompt')]) + + manager.dequeueMessage() + + expect(manager.contextManager.getSelectedContext()).toEqual([ + element('div.prompt'), + pick('for the composer') + ]) + }) + // Restoration is only coherent when the text it belongs to actually lands in the // composer. Both cases below leave another draft sitting there, so replacing its // chips would silently retarget an instruction the user is still writing. @@ -3151,8 +3235,7 @@ describe('AIChatManager queued messages', () => { const accepted = await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(accepted).toBe(false) @@ -3172,8 +3255,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(mocks.runChatLoop).not.toHaveBeenCalled() @@ -3214,8 +3296,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(manager.contextManager.getSelectedContext()).toEqual([]) @@ -3234,8 +3315,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(manager.contextManager.getSelectedContext()).toEqual([]) @@ -5043,6 +5123,25 @@ describe('AIChatManager cross-tab run seams', () => { expect(manager.queuedMessage).toBe('race loser') }) + it.each([ + ['at the start of the send', () => true], + // Announced during the send's own awaits. + ['once it is under way', (reads: number) => reads > 1] + ])('keeps the pick of a refused prompt, refused %s', async (_, held) => { + const manager = new AIChatManager() + manager.isSessionChat = true + manager.mode = AIMode.GLOBAL + let reads = 0 + manager.runHeldElsewhereResolver = () => held(++reads) + const selection = element('div.prompt') + + manager.sendOrQueue('make it red', [selection]) + + await vi.waitFor(() => expect(manager.queuedMessage).toBe('make it red')) + expect(mocks.runChatLoop).not.toHaveBeenCalled() + expect(manager.queuedContext).toEqual([selection]) + }) + // A synthetic (auto-resume) prompt is client-authored: a refusal must // release it rather than hand it back as a draft the user never wrote — // staged instructions would otherwise block every later auto-resume. diff --git a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte index dd94b076ea..73d26f1906 100644 --- a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte @@ -37,6 +37,8 @@ // (the composer keeps every badge the same size). const COMPACT_TYPES = new Set([ 'app_dom_selector', + 'code_piece', + 'flow_module_code_piece', 'workspace_app', 'workspace_agent', 'workspace_script', diff --git a/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts b/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts index 18190290b5..cf7ebf58fa 100644 --- a/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts @@ -4,9 +4,14 @@ import { SQLSchemaLanguages, type DBSchemas } from '$lib/stores' import { diffLines } from 'diff' import { createAppDomSelectorElement, + isCodeSelection, isMentionContext, + isPickContext, + isSameCodeRange, + isSameContextElement, + type CodeSelection, type ContextElement, - type FlowModuleElement + type PickContext } from './context' import type { FlowModule } from '$lib/gen' @@ -77,13 +82,13 @@ export default class ContextManager { this.availableContext = [] if (!workspace || (this.workspace !== undefined && this.workspace !== workspace)) { this.workspace = workspace - this.selectedContext = [] + // Code selections are of the session's own items, not of the workspace browsed. + this.selectedContext = currentlySelectedContext.filter(isCodeSelection) return } this.workspace = workspace this.selectedContext = currentlySelectedContext.filter( - (context) => - isMentionContext(context) + (context) => isMentionContext(context) || isCodeSelection(context) ) } @@ -250,11 +255,11 @@ export default class ContextManager { // Seed with the (refreshed) code block + everything else previously // selected. The filter further down validates each entry against - // newAvailableContext (and the per-type allowlist for code_piece / - // workspace_*); types that are auto-derived (diff/error/db) survive - // when they're still in availableContext, user-picked workspace refs - // survive unconditionally, and `code` is excluded from the carryover - // because we just rebuilt it. + // newAvailableContext (and the per-type allowlist for workspace_*); + // types that are auto-derived (diff/error/db) survive when they're + // still in availableContext, user-picked workspace refs survive + // unconditionally, and `code` is excluded from the carryover because + // we just rebuilt it. let newSelectedContext: ContextElement[] = [ { type: 'code', @@ -285,7 +290,6 @@ export default class ContextManager { newSelectedContext = newSelectedContext .filter( (c) => - (c.type === 'code_piece' && scriptOptions.getCode().includes(c.content)) || c.type === 'code' || // Workspace references are user-picked via @-mention and not in // availableContext; preserve so badges survive editor refreshes. @@ -336,6 +340,24 @@ export default class ContextManager { this.selectedContext = this.selectedContext.filter((c) => !isMentionContext(c)) } + consumePickContext() { + this.selectedContext = this.selectedContext.filter((c) => !isPickContext(c)) + } + + /** Put picks back with their message, beside those already selected or in place of them. + * Selected code always stays: it names its own lines, so it retargets no other message. */ + restorePickContext(picks: PickContext[], keepExisting: boolean) { + const rest = this.selectedContext.filter((c) => !isPickContext(c)) + const existing = this.selectedContext.filter( + (c) => isCodeSelection(c) || (keepExisting && isPickContext(c)) + ) + this.selectedContext = [ + ...rest, + ...picks, + ...existing.filter((c) => !picks.some((p) => isSameContextElement(p, c))) + ] + } + getAvailableContext() { return this.availableContext } @@ -344,52 +366,12 @@ export default class ContextManager { this.scriptOptions = scriptOptions } - addSelectedLinesToContext(lines: string, startLine: number, endLine: number, moduleId?: string) { - const title = moduleId ? `${moduleId} L${startLine}-L${endLine}` : `L${startLine}-L${endLine}` - if ( - !this.scriptOptions || - this.selectedContext.find( - (c) => - (c.type === 'code_piece' && c.title === title) || - (c.type === 'flow_module_code_piece' && c.id === moduleId && c.title === title) - ) - ) { - return - } - if (moduleId) { - const module = [...this.availableContext, ...this.selectedContext].find( - (c) => c.type === 'flow_module' && c.id === moduleId - ) as FlowModuleElement - if (!module) { - console.error('Module not found', moduleId) - return - } - this.selectedContext = [ - ...this.selectedContext, - { - type: 'flow_module_code_piece', - id: moduleId, - title: title, - startLine, - endLine, - content: lines, - lang: this.scriptOptions.lang, - value: module.value - } - ] - } else { - this.selectedContext = [ - ...this.selectedContext, - { - type: 'code_piece', - title: title, - startLine, - endLine, - content: lines, - lang: this.scriptOptions.lang - } - ] - } + /** Attach selected code. Lines already attached are replaced, as their code may have changed. */ + addCodeSelection(selection: CodeSelection) { + this.selectedContext = [ + ...this.selectedContext.filter((c) => !isCodeSelection(c) || !isSameCodeRange(c, selection)), + selection + ] } /** @@ -481,7 +463,6 @@ export default class ContextManager { } updateContextOnRequest(options: { removeDiff?: boolean; addBackCode?: boolean }) { - this.selectedContext = this.selectedContext.filter((c) => c.type !== 'code_piece') if (options.removeDiff) { this.selectedContext = this.selectedContext.filter((c) => c.type !== 'diff') } diff --git a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte b/frontend/src/lib/components/copilot/chat/InlinePrompt.svelte similarity index 51% rename from frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte rename to frontend/src/lib/components/copilot/chat/InlinePrompt.svelte index 721b3b4bfe..b1fde5ca90 100644 --- a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte +++ b/frontend/src/lib/components/copilot/chat/InlinePrompt.svelte @@ -4,20 +4,19 @@ import { ArrowUp } from 'lucide-svelte' let { - x, - y, - label, - inNewSession = false, + position = undefined, + label = undefined, + ariaLabel, onSend, onClose }: { - /** Fixed-position anchor (host viewport coords), top-left of the input. */ - x: number - y: number - /** Short element label shown as the placeholder hint (e.g. "button.btn"). */ - label: string - /** Sending leaves this page for a new AI session, so the hint says so. */ - inNewSession?: boolean + /** Fixed-position anchor (host viewport coords), top-left of the input. Without one, the + * box sits where its parent puts it. */ + position?: { x: number; y: number } + /** Short name of what the prompt is about, shown as the placeholder hint. Without one, the + * hint says that sending leaves this page for a new AI session. */ + label?: string + ariaLabel: string /** Resolving to `false` keeps the box open with its text. */ onSend: (prompt: string) => void | Promise onClose: () => void @@ -27,11 +26,15 @@ let sending = $state(false) let textarea = $state(undefined) - // Focus when the anchor first appears (the element was just selected). + // Focus when the anchor first appears (its subject was just selected). $effect(() => { textarea?.focus() }) + export function focus() { + textarea?.focus() + } + async function submit() { const v = value.trim() if (!v || sending) return @@ -44,29 +47,38 @@ } - +