From 7ec64ab33acc56870975c05f24a983bdcd146ee2 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 10 Nov 2026 17:18:32 +0000 Subject: [PATCH 01/22] perf: cut release CI wall time and build windmill-extra on its own release (#12329) * perf: cut release CI wall time and build windmill-extra on its own release Co-Authored-By: Claude Opus 5.5 * fix: wait for the ee-slim built from the release commit Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/docker-image.yml | 31 +++++----------- .github/workflows/publish_extra.yml | 56 +++++++++++++++++++++++------ docker/DockerfileExtra | 18 +++++++--- docker/DockerfileFull | 6 ++-- docker/DockerfileFullEe | 6 ++-- 5 files changed, 76 insertions(+), 41 deletions(-) diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index a5823ef19c..4ef7adc46f 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -49,7 +49,10 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ github.ref }} + # GIT_VERSION is `git describe --tags`, which needs the history and + # tags but no file contents beyond the checked-out tree fetch-depth: 0 + filter: blob:none - name: Read EE repo commit hash run: | @@ -61,7 +64,6 @@ jobs: path: ./windmill-ee-private ref: ${{ env.ee_repo_ref }} token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 @@ -123,7 +125,10 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ github.ref }} + # GIT_VERSION is `git describe --tags`, which needs the history and + # tags but no file contents beyond the checked-out tree fetch-depth: 0 + filter: blob:none - name: Read EE repo commit hash run: | @@ -135,7 +140,6 @@ jobs: path: ./windmill-ee-private ref: ${{ env.ee_repo_ref }} token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 @@ -371,8 +375,6 @@ jobs: startsWith(github.ref, 'refs/tags/v')) && (github.event_name != 'workflow_dispatch') steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - name: Login to registry uses: docker/login-action@v3 with: @@ -407,8 +409,6 @@ jobs: startsWith(github.ref, 'refs/tags/v')) steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - name: Login to registry uses: docker/login-action@v3 with: @@ -570,7 +570,7 @@ jobs: # only-fixed: true publish_ecr_s3: - needs: [build_ee_full] + needs: [build_ee] runs-on: ubicloud-standard-2-arm if: ${{ startsWith(github.ref, 'refs/tags/v') }} env: @@ -578,8 +578,6 @@ jobs: AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 @@ -591,15 +589,11 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Get version from tag - id: version - run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" - - uses: shrink/actions-docker-extract@v3 id: extract with: image: |- - ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-full:${{ steps.version.outputs.VERSION }} + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} path: "/static_frontend/." - uses: reggionick/s3-deploy@v4 @@ -615,7 +609,6 @@ jobs: steps: - uses: actions/checkout@v4 with: - fetch-depth: 0 ref: ${{ github.ref }} # - name: Set up Docker Buildx @@ -672,8 +665,6 @@ jobs: digest: ${{ steps.docker_build.outputs.digest }} steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 @@ -729,8 +720,6 @@ jobs: steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 @@ -785,8 +774,6 @@ jobs: runs-on: ubicloud steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 @@ -839,8 +826,6 @@ jobs: runs-on: ubicloud steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 diff --git a/.github/workflows/publish_extra.yml b/.github/workflows/publish_extra.yml index c1db4a654d..4f9ec08e1e 100644 --- a/.github/workflows/publish_extra.yml +++ b/.github/workflows/publish_extra.yml @@ -13,22 +13,56 @@ on: permissions: write-all jobs: - sleep: + # A release builds on its own ee-slim, pinned by digest (:latest is still the + # previous release while this one builds), and waits for its python client to + # be on PyPI, since lsp/Pipfile requires it. + base_image: runs-on: ubicloud + outputs: + image: ${{ steps.base.outputs.image }} steps: - - name: Sleep for 900 seconds waiting for pypi to update index - if: startsWith(github.ref, 'refs/tags/v') - run: sleep 900 + - name: Wait for this release's ee-slim image and PyPI client + id: base shell: bash + env: + IMAGE: ${{ env.REGISTRY }}/${{ github.repository }}-ee-slim + run: | + set -euo pipefail + if [[ "$GITHUB_REF" != refs/tags/v* ]]; then + echo "image=$IMAGE:latest" >> "$GITHUB_OUTPUT" + exit 0 + fi + version="${GITHUB_REF_NAME#v}" + deadline=$((SECONDS + 75 * 60)) + on_pypi() { + local page + page=$(curl -fsS -H 'Cache-Control: max-age=0' https://pypi.org/simple/wmill/) || return 1 + grep -qF -e "wmill-${version}-py" -e "wmill-${version}.tar.gz" <<<"$page" + } + until on_pypi; do + (( SECONDS < deadline )) || { echo "wmill $version is not on PyPI"; exit 1; } + sleep 20 + done + echo "wmill $version is on PyPI" + # A re-pushed tag finds the previous attempt's image under the same tag, + # so wait for the one built from this commit. + revision() { + docker buildx imagetools inspect "$IMAGE:$version" --format \ + '{{ index (index .Image "linux/amd64").Config.Labels "org.opencontainers.image.revision" }}' 2>/dev/null + } + until [[ "$(revision)" == "$GITHUB_SHA" ]]; do + (( SECONDS < deadline )) || { echo "$IMAGE:$version for $GITHUB_SHA was never pushed"; exit 1; } + sleep 30 + done + digest=$(docker buildx imagetools inspect "$IMAGE:$version" --format '{{.Manifest.Digest}}') + echo "image=$IMAGE@$digest" | tee -a "$GITHUB_OUTPUT" # Build and test the image before publishing test_extra: - needs: [sleep] + needs: [base_image] runs-on: ubicloud-standard-8 steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - name: Setup Bun uses: oven-sh/setup-bun@v2 @@ -62,6 +96,8 @@ jobs: context: . file: ./docker/DockerfileExtra load: true + build-args: | + BASE_IMAGE=${{ needs.base_image.outputs.image }} tags: windmill-extra:test cache-from: type=gha cache-to: type=gha,mode=max @@ -102,15 +138,13 @@ jobs: docker rm windmill-extra-test || true publish_extra: - needs: [sleep, test_extra] + needs: [base_image, test_extra] # a tag-targeted dispatch would republish the release tags unsigned, # un-verifying the release; to republish a release, re-push its tag if: github.event_name == 'push' || !startsWith(github.ref, 'refs/tags/') runs-on: ubicloud-standard-8 steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 - uses: depot/setup-action@v1 @@ -141,6 +175,8 @@ jobs: file: ./docker/DockerfileExtra platforms: linux/amd64,linux/arm64 push: true + build-args: | + BASE_IMAGE=${{ needs.base_image.outputs.image }} sbom: ${{ startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' }} tags: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest diff --git a/docker/DockerfileExtra b/docker/DockerfileExtra index 7eb2de6bf7..2c79221cf7 100644 --- a/docker/DockerfileExtra +++ b/docker/DockerfileExtra @@ -19,7 +19,10 @@ # ============================================================================ # Build final extra services image from windmill-ee-slim (includes nsjail) # ============================================================================ -FROM ghcr.io/windmill-labs/windmill-ee-slim:latest AS final +# Release builds pass this release's ee-slim by digest: at tag time :latest is +# still the previous release. +ARG BASE_IMAGE=ghcr.io/windmill-labs/windmill-ee-slim:latest +FROM ${BASE_IMAGE} AS final ARG APP=/usr/src/app @@ -138,9 +141,16 @@ RUN addgroup --gid 1000 windmill && \ # (/tmp/windmill/cache/uv) after the base already made it world-writable, leaving # root-owned 0755 dirs that make uv fail EACCES for a non-root UID. /pyls/.cache # (XDG_CACHE_HOME, incl. DENO_DIR) and /tmp/monaco are written at runtime too. -RUN chmod -R a+rX /usr/local /pyls /debugger /multiplayer /tmp/monaco && \ - chmod -R a+rw /tmp/windmill /pyls/.cache && \ - find /tmp/windmill /pyls/.cache /tmp/monaco -type d -exec chmod 777 {} + +# Each find touches only paths missing the bits (same result as chmod -R): a +# chmod on a file from an earlier layer copies it into this layer, so a blanket +# chmod -R costs 15 min and 330 MB per arch here. +RUN find /usr/local /pyls /debugger /multiplayer /tmp/monaco ! -type l \ + \( ! -perm -a+r -o -perm /111 ! -perm -a+x -o -type d ! -perm -a+x \) \ + -exec chmod a+rX {} + && \ + find /tmp/windmill /pyls/.cache ! -type d ! -type l ! -perm -a+rw \ + -exec chmod a+rw {} + && \ + find /tmp/windmill /pyls/.cache /tmp/monaco -type d ! -perm 777 \ + -exec chmod 777 {} + # Expose all service ports EXPOSE 3000 3001 3002 3003 diff --git a/docker/DockerfileFull b/docker/DockerfileFull index d145a5ffff..e1299de610 100644 --- a/docker/DockerfileFull +++ b/docker/DockerfileFull @@ -70,5 +70,7 @@ RUN apt-get install -y r-base-dev \ # Fix UV cache permissions for non-root user support (uid 1000, etc.) # The uv tool install ansible command populates the UV cache with root-owned files -RUN chmod -R a+rw /tmp/windmill/cache/uv && \ - find /tmp/windmill/cache/uv -type d -exec chmod 777 {} + +# Only paths missing the bits are touched: a chmod on a file from an earlier layer +# copies it into this layer, so a blanket chmod -R costs minutes per arch. +RUN find /tmp/windmill/cache/uv \( -type d ! -perm 777 -exec chmod 777 {} + \) \ + -o \( ! -type d ! -type l ! -perm -a+rw -exec chmod a+rw {} + \) diff --git a/docker/DockerfileFullEe b/docker/DockerfileFullEe index 8ca1067f7a..3b9817d96d 100644 --- a/docker/DockerfileFullEe +++ b/docker/DockerfileFullEe @@ -104,5 +104,7 @@ RUN apt-get install -y libsasl2-modules-gssapi-mit krb5-user # Fix UV cache permissions for non-root user support (uid 1000, etc.) # The uv tool install ansible command populates the UV cache with root-owned files -RUN chmod -R a+rw /tmp/windmill/cache/uv && \ - find /tmp/windmill/cache/uv -type d -exec chmod 777 {} + +# Only paths missing the bits are touched: a chmod on a file from an earlier layer +# copies it into this layer, so a blanket chmod -R costs minutes per arch. +RUN find /tmp/windmill/cache/uv \( -type d ! -perm 777 -exec chmod 777 {} + \) \ + -o \( ! -type d ! -type l ! -perm -a+rw -exec chmod a+rw {} + \) From f9a797281218d331cc0898fbca87e155959f5ae0 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Tue, 10 Nov 2026 18:19:42 +0100 Subject: [PATCH 02/22] docs: say saved ai agents also run on their own as a one-step flow (#12308) * docs: say saved ai agents also run on their own as a one-step flow Co-Authored-By: Claude Opus 5.5 * docs: agent runs drop saved history inputs on every run; the editor chat is a preview Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F4rzFpemqD4pqLnAp4qRqF --------- Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 3 +++ CONTEXT.md | 10 ++++++++-- docs/reusable-ai-agents.md | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b3d13d1466..a06bc3676f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,9 @@ Open-source platform for internal tools, workflows, API integrations, background - **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace settings that let operators compose flows, AI agents and full-code apps, what the composition check must cover, which raw-app endpoint stays closed on purpose, and why either right costs a full seat +- **AI agents**: `docs/reusable-ai-agents.md` — saved agents, linked from flow steps and also run + on their own (page, API, Slack, apps) as a one-step flow, so flow and chat-flow behaviour + reaches them too; memory, approvals and questions - **Auth surface**: `docs/auth-surface.md` — credential precedence, session/cache invalidation scope, which token labels email their owner at expiry, how OAuth login matches `login_type`, and that every superadmin route refuses `$WM_TOKEN`. Read before designing anything that creates diff --git a/CONTEXT.md b/CONTEXT.md index 054960607c..ed3ebd9010 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -39,9 +39,15 @@ _Avoid_: JS field, code input ### Flow chat +**Agent**: +A saved AI agent: an `ai_agent` resource holding a model, prompt and tools. Flow steps link to +it, and it also runs on its own (its page, the API, Slack, apps) as a one-step flow, so it has +conversations of its own. See `docs/reusable-ai-agents.md`. +_Avoid_: bot, assistant + **Conversation**: -One thread of messages against one chat-enabled flow, with its own agent memory. A flow has -many; the chat shows one at a time. +One thread of messages against one chat-enabled flow or one agent, with its own agent memory. +Each has many; the chat shows one at a time. _Avoid_: thread, session (that names an AI session, a different thing), chat (that names the surface) **Turn**: diff --git a/docs/reusable-ai-agents.md b/docs/reusable-ai-agents.md index 3d3163470f..83b8b48800 100644 --- a/docs/reusable-ai-agents.md +++ b/docs/reusable-ai-agents.md @@ -8,6 +8,23 @@ agent, and edits to the agent propagate to every linked step. The `ai_agent` resource type is defined in the hub (windmill-integrations) and synced into every workspace via the standard cached-resource-type sync, like other built-in types. +## Running an agent on its own + +A saved agent also runs without any flow of the author's: from its deployed page, through +`POST /w/{workspace}/jobs/run/agent/{path}` (scope `jobs:run:agents:`), from a Slack channel +it is shared in, from a full-code app, and from the AI session's run tools. All of them go through +`windmill-api/src/agent_runs.rs`, which reads the agent and runs it as a **one-step flow** +(`agent_step_flow`, step id `__wm_agent_root`). Every run drops the agent's saved `memory_id` and +`previous_messages` step inputs: the message, attachments and any `previous_messages` come from +the run's input. A run with a `memory_id` is a turn of a conversation, filed under `.chat` +and run with chat input enabled. The agent editor's chat is different: it previews the draft as a +flow preview of the same one step (`agentChatFlow`), not through `agent_runs.rs`. + +Since the run is a flow, everything written for flow runs and chat flows applies to it as well: +conversations, the running-turn check, approvals and questions. A change to one of those paths +must keep working for this one-step shape, and can be tested from the agent's deployed page as +well as from a flow. + ## Rigid linking `FlowModuleValue::AIAgent` has an optional `agent` field holding the resource path, plus a From 38e7463dd4e93c36f28fefb102bc5d0d3060cdf3 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 10 Nov 2026 21:24:16 +0000 Subject: [PATCH 03/22] fix: build Azure block upload URLs from the account endpoint (#12333) * [ee] fix: build Azure block upload URLs from the endpoint the object store client uses Bumps ee-repo-ref to the companion windmill-ee-private commit. Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to c75b9d7ca70cc3a33c7619aa969b02297e732ecb This commit updates the EE repository reference after PR #974 was merged in windmill-ee-private. Previous ee-repo-ref: e0be4037aa3a588fcf19bd41faa9485c35b35a23 New ee-repo-ref: c75b9d7ca70cc3a33c7619aa969b02297e732ecb Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 7fe20e438b..4c2abd924f 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -d7d509d0955c52f83afd0bf8b61a0e811162c16f +c75b9d7ca70cc3a33c7619aa969b02297e732ecb From 841cc3ecbad7e599086bdb2902fa8c2d4c48e7a6 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 10 Nov 2026 21:50:01 +0000 Subject: [PATCH 04/22] fix: stream logs of a selected step nested in a subflow or loop (#12334) --- .../components/FlowStatusViewerInner.svelte | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 308092c1c4..1b1334bbcc 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -108,6 +108,10 @@ innerModule?: FlowModuleValue | undefined render?: boolean selectedNode?: string | undefined + /** Job of the node selected in the root viewer's graph. Nested viewers have no + * selectedNode of their own, so this is how a step inside a subflow, loop or retry + * knows it is selected and must stream its logs. */ + selectedJobId?: string | undefined globalModuleStates: Record[] globalDurationStatuses?: Record[] isSelectedBranch?: boolean @@ -169,6 +173,7 @@ innerModule = undefined, render = true, selectedNode = $bindable(undefined), + selectedJobId = undefined, globalModuleStates, globalDurationStatuses = [], updateRecursiveRefreshFn = undefined, @@ -1407,6 +1412,11 @@ let noLogs = $derived(graphTabOpen && !isNodeSelected) + // The root viewer's module states hold every nested step, prefixed for subflows. + let effectiveSelectedJobId = $derived( + selectedJobId ?? localModuleStates?.[selectedNode ?? '']?.job_id + ) + /** * Returns a string like "forloopmodid1-{iter1}-forloopmodid2-{iter2}-forloopmodid3-{iter3}-" * that can be used to prefix tool call store keys for nested tool calls. @@ -1668,6 +1678,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={forloop_selected == loopJobId} toolCallStore={{ getStoredToolCallJob: (storeKey: string) => @@ -1765,6 +1776,7 @@ jobId={failedRetry} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={retry_selected == failedRetry} /> @@ -1801,6 +1813,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={false} /> {:else if mod.flow_jobs?.length == 0 && mod.job == '00000000-0000-0000-0000-000000000000'} @@ -1842,7 +1855,8 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} - isNodeSelected={localModuleStates?.[selectedNode ?? '']?.job_id == mod.job} + selectedJobId={effectiveSelectedJobId} + isNodeSelected={effectiveSelectedJobId == mod.job} {toolCallStore} showLogsWithResult={['script', 'rawscript'].includes( job.raw_flow?.modules[i]?.value?.type ?? '' @@ -2085,7 +2099,11 @@ wrapperClass={closableDetails ? 'grow min-w-0' : 'shrink-0'} > {#if !hideTimeline} - + {/if} Date: Tue, 10 Nov 2026 22:50:57 +0100 Subject: [PATCH 05/22] fix: send AI session requests with their own workspace's AI config (#12330) --- frontend/src/lib/aiStore.test.ts | 45 ++++- frontend/src/lib/aiStore.ts | 156 ++++++++++++++---- frontend/src/lib/components/Editor.svelte | 16 +- .../copilot/autocomplete/Autocompletor.ts | 39 +++-- .../copilot/autocomplete/request.ts | 10 +- .../copilot/chat/AIChatInput.svelte | 7 +- .../copilot/chat/AIChatManager.svelte.ts | 117 +++++++++---- .../copilot/chat/AIChatManager.test.ts | 5 + .../copilot/chat/AIChatModelSettings.svelte | 2 + .../chat/AssistantInstructionsSection.svelte | 2 + .../lib/components/copilot/chat/anthropic.ts | 5 +- .../lib/components/copilot/chat/chatLoop.ts | 16 +- .../components/copilot/chat/chatViewHost.ts | 4 + .../components/copilot/chat/global/core.ts | 7 +- .../copilot/chat/openai-responses.ts | 13 +- .../components/copilot/chat/script/core.ts | 19 ++- .../copilot/chat/sessionAiConfig.test.ts | 145 ++++++++++++++++ frontend/src/lib/components/copilot/lib.ts | 112 +++++++++---- .../components/copilot/loadCopilot.test.ts | 33 +++- .../src/lib/components/copilot/loadCopilot.ts | 14 +- .../deploymentRequest/AiReview.svelte | 26 ++- .../components/deploymentRequest/aiReview.ts | 6 +- .../InstanceAISettings.svelte | 3 +- .../sessions/WorkspaceDiffDrawer.svelte | 10 +- .../sessions/sessionRuntime.svelte.ts | 65 +------- .../lib/components/sessions/sessionTitle.ts | 65 ++++++++ .../workspaceSettings/AISettings.svelte | 3 +- 27 files changed, 711 insertions(+), 234 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts create mode 100644 frontend/src/lib/components/sessions/sessionTitle.ts diff --git a/frontend/src/lib/aiStore.test.ts b/frontend/src/lib/aiStore.test.ts index be8980e93a..22c841c91a 100644 --- a/frontend/src/lib/aiStore.test.ts +++ b/frontend/src/lib/aiStore.test.ts @@ -1,16 +1,53 @@ import { describe, expect, it, vi } from 'vitest' import { get } from 'svelte/store' -// aiStore pulls in the (heavy) copilot lib for workspaceAIClients and the gen -// client for WorkspaceService; neither is exercised by setCopilotInfo. +let requests: { workspace: string; resolve: (config: any) => void }[] = [] + +// aiStore pulls in the (heavy) copilot lib for workspaceAIClients; setCopilotInfo does not +// exercise it. vi.mock('./components/copilot/lib', () => ({ workspaceAIClients: { init: () => {} } })) vi.mock('./gen', () => ({ - WorkspaceService: { getCopilotInfo: async () => ({}) } + WorkspaceService: { + getCopilotInfo: ({ workspace }: { workspace: string }) => + new Promise((resolve) => requests.push({ workspace, resolve })) + } })) -import { isWebSearchEnabledForProvider, setCopilotInfo, copilotInfo } from './aiStore' +import { + isWebSearchEnabledForProvider, + setCopilotInfo, + copilotInfo, + getWorkspaceCopilotInfo, + invalidateWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo +} from './aiStore' + +const withModel = (model: string) => ({ + providers: { anthropic: { resource_path: 'u/admin/anthropic', models: [model] } } +}) +const modelOf = (info: { aiModels: { model: string }[] } | undefined) => info?.aiModels[0]?.model + +// A config saved, or one every workspace inherits, while a session's load is in flight: the load +// read the config from before the save and must not keep it. +describe.each([ + ['its workspace', () => invalidateWorkspaceCopilotInfo('ws')], + ['every workspace', () => invalidateWorkspaceCopilotInfo()] +])('loadWorkspaceCopilotInfo invalidated for %s mid-fetch', (_, invalidate) => { + it('refetches instead of keeping the outdated config', async () => { + requests = [] + invalidateWorkspaceCopilotInfo() + const load = loadWorkspaceCopilotInfo('ws') + invalidate() + requests[0].resolve(withModel('before-save')) + await vi.waitFor(() => expect(requests).toHaveLength(2)) + requests[1].resolve(withModel('saved')) + + expect(modelOf(await load)).toBe('saved') + expect(modelOf(getWorkspaceCopilotInfo('ws'))).toBe('saved') + }) +}) describe('setCopilotInfo legacy /thinking migration', () => { it('strips the /thinking suffix from configured model slots', () => { diff --git a/frontend/src/lib/aiStore.ts b/frontend/src/lib/aiStore.ts index ac9320f8a3..246fd0a1f0 100644 --- a/frontend/src/lib/aiStore.ts +++ b/frontend/src/lib/aiStore.ts @@ -3,13 +3,15 @@ // import aiStore back, and such a cycle crashes the app once the bundler splits it across // chunks (docs/frontend-import-cycles.md; the build fails on the chunk cycle, not on this). import { writable, get } from 'svelte/store' +import { SvelteMap } from 'svelte/reactivity' import { type AIProviderModel, type AIProvider, type AIConfig, type AIWebSearchConfig, type FreeTierInfo, - type ModelPriceOverride + type ModelPriceOverride, + WorkspaceService } from './gen' import { aiUserDisabled, @@ -40,7 +42,7 @@ export const copilotSessionModel = writable( : undefined ) -export const copilotInfo = writable<{ +export type CopilotInfo = { enabled: boolean // The workspace hid the assistant (`ai_config.copilot_disabled`). `enabled` is then false // whatever the providers say, and the AI entry points that nudge "configure AI" when @@ -64,7 +66,9 @@ export const copilotInfo = writable<{ // Windmill's free tier. `exhausted` means the grant is spent: there is no model, but // that is a different state from "never configured" and the UI must say so. freeTier?: FreeTierInfo -}>({ +} + +export const copilotInfo = writable({ enabled: false, workspaceDisabled: false, codeCompletionModel: undefined, @@ -78,13 +82,27 @@ export const copilotInfo = writable<{ webSearchEnabledProviders: {} }) +// Each workspace's AI config, read by AI sessions, which send with their own workspace's config +// rather than the tab's. Only `loadWorkspaceCopilotInfo` fills it: a save invalidates instead. +const workspaceCopilotInfos = new SvelteMap() +const workspaceLoads = new Map>() +// Bumped by invalidation: a load started before it refetches instead of keeping its answer. +let allWorkspacesVersion = 0 +const workspaceVersions = new Map() +const versionOf = (workspace: string) => + `${allWorkspacesVersion}:${workspaceVersions.get(workspace) ?? 0}` + // Apply the per-user opt-out live: toggling it flips `enabled` without re-fetching. // Only enable when providers exist (aiModels is populated whenever the config has any). aiUserDisabled.subscribe((disabled) => { - copilotInfo.update((info) => ({ + const withOptOut = (info: CopilotInfo): CopilotInfo => ({ ...info, enabled: info.aiModels.length > 0 && !disabled && !info.workspaceDisabled - })) + }) + copilotInfo.update(withOptOut) + for (const [workspace, info] of workspaceCopilotInfos) { + workspaceCopilotInfos.set(workspace, withOptOut(info)) + } }) /** Strip the deprecated /thinking suffix from a configured model slot, if present. */ @@ -110,7 +128,7 @@ function dedupeModels(models: AIProviderModel[]): AIProviderModel[] { // workspace's provider/model while the scoped load is still in flight. export const copilotWorkspace = writable(undefined) -export function setCopilotInfo(aiConfig: AIConfig) { +function buildCopilotInfo(aiConfig: AIConfig, userDisabled: boolean): CopilotInfo { if (Object.keys(aiConfig.providers ?? {}).length > 0) { const aiModels = dedupeModels( Object.entries(aiConfig.providers ?? {}).flatMap(([provider, providerConfig]) => @@ -128,20 +146,10 @@ export function setCopilotInfo(aiConfig: AIConfig) { ]) ) as Partial> - copilotSessionModel.update((model) => { - if ( - model && - !aiModels.some((m) => m.model === model.model && m.provider === model.provider) - ) { - return undefined - } - return model - }) - const workspaceDisabled = aiConfig.copilot_disabled === true - copilotInfo.set({ + return { // Providers are configured; only the workspace or per-user opt-outs can gate it off. - enabled: !workspaceDisabled && !get(aiUserDisabled), + enabled: !workspaceDisabled && !userDisabled, workspaceDisabled, // Strip the deprecated /thinking suffix from the configured model slots too, // otherwise a workspace whose default still carries it sends an invalid model id. @@ -156,11 +164,9 @@ export function setCopilotInfo(aiConfig: AIConfig) { webSearchBackend: aiConfig.web_search?.provider, modelPricing: aiConfig.model_pricing ?? {}, freeTier: aiConfig.free_tier - }) + } } else { - copilotSessionModel.set(undefined) - - copilotInfo.set({ + return { enabled: false, workspaceDisabled: aiConfig.copilot_disabled === true, codeCompletionModel: undefined, @@ -175,20 +181,26 @@ export function setCopilotInfo(aiConfig: AIConfig) { // An exhausted free grant lands here — no providers, but the reason AI is off // is "you used it up", not "you never set it up". freeTier: aiConfig.free_tier - }) + } } } -export function isWebSearchEnabledForProvider(provider: AIProvider | undefined): boolean { +export function isWebSearchEnabledForProvider( + provider: AIProvider | undefined, + info: CopilotInfo = get(copilotInfo) +): boolean { if (!provider) { return false } - return get(copilotInfo).webSearchEnabledProviders?.[provider] ?? true + return info.webSearchEnabledProviders?.[provider] ?? true } export function getCurrentModel(): ReasoningProviderModel { - const model = - get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return resolveModelFor(get(copilotInfo)) +} + +export function resolveModelFor(info: CopilotInfo): ReasoningProviderModel { + const model = tryResolveModelFor(info) if (!model) { throw new Error('No model selected') } @@ -196,7 +208,10 @@ export function getCurrentModel(): ReasoningProviderModel { } export function getMetadataModel(): AIProviderModel { - const info = get(copilotInfo) + return resolveMetadataModelFor(get(copilotInfo)) +} + +export function resolveMetadataModelFor(info: CopilotInfo): AIProviderModel { const model = info.metadataModel ?? info.defaultModel ?? info.aiModels[0] if (!model) { throw new Error('No model selected') @@ -205,9 +220,85 @@ export function getMetadataModel(): AIProviderModel { } export function tryGetCurrentModel(): ReasoningProviderModel | undefined { - return get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return tryResolveModelFor(get(copilotInfo)) } +/** `workspace`'s AI config if loaded; otherwise starts loading it and returns undefined. */ +export function getWorkspaceCopilotInfo(workspace: string): CopilotInfo | undefined { + const info = workspaceCopilotInfos.get(workspace) + if (!info) { + loadWorkspaceCopilotInfo(workspace).catch((e) => + console.error(`Failed to load the AI config of workspace ${workspace}`, e) + ) + } + return info +} + +/** `workspace`'s AI config for a request made on its behalf, without touching the tab's. + * Fetched once and kept until invalidated. `fresh` refetches a config that may have changed + * elsewhere: unlike after a save, the one held stays readable until the new one lands, so what + * shows it does not blank meanwhile, and a load already in flight is as fresh and is shared. */ +export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Promise { + const known = workspaceCopilotInfos.get(workspace) + if (known && !fresh) return Promise.resolve(known) + let load = workspaceLoads.get(workspace) + if (!load) { + const version = versionOf(workspace) + load = WorkspaceService.getCopilotInfo({ workspace }) + // Settled before the retry below, which would otherwise be handed this same load. + .finally(() => workspaceLoads.delete(workspace)) + .then((config) => { + if (version !== versionOf(workspace)) return loadWorkspaceCopilotInfo(workspace) + const info = buildCopilotInfo(config, get(aiUserDisabled)) + workspaceCopilotInfos.set(workspace, info) + return info + }) + workspaceLoads.set(workspace, load) + } + return load +} + +/** After a save of `workspace`'s AI config, or with none of a config every workspace inherits + * (the instance's): the next request refetches. */ +export function invalidateWorkspaceCopilotInfo(workspace?: string) { + if (workspace) { + workspaceVersions.set(workspace, (workspaceVersions.get(workspace) ?? 0) + 1) + workspaceCopilotInfos.delete(workspace) + } else { + allWorkspacesVersion++ + workspaceCopilotInfos.clear() + } +} + +export function setCopilotInfo(aiConfig: AIConfig) { + applyCopilotInfo(buildCopilotInfo(aiConfig, get(aiUserDisabled))) +} + +export function applyCopilotInfo(info: CopilotInfo) { + copilotSessionModel.update((model) => (model && isOffered(info, model) ? model : undefined)) + copilotInfo.set(info) +} + +function isOffered(info: CopilotInfo, model: AIProviderModel): boolean { + return info.aiModels.some((m) => m.model === model.model && m.provider === model.provider) +} + +/** The model a request for `info`'s workspace sends: the shared pick when that workspace offers + * it, else its default, else its first model. Never one the workspace does not offer. */ +export function tryResolveModelFor(info: CopilotInfo): ReasoningProviderModel | undefined { + const picked = get(copilotSessionModel) + if (picked && isOffered(info, picked)) return picked + return info.defaultModel ?? info.aiModels[0] +} + +/** A workspace a request is made for and that workspace's AI config, kept together so a request + * never pairs one workspace's credentials with another's settings. */ +export type AiTarget = { workspace: string; info: CopilotInfo } + +/** What an AI session sends with, for code that otherwise reads the tab's model and config. + * Both are undefined while the session's config is loading. */ +export type SessionAi = { model: ReasoningProviderModel | undefined; info: CopilotInfo | undefined } + export function getUserCustomPrompts(): Record { const stored = getLocalSetting(USER_CUSTOM_PROMPTS_KEY) if (stored) { @@ -242,8 +333,11 @@ export function getCombinedCustomPrompt(mode: string): string | undefined { // Like getCombinedCustomPrompt but keeps the workspace and user slices separate so the // Global system prompt can label them distinctly — only the user slice is editable by the // update_user_instructions tool. -export function getCustomPromptParts(mode: string): { workspace?: string; user?: string } { - const workspace = get(copilotInfo).customPrompts?.[mode]?.trim() || undefined +export function getCustomPromptParts( + mode: string, + customPrompts: Record | undefined = get(copilotInfo).customPrompts +): { workspace?: string; user?: string } { + const workspace = customPrompts?.[mode]?.trim() || undefined const user = getUserCustomPrompts()[mode]?.trim() || undefined return { workspace, user } } diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index b103e7ddf8..7e9b192578 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -276,6 +276,10 @@ // rather than via getAiChatManager(), which collapses "no session" into the // singleton — the distinction is what tells ⌘L whether a pane exists to open. const sessionScopedChatManager = getContext('aiChatManager') + // Autocomplete in a session's editor follows the session's workspace, not the tab's. + const completionInfo = $derived( + sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo + ) // let graphqlService: MonacoGraphQLAPI | undefined = undefined let fetchedDbSchema: DBSchema | undefined = $state(undefined) @@ -1008,7 +1012,11 @@ if (autocompletor) { autocompletor.dispose() } - autocompletor = new Autocompletor(editor, scriptLang, { workflowAsCode }) + const session = sessionScopedChatManager + autocompletor = new Autocompletor(editor, scriptLang, { + workflowAsCode, + sessionTarget: session ? () => session.loadedSessionAiTarget : undefined + }) } const outputChannel = { @@ -2082,9 +2090,9 @@ }) $effect(() => { const currentWorkflowAsCode = workflowAsCode - $copilotInfo.enabled && + completionInfo?.enabled && $codeCompletionSessionEnabled && - Autocompletor.isProviderModelSupported($copilotInfo.codeCompletionModel) && + Autocompletor.isProviderModelSupported(completionInfo.codeCompletionModel) && initialized && editor && scriptLang && @@ -2094,7 +2102,7 @@ $copilotInfo.enabled && initialized && editor && untrack(() => editor && addChatHandler(editor)) }) $effect(() => { - ;(!$codeCompletionSessionEnabled || !$copilotInfo.enabled) && autocompletor?.dispose() + ;(!$codeCompletionSessionEnabled || !completionInfo?.enabled) && autocompletor?.dispose() }) $effect(() => { if (yContent && awareness && model && editor) { diff --git a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts index 5c9519ba1e..ce1f9bc3f2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts +++ b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts @@ -9,7 +9,7 @@ import { setGlobalCSS } from '../shared' import { supportsAutocomplete } from '../utils' import { get } from 'svelte/store' import type { MonacoLanguageClient } from 'monaco-languageclient' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' import { getTypeScriptWorker } from '@codingame/monaco-vscode-standalone-typescript-language-features' // max ratio of completions to context window @@ -72,15 +72,21 @@ export class Autocompletor { #completionDisposable: IDisposable #cursorDisposable: IDisposable #lastCompletions: string[] = [] - #contextWindow: number = 0 + #sessionTarget: (() => AiTarget | undefined) | undefined #shouldShowDeletionCue = false #languageClient: MonacoLanguageClient | undefined = undefined constructor( editor: meditor.IStandaloneCodeEditor, scriptLang: ScriptLang | 'bunnative' | 'jsx' | 'tsx' | 'json', - options: { workflowAsCode?: boolean } = {} + options: { + workflowAsCode?: boolean + /** Set in an AI session's editor: completions go to the session's workspace with its + * AI config. Undefined while that config is loading. */ + sessionTarget?: () => AiTarget | undefined + } = {} ) { + this.#sessionTarget = options.sessionTarget setGlobalCSS( 'ai-chat-autocomplete', ` @@ -94,15 +100,6 @@ export class Autocompletor { const deletionsCues = editor.createDecorationsCollection() - const { codeCompletionModel: completionModel, contextWindowPerModel } = get(copilotInfo) - this.#contextWindow = completionModel - ? getEffectiveModelContextWindow( - completionModel.provider, - completionModel.model, - contextWindowPerModel - ) - : ASSUMED_CONTEXT_WINDOW - this.#completionDisposable = languages.registerInlineCompletionsProvider( { pattern: '**' }, { @@ -520,9 +517,22 @@ export class Autocompletor { const markers = meditor.getModelMarkers({ resource: model.uri }) const markersAtCursor = this.#markersAtCursor(position, markers) + const target = this.#sessionTarget?.() + // A session's editor completes only once its own workspace's config is known. + if (this.#sessionTarget && !target) { + return + } + const { codeCompletionModel, contextWindowPerModel } = target?.info ?? get(copilotInfo) + const contextWindow = codeCompletionModel + ? getEffectiveModelContextWindow( + codeCompletionModel.provider, + codeCompletionModel.model, + contextWindowPerModel + ) + : ASSUMED_CONTEXT_WINDOW const librariesCompletions: string = completions .join('\n') - .slice(0, Math.floor(this.#contextWindow * COMPLETIONS_MAX_RATIO)) + .slice(0, Math.floor(contextWindow * COMPLETIONS_MAX_RATIO)) const completion = await autocompleteRequest( { @@ -533,7 +543,8 @@ export class Autocompletor { libraries: librariesCompletions, workflowAsCode: this.#workflowAsCode }, - this.#abortController + this.#abortController, + target ) if (!completion) { diff --git a/frontend/src/lib/components/copilot/autocomplete/request.ts b/frontend/src/lib/components/copilot/autocomplete/request.ts index cc3987ebe5..651b212ec2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/request.ts +++ b/frontend/src/lib/components/copilot/autocomplete/request.ts @@ -4,7 +4,7 @@ import { getLangContext } from '../chat/script/core' import { type ScriptLang } from '$lib/gen/types.gen' import type { editor } from 'monaco-editor' import { getCommentSymbol } from '../utils' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' function comment(commentSymbol: string, text: string) { return text @@ -22,9 +22,10 @@ export async function autocompleteRequest( libraries: string workflowAsCode?: boolean }, - abortController: AbortController + abortController: AbortController, + target?: AiTarget ) { - const providerModel = get(copilotInfo).codeCompletionModel + const providerModel = (target?.info ?? get(copilotInfo)).codeCompletionModel if (!providerModel) { throw new Error('No code completion model selected') @@ -56,7 +57,8 @@ export async function autocompleteRequest( context.prefix, context.suffix, providerModel, - abortController + abortController, + target?.workspace ) return completion diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index f3b49d680b..f3dd73bc46 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -44,7 +44,6 @@ type AttachedImage } from './imageUtils' import { modelSupportsVision } from '../modelConfig' - import { tryGetCurrentModel } from '$lib/aiStore' import { createLongHash } from '$lib/editorLangUtils' import { fileToAttachedTextFile, @@ -334,11 +333,9 @@ if (imageFiles.length === 0) return // The vision check is about the model this composer's own turn will hit, so it // only applies to a host that picks that model. Elsewhere the model is chosen - // in the flow and tryGetCurrentModel would answer for the wrong one. + // in the flow and the host's model would answer for the wrong one. if (chatHost.supportsModelSettings) { - // tryGetCurrentModel returns undefined instead of throwing: this runs from a - // drop/paste handler that can't surface a rejection. - const model = tryGetCurrentModel() + const model = chatHost.currentModel // Only known text-only models fail this, so attaching would certainly 400 the // next turn — refuse rather than warn and send it anyway. if (model && !modelSupportsVision(model.provider, model.model)) { diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 6c8142fa72..9910bb1e87 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -98,7 +98,17 @@ import { fromStore, get } from 'svelte/store' import type { ProviderToolSummary } from './agentContext' import { BROWSER } from 'esm-env' import { roleCapabilities, workspaceStore, type DBSchemas } from '$lib/stores' -import { copilotInfo, copilotSessionModel } from '$lib/aiStore' +import { + copilotInfo, + copilotSessionModel, + getWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo, + resolveModelFor, + tryResolveModelFor, + type AiTarget, + type CopilotInfo +} from '$lib/aiStore' +import type { ReasoningProviderModel } from '../reasoningRegistry' import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot' import { askTools, prepareAskSystemMessage, prepareAskUserMessage } from './ask/core' import { readDocsPageTool, searchDocsTool } from './docs/core' @@ -707,8 +717,11 @@ export class AIChatManager implements ChatViewHost { if (this.reasoningSummaryUnavailableFor.length === 0) { return undefined } - const provider = getCurrentModel().provider - if (!this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider))) { + const provider = this.currentModel?.provider + if ( + !provider || + !this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider)) + ) { return undefined } return `Thinking (hidden, ${providerDisplayName(provider)} org not verified)` @@ -860,16 +873,12 @@ export class AIChatManager implements ChatViewHost { #copilotInfo = fromStore(copilotInfo) #sessionModel = fromStore(copilotSessionModel) /** Capabilities the provider runs on its own servers, attached by the adapter at send - * time. Never part of `tools`: the request path would try to dispatch them. The two - * `void` reads only subscribe: the model helpers read through `get()`, which tracks - * nothing, so a change of model or of the workspace's AI config would otherwise not - * re-derive. A workspace switch re-derives through the AI config it loads. */ + * time. Never part of `tools`: the request path would try to dispatch them. */ get providerTools(): ProviderToolSummary[] { - void this.#copilotInfo.current - void this.#sessionModel.current - const model = tryGetCurrentModel() - if (!model || (model.provider === 'openai' && this.skipResponsesApi)) return [] - const enabled = isWebSearchEnabledForProvider(model.provider) + const model = this.currentModel + const info = this.aiInfo + if (!model || !info || (model.provider === 'openai' && this.skipResponsesApi)) return [] + const enabled = isWebSearchEnabledForProvider(model.provider, info) return sendsWebSearch(this.operatingWorkspace ?? '', model, enabled) ? [ { @@ -1061,6 +1070,37 @@ export class AIChatManager implements ChatViewHost { return this.workspaceResolver?.() ?? get(workspaceStore) } + /** The AI config this chat sends with. A session's is its own workspace's, never the tab's, + * which belongs to whatever workspace is on screen; other chats use the tab's. Undefined while + * a session's is still loading, and reading it starts the load. */ + get aiInfo(): CopilotInfo | undefined { + if (!this.isSessionChat) return this.#copilotInfo.current + const workspace = this.operatingWorkspace + return workspace ? getWorkspaceCopilotInfo(workspace) : undefined + } + + /** The session's workspace and loaded config, for code that cannot wait for the load. */ + get loadedSessionAiTarget(): AiTarget | undefined { + const info = this.isSessionChat ? this.aiInfo : undefined + const workspace = this.operatingWorkspace + return info && workspace ? { workspace, info } : undefined + } + + get currentModel(): ReasoningProviderModel | undefined { + // Subscribes only: the model helpers read through `get()`, which tracks nothing. + void this.#sessionModel.current + const info = this.aiInfo + return info && tryResolveModelFor(info) + } + + /** Resolved at each request, after any fork commit. Undefined for other chats, whose requests + * use the tab's. */ + sessionAiTarget = async (): Promise => { + if (!this.isSessionChat) return undefined + const workspace = this.operatingWorkspace ?? '' + return { workspace, info: await loadWorkspaceCopilotInfo(workspace) } + } + // Fired whenever the active chat id changes away from the one the consumer // knows (a "/clear" rotation or a history switch). Session runtimes wire this // to keep the session record's chatId aligned — the compare-page handoff @@ -1792,6 +1832,7 @@ export class AIChatManager implements ChatViewHost { ): Promise<'ok' | 'empty' | 'aborted' | 'error'> => { this.compacting = true try { + const target = await this.sessionAiTarget() // Cap the summarizer's output at the budget already reserved for the // summary: without a cap the model's default max_tokens applies. const raw = await getStreamedCompletionText( @@ -1802,7 +1843,7 @@ export class AIChatManager implements ChatViewHost { { role: 'user', content: getCompactionSummaryPrompt() } ], abortController, - { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS } + { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS, ...target } ) const formatted = formatCompactSummary(raw) if (!formatted) { @@ -1991,12 +2032,9 @@ export class AIChatManager implements ChatViewHost { model: ChatLoopConfig['modelProvider'] | undefined, inFlightTokens = 0 ): Promise => { + const info = (await this.sessionAiTarget())?.info ?? get(copilotInfo) const contextWindow = model - ? getEffectiveModelContextWindow( - model.provider, - model.model, - get(copilotInfo).contextWindowPerModel - ) + ? getEffectiveModelContextWindow(model.provider, model.model, info.contextWindowPerModel) : undefined if (contextWindow === undefined || projectedTokens < contextWindow * COMPACTION_TRIGGER_RATIO) { return false @@ -2893,6 +2931,7 @@ export class AIChatManager implements ChatViewHost { ? { sessionId: this.sessionId, operatingWorkspace: this.operatingWorkspace, + sessionAi: () => ({ model: this.currentModel, info: this.aiInfo }), artifacts: this.artifacts, access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), @@ -2923,7 +2962,10 @@ export class AIChatManager implements ChatViewHost { ensurePipeline: this.#ensurePipeline } : baseHelpers - this.systemMessage = assembleGlobalSystemMessage(getCustomPromptParts(AIMode.GLOBAL), opts) + this.systemMessage = assembleGlobalSystemMessage( + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), + opts + ) this.syncArtifactsSession() } @@ -3103,7 +3145,7 @@ export class AIChatManager implements ChatViewHost { return } this.systemMessage = assembleGlobalSystemMessage( - getCustomPromptParts(AIMode.GLOBAL), + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), this.globalAssemblyOpts() ) } @@ -3435,7 +3477,8 @@ export class AIChatManager implements ChatViewHost { } private notifyReasoningSummaryUnavailable = () => { - const provider = getCurrentModel().provider + const provider = this.currentModel?.provider + if (!provider) return const key = this.reasoningSummaryKey(provider) if (!this.reasoningSummaryUnavailableFor.includes(key)) { this.reasoningSummaryUnavailableFor = [...this.reasoningSummaryUnavailableFor, key] @@ -3482,6 +3525,8 @@ export class AIChatManager implements ChatViewHost { // while a response streams would bill it to the workspace the user landed // on rather than the one whose credentials and proxy served it. const usageWorkspace = this.operatingWorkspace + const target = await this.sessionAiTarget() + const info = target?.info const result = await runChatLoop({ messages, addedMessages, @@ -3502,7 +3547,7 @@ export class AIChatManager implements ChatViewHost { get tools() { return withWebSearchFallback( self.tools, - !!get(copilotInfo).webSearchBackend, + !!(info ?? get(copilotInfo)).webSearchBackend, self.providerTools.length > 0 ) }, @@ -3512,10 +3557,10 @@ export class AIChatManager implements ChatViewHost { abortController, callbacks, get modelProvider() { - return getCurrentModel() + return info ? resolveModelFor(info) : getCurrentModel() }, get webSearch() { - return isWebSearchEnabledForProvider(getCurrentModel().provider) + return isWebSearchEnabledForProvider(this.modelProvider.provider, info) }, // Build the proxy clients against the operating workspace, not the global // singleton: a session deliberately leaves workspaceStore untouched, so the @@ -3523,13 +3568,14 @@ export class AIChatManager implements ChatViewHost { // request through the navigation workspace's /ai/proxy instead of the // session's — sending it to the wrong workspace's AI credentials. get clients() { - const ws = self.operatingWorkspace ?? '' + const ws = target?.workspace ?? self.operatingWorkspace ?? '' return { openai: workspaceAIClients.createOpenaiClient(ws), anthropic: workspaceAIClients.createAnthropicClient(ws) } }, - workspace: this.operatingWorkspace ?? '', + workspace: target?.workspace ?? this.operatingWorkspace ?? '', + info, skipResponsesApi: this.skipResponsesApi, onSkipResponsesApi: () => { this.skipResponsesApi = true @@ -3973,7 +4019,7 @@ export class AIChatManager implements ChatViewHost { // only edit/retry of a pre-id transcript can arrive without one, and the // hash is deterministic, so hydration reproduces the original id. const files = withAttachedTextFileIds(options.files ?? []) - const sendModel = tryGetCurrentModel() + const sendModel = this.currentModel const modelIsBlind = !!sendModel && !modelSupportsVision(sendModel.provider, sendModel.model) if (requestedImages.length > 0 && modelIsBlind) { // An image-only message has nothing left once the images are dropped — @@ -4111,8 +4157,13 @@ export class AIChatManager implements ChatViewHost { this.refreshSessionAccess(this.operatingWorkspace ?? ''), resolveResourceTypeSync(this.operatingWorkspace ?? '', this.messages).then((sync) => { this.resourceTypeSync = sync - }) + }), + // Its workspace prompt goes into the system prompt rebuilt below. + this.sessionAiTarget().catch(() => {}) ]) + if (this.isSessionChat) { + this.rebuildGlobalSystemMessage() + } } // Stop/Escape during the beforeSend pre-flight aborted this send before any // request went out. Mirror the main "cancelled before usable output" recovery: @@ -4268,7 +4319,7 @@ export class AIChatManager implements ChatViewHost { // loading + abortController were set optimistically before beforeSend, above. this.#automaticScroll = true - const model = tryGetCurrentModel() + const model = this.currentModel if (model) { const chatId = this.historyManager.getCurrentChatId() logFeatureUsage('ai_chat', 'message', { @@ -4792,15 +4843,11 @@ export class AIChatManager implements ChatViewHost { if ( requestCarriedImages && messagesHaveImageParts(this.messages) && - isImageRejection(err, [ - sendModel?.model, - tryGetCurrentModel()?.model, - failingModel?.model - ]) + isImageRejection(err, [sendModel?.model, this.currentModel?.model, failingModel?.model]) ) { this.messages = stripImagePartsFromMessages(this.messages) sendUserToast( - `${tryGetCurrentModel()?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, + `${this.currentModel?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, true ) } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 9f6179a538..ff64eb07fc 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -141,6 +141,11 @@ vi.mock('$lib/aiStore', () => ({ copilotSessionModel: writable(undefined), getCurrentModel: mocks.getCurrentModel, tryGetCurrentModel: mocks.tryGetCurrentModel, + // A session reads its own workspace's config; here every workspace has the same one. + getWorkspaceCopilotInfo: () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + loadWorkspaceCopilotInfo: async () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + resolveModelFor: mocks.getCurrentModel, + tryResolveModelFor: mocks.tryGetCurrentModel, getCombinedCustomPrompt: () => '', getCustomPromptParts: () => ({}), getUserCustomPrompts: () => ({}), diff --git a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte index 5f4b4a5040..fb65460f2c 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte @@ -17,6 +17,7 @@ copilotInfo, copilotSessionModel, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -192,6 +193,7 @@ requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(workspace) initialPrompt = value customPrompts = { [activeMode]: value } sendUserToast('Workspace AI prompt saved') diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 547940bde9..ebea3dbb6a 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -23,6 +23,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio import { copilotInfo, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -596,6 +597,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(target) workspaceSaved = value workspaceDraft = value sendUserToast('Workspace instructions were saved') diff --git a/frontend/src/lib/components/copilot/chat/anthropic.ts b/frontend/src/lib/components/copilot/chat/anthropic.ts index ce11b0dade..937fe47ed4 100644 --- a/frontend/src/lib/components/copilot/chat/anthropic.ts +++ b/frontend/src/lib/components/copilot/chat/anthropic.ts @@ -14,6 +14,7 @@ import type { } from '@anthropic-ai/sdk/resources' import type { MessageStream } from '@anthropic-ai/sdk/lib/MessageStream' import type { AIProviderModel } from '$lib/gen' +import type { CopilotInfo } from '$lib/aiStore' import { getProviderAndCompletionConfig, workspaceAIClients } from '../lib' import { applyReasoningToConfig } from '../reasoningRegistry' import { @@ -137,13 +138,15 @@ export async function getAnthropicCompletion( anthropicClient?: Anthropic webSearch?: boolean reasoningEffort?: string + info?: CopilotInfo } ): Promise { const { provider, config } = getProviderAndCompletionConfig({ messages, stream: true, forceModelProvider: options?.forceModelProvider, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) let anthropicTools = convertOpenAIToolsToAnthropic(tools) diff --git a/frontend/src/lib/components/copilot/chat/chatLoop.ts b/frontend/src/lib/components/copilot/chat/chatLoop.ts index 14de05cd74..e6b9e5c060 100644 --- a/frontend/src/lib/components/copilot/chat/chatLoop.ts +++ b/frontend/src/lib/components/copilot/chat/chatLoop.ts @@ -14,6 +14,7 @@ import { type ReasoningProviderModel } from '../reasoningRegistry' import { getAnthropicCompletion, parseAnthropicCompletion } from './anthropic' +import type { CopilotInfo } from '$lib/aiStore' import { modelSupportsVision, usesAnthropicMessagesApi } from '../modelConfig' import { boundImagePartBytes, stripImagePartsFromMessages } from './imageUtils' import { @@ -49,6 +50,8 @@ export interface ChatLoopConfig { modelProvider: ReasoningProviderModel clients: ChatClients workspace: string + /** `workspace`'s AI config when it is not the tab's (an AI session). */ + info?: CopilotInfo /** * Enable provider-native web search. Defaults to true for compatible providers * and is re-read each iteration so model/provider changes take effect. Explicit @@ -371,6 +374,7 @@ export async function runChatLoop(config: ChatLoopConfig): Promise[] = [ // A known text-only model would reject the follow-up image message and fail // the turn, so refuse before capturing rather than buffer an image it can // never read. The model is re-read here because it can change between turns. - const model = tryGetCurrentModel() + const sessionAi = (ctx.helpers as GlobalToolHelpers | undefined)?.sessionAi + const model = sessionAi ? sessionAi().model : tryGetCurrentModel() if (model && !modelSupportsVision(model.provider, model.model)) { const cannotSee = `${model.model} cannot read images, so a screenshot would be discarded. Ask the user to describe what looks wrong, or to switch to a model that supports images.` ctx.toolCallbacks.setToolStatus(ctx.toolId, { @@ -4694,6 +4695,8 @@ export type GlobalToolHelpers = SessionToolHelpers & { // (possibly forked) workspace while $workspaceStore stays on the navigation workspace, // so permission gating (open_page) must read this, not the global store. operatingWorkspace?: string + // The session's model and its workspace's AI config, rather than the tab's. + sessionAi?: () => SessionAi // Wired only for session chats (see AIChatManager): the artifact tools are session-gated. artifacts?: SessionArtifactsStore getChatId?: () => string | undefined diff --git a/frontend/src/lib/components/copilot/chat/openai-responses.ts b/frontend/src/lib/components/copilot/chat/openai-responses.ts index 2071ff0d74..eccda3bc1a 100644 --- a/frontend/src/lib/components/copilot/chat/openai-responses.ts +++ b/frontend/src/lib/components/copilot/chat/openai-responses.ts @@ -28,6 +28,7 @@ import { OutputTokenLimitError } from './outputTokenLimit' import { buildAssistantToolCallMessage } from './openaiReasoning' import type { ResponseStream } from 'openai/lib/responses/ResponseStream.mjs' import type { AIProviderModel } from '$lib/gen' +import type { CopilotInfo } from '$lib/aiStore' import { openAIResponsesUsageToChatTokenUsage, type ChatTokenUsage } from './tokenUsage' interface ParsedCompletionResult { @@ -308,6 +309,7 @@ export async function getOpenAIResponsesCompletion( reasoningEffort?: string reasoningSummary?: boolean promptCacheKey?: string + info?: CopilotInfo } ) { const { provider, config } = getProviderAndCompletionConfig({ @@ -315,7 +317,8 @@ export async function getOpenAIResponsesCompletion( stream: true, tools, forceModelProvider: options?.forceModelProvider, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages, provider === 'deepseek') const responsesConfig = applyReasoningToConfig( @@ -379,6 +382,7 @@ export async function* getOpenAIResponsesCompletionStream( openaiClient?: OpenAI reasoningEffort?: string maxTokensCap?: number + info?: CopilotInfo } ): AsyncGenerator { const { provider, config } = getProviderAndCompletionConfig({ @@ -387,7 +391,8 @@ export async function* getOpenAIResponsesCompletionStream( tools, forceModelProvider: options?.forceModelProvider, maxTokensCap: options?.maxTokensCap, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages) // No prompt cache key here: a rejected key has to be retried without it, and this is @@ -717,13 +722,15 @@ export async function getNonStreamingOpenAIResponsesCompletion( resourceValue?: Record forceModelProvider?: AIProviderModel maxTokensCap?: number + info?: CopilotInfo } ): Promise { const { provider, config } = getProviderAndCompletionConfig({ messages, stream: false, forceModelProvider: options?.forceModelProvider, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages) diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index e7053ce141..79f8621e40 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -26,7 +26,7 @@ import { createWorkspaceMutationTools } from '../workspaceTools' import { setupTypeAcquisition, type DepsToGet } from '$lib/ata' import { getEffectiveModelContextWindow } from '../../modelConfig' import type { ReviewChangesOpts } from '../monaco-adapter' -import { copilotInfo, getCurrentModel } from '$lib/aiStore' +import { copilotInfo, getCurrentModel, type SessionAi } from '$lib/aiStore' import { get } from 'svelte/store' import { getDbSchemas } from '$lib/components/apps/components/display/dbtable/metadata' import { scriptLangToEditorLang } from '$lib/scripts' @@ -604,7 +604,10 @@ type PackageSearchResult = { } const packagesSearchCache = new Map() -export async function searchExternalIntegrationResources(args: { query: string }): Promise { +export async function searchExternalIntegrationResources( + args: { query: string }, + sessionAi?: SessionAi +): Promise { try { if (packagesSearchCache.has(args.query)) { return JSON.stringify(packagesSearchCache.get(args.query)) @@ -619,11 +622,14 @@ export async function searchExternalIntegrationResources(args: { query: string } (r: PackageSearchQuery) => r.searchScore >= best * NPM_RUNNER_UP_SHARE ) - const model = getCurrentModel() + const model = sessionAi ? sessionAi.model : getCurrentModel() + if (!model) { + throw new Error('No model selected') + } const modelContextWindow = getEffectiveModelContextWindow( model.provider, model.model, - get(copilotInfo).contextWindowPerModel + (sessionAi ? sessionAi.info : get(copilotInfo))?.contextWindowPerModel ) const results: PackageSearchResult[] = await Promise.all( filtered.map(async (r: PackageSearchQuery) => { @@ -684,9 +690,10 @@ export const searchNpmPackagesTool: SessionTool<{}> = { requires: NONE, def: SEARCH_NPM_PACKAGES_TOOL, planModeSafe: true, - fn: async ({ args, toolId, toolCallbacks }) => { + fn: async ({ args, toolId, toolCallbacks, helpers }) => { toolCallbacks.setToolStatus(toolId, { content: 'Searching for relevant packages...' }) - const result = await searchExternalIntegrationResources(args) + const sessionAi = (helpers as { sessionAi?: () => SessionAi } | undefined)?.sessionAi + const result = await searchExternalIntegrationResources(args, sessionAi?.()) toolCallbacks.setToolStatus(toolId, { content: 'Retrieved relevant packages' }) return result } diff --git a/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts b/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts new file mode 100644 index 0000000000..afe3dc773a --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts @@ -0,0 +1,145 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AIConfig } from '$lib/gen' +import { copilotSessionModel, setCopilotInfo } from '$lib/aiStore' +import { workspaceStore } from '$lib/stores' +import { workspaceAIClients } from '../lib' +import { AIChatManager } from './AIChatManager.svelte' +import { generateSessionSummary } from '$lib/components/sessions/sessionTitle' + +vi.mock('$app/navigation', () => ({ + goto: vi.fn(), + afterNavigate: vi.fn(), + beforeNavigate: vi.fn() +})) +vi.mock('monaco-editor', () => ({ Selection: class Selection {} })) +vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() })) + +// The session works in `staging` while the tab shows `prod`: every request the session +// makes must carry staging's proxy, model and limits. +const CONFIGS: Record = { + staging: { + providers: { mistral: { resource_path: 'u/admin/mistral', models: ['staging-model'] } }, + default_model: { provider: 'mistral', model: 'staging-model' }, + max_tokens_per_model: { 'mistral:staging-model': 3000 }, + context_window_per_model: { 'mistral:staging-model': 30000 } + }, + prod: { + providers: { deepseek: { resource_path: 'u/admin/deepseek', models: ['prod-model'] } }, + default_model: { provider: 'deepseek', model: 'prod-model' } + } +} + +vi.mock('$lib/gen', async (importOriginal) => ({ + ...(await importOriginal()), + WorkspaceService: { + getCopilotInfo: async ({ workspace }: { workspace: string }) => CONFIGS[workspace] + } +})) + +type SentRequest = { url: string; body: any } +let sent: SentRequest[] = [] + +function completionResponse(body: any): Response { + const text = 'Earlier work' + if (!body.stream) { + return Response.json({ + id: 'c', + object: 'chat.completion', + created: 0, + model: body.model, + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'Staging title' }, + finish_reason: 'stop' + } + ] + }) + } + const chunk = (delta: object, finish_reason: string | null) => + `data: ${JSON.stringify({ + id: 'c', + object: 'chat.completion.chunk', + created: 0, + model: body.model, + choices: [{ index: 0, delta, finish_reason }] + })}\n\n` + return new Response(chunk({ content: text }, null) + chunk({}, 'stop') + 'data: [DONE]\n\n', { + headers: { 'content-type': 'text/event-stream' } + }) +} + +function sessionManager(): AIChatManager { + const manager = new AIChatManager() + manager.isSessionChat = true + manager.workspaceResolver = () => 'staging' + manager.messages = [ + { role: 'user', content: 'q1' }, + { role: 'assistant', content: 'a1' }, + { role: 'user', content: 'q2' }, + { role: 'assistant', content: 'a2' }, + { role: 'user', content: 'q3' } + ] + manager.displayMessages = [ + { role: 'user', content: 'q1', index: 0 }, + { role: 'assistant', content: 'a1' }, + { role: 'user', content: 'q2', index: 2 }, + { role: 'assistant', content: 'a2' }, + { role: 'user', content: 'q3', index: 4 } + ] as AIChatManager['displayMessages'] + return manager +} + +function expectSentForStaging(request: SentRequest | undefined) { + expect(request?.url).toContain('/w/staging/ai/proxy/') + expect(request?.body.model).toBe('staging-model') + expect(request?.body.max_tokens).toBe(3000) +} + +beforeEach(() => { + sent = [] + vi.stubGlobal('location', { origin: 'http://localhost' }) + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input) + const body = JSON.parse( + String(init?.body ?? (input instanceof Request ? await input.text() : '{}')) + ) + sent.push({ url, body }) + return completionResponse(body) + }) + // The tab is on prod, with prod's model picked. + workspaceStore.set('prod') + workspaceAIClients.init('prod') + setCopilotInfo(CONFIGS.prod) + copilotSessionModel.set({ provider: 'deepseek', model: 'prod-model' }) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('an AI session in another workspace than the tab', () => { + it('names the session with its own workspace', async () => { + expect(await generateSessionSummary(sessionManager())).toBe('Staging title') + expect(sent).toHaveLength(1) + expectSentForStaging(sent[0]) + }) + + it('summarizes for compaction with its own workspace', async () => { + const manager = sessionManager() + await manager.compactManually() + expect(sent).toHaveLength(1) + expectSentForStaging(sent[0]) + }) + + it("compacts at its own workspace's context window", async () => { + const manager = sessionManager() + manager.abortController = new AbortController() + // 80% of staging's 30k window; far below the window prod's model would get. + const compacted = await (manager as any).compactIfOverTrigger(25000, { + provider: 'mistral', + model: 'staging-model' + }) + expect(compacted).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index d2eae56bcd..5975fc3546 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -47,7 +47,15 @@ import { import { convertOpenAIToAnthropicMessages } from './chat/anthropic' import type { Stream } from 'openai/core/streaming.mjs' import { generateRandomString } from '$lib/utils' -import { copilotInfo, getCurrentModel, getMetadataModel } from '$lib/aiStore' +import { + copilotInfo, + getCurrentModel, + getMetadataModel, + resolveMetadataModelFor, + resolveModelFor, + type AiTarget, + type CopilotInfo +} from '$lib/aiStore' import { emptyChatTokenUsage, openAICompletionsUsageToChatTokenUsage, @@ -279,7 +287,8 @@ export function getModelMaxTokens( function resolveMaxTokens( modelProvider: AIProviderModel, cap?: number, - reasoningEffort?: ReasoningEffort + reasoningEffort?: ReasoningEffort, + info?: CopilotInfo ): number { const defaultMaxTokens = getModelMaxTokens( modelProvider.provider, @@ -289,7 +298,7 @@ function resolveMaxTokens( const modelKey = `${modelProvider.provider}:${modelProvider.model}` let customMaxTokensStore: Record | undefined try { - customMaxTokensStore = get(copilotInfo)?.maxTokensPerModel + customMaxTokensStore = (info ?? get(copilotInfo))?.maxTokensPerModel } catch { // copilotInfo store may not be initialized in vitest } @@ -308,9 +317,10 @@ function getModelSpecificConfig( modelProvider: AIProviderModel, tools?: OpenAI.Chat.Completions.ChatCompletionTool[], maxTokensCap?: number, - reasoningEffort?: ReasoningEffort + reasoningEffort?: ReasoningEffort, + info?: CopilotInfo ) { - const maxTokens = resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort) + const maxTokens = resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort, info) if ( (modelProvider.provider === 'openai' || modelProvider.provider === 'azure_openai' || @@ -594,6 +604,7 @@ interface AnthropicCompletionParams { resourcePath?: string resourceValue?: Record maxTokensCap?: number + info?: CopilotInfo } function buildAnthropicProxyRequest({ @@ -603,7 +614,8 @@ function buildAnthropicProxyRequest({ workspace, resourcePath, resourceValue, - maxTokensCap + maxTokensCap, + info }: Omit) { const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) @@ -623,7 +635,7 @@ function buildAnthropicProxyRequest({ const body = { model: modelProvider.model, - max_tokens: resolveMaxTokens(modelProvider, maxTokensCap), + max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, undefined, info), messages: anthropicMessages, ...(system && { system }) } @@ -887,6 +899,11 @@ export function modelSupportsWebSearch(provider: AIProvider | undefined, model: return providerSupportsWebSearch(provider) } +/** The model a request sends: for `info`'s workspace when given, else the tab's. */ +function modelFor(info: CopilotInfo | undefined): AIProviderModel { + return info ? resolveModelFor(info) : getCurrentModel() +} + export function getProviderAndCompletionConfig({ messages, stream, @@ -894,7 +911,8 @@ export function getProviderAndCompletionConfig({ forceModelProvider, maxTokensCap, promptCaching, - reasoningEffort + reasoningEffort, + info }: { messages: ChatCompletionMessageParam[] stream: K @@ -907,13 +925,15 @@ export function getProviderAndCompletionConfig({ // The effort the caller will add with `applyReasoningToConfig`. Only sizes the // output budget here: a request that reasons needs room for the thinking. reasoningEffort?: ReasoningEffort + // The AI config of the workspace the request is made for, when it is not the tab's. + info?: CopilotInfo }): { provider: AIProvider config: K extends true ? ChatCompletionCreateParamsStreaming : ChatCompletionCreateParamsNonStreaming } { - const modelProvider = forceModelProvider ?? getCurrentModel() + const modelProvider = forceModelProvider ?? modelFor(info) const providerConfig = PROVIDER_COMPLETION_CONFIG_MAP[modelProvider.provider] const processedMessages = prepareMessages(modelProvider.provider, messages, { model: modelProvider.model, @@ -923,7 +943,7 @@ export function getProviderAndCompletionConfig({ provider: modelProvider.provider, config: { ...providerConfig, - ...getModelSpecificConfig(modelProvider, tools, maxTokensCap, reasoningEffort), + ...getModelSpecificConfig(modelProvider, tools, maxTokensCap, reasoningEffort, info), messages: processedMessages, stream } as any @@ -940,9 +960,10 @@ export async function getNonStreamingCompletion( workspace?: string // use a specific workspace proxy when testing a workspace resource forceModelProvider?: AIProviderModel maxTokensCap?: number // hard ceiling on output tokens (see METADATA_MAX_TOKENS) + info?: CopilotInfo // the AI config of `workspace`, when it is not the tab's } ) { - const modelProvider = options?.forceModelProvider ?? getCurrentModel() + const modelProvider = options?.forceModelProvider ?? modelFor(options?.info) if (usesAnthropicMessagesApi(modelProvider.provider, modelProvider.model)) { return getAnthropicNonStreamingCompletion({ @@ -953,7 +974,8 @@ export async function getNonStreamingCompletion( workspace: options?.workspace, resourcePath: options?.resourcePath, resourceValue: options?.resourceValue, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) } @@ -961,18 +983,18 @@ export async function getNonStreamingCompletion( const { provider, config } = getProviderAndCompletionConfig({ messages, stream: false, - forceModelProvider: options?.forceModelProvider, - maxTokensCap: options?.maxTokensCap + forceModelProvider: modelProvider, + maxTokensCap: options?.maxTokensCap, + info: options?.info }) // Use Responses API for OpenAI and Azure OpenAI if (provider === 'openai' || provider === 'azure_openai') { try { - const response = await getNonStreamingOpenAIResponsesCompletion( - messages, - abortController, - options - ) + const response = await getNonStreamingOpenAIResponsesCompletion(messages, abortController, { + ...options, + forceModelProvider: modelProvider + }) return response } catch (error) { console.error('Error using Responses API:', error) @@ -1003,13 +1025,17 @@ export async function getNonStreamingCompletion( return response } +/** `target` sends it for that workspace with its config; without one it uses the tab's. */ export async function getNonStreamingMetadataCompletion( messages: ChatCompletionMessageParam[], - abortController: AbortController + abortController: AbortController, + target?: AiTarget ) { return getNonStreamingCompletion(messages, abortController, { - forceModelProvider: getMetadataModel(), - maxTokensCap: METADATA_MAX_TOKENS + forceModelProvider: target ? resolveMetadataModelFor(target.info) : getMetadataModel(), + maxTokensCap: METADATA_MAX_TOKENS, + workspace: target?.workspace, + info: target?.info }) } @@ -1019,7 +1045,8 @@ export async function getFimCompletion( prompt: string, suffix: string, providerModel: AIProviderModel, - abortController: AbortController + abortController: AbortController, + workspace: string = get(workspaceStore)! ): Promise { // The Anthropic Messages API has no fill-in-the-middle endpoint, and Foundry // Claude deployments don't expose the OpenAI-compatible completions surface the @@ -1039,8 +1066,6 @@ export async function getFimCompletion( } } - const workspace = get(workspaceStore) - const response = await fetch( `${location.origin}${OpenAPI.BASE}/w/${workspace}/ai/proxy/fim/completions`, { @@ -1108,36 +1133,46 @@ export async function getCompletion( reasoningEffort?: string promptCaching?: boolean maxTokensCap?: number + // Send for this workspace, with its AI config, rather than the tab's. + workspace?: string + info?: CopilotInfo } ): Promise> { - const modelProvider = options?.forceModelProvider ?? getCurrentModel() + const modelProvider = options?.forceModelProvider ?? modelFor(options?.info) if (usesAnthropicMessagesApi(modelProvider.provider, modelProvider.model)) { return getAnthropicStreamingCompletion({ messages, modelProvider, abortController, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + workspace: options?.workspace, + info: options?.info }) } + const openaiClient = + options?.openaiClient ?? + (options?.workspace ? workspaceAIClients.createOpenaiClient(options.workspace) : undefined) const { provider, config } = getProviderAndCompletionConfig({ messages, stream: true, tools, - forceModelProvider: options?.forceModelProvider, + forceModelProvider: modelProvider, maxTokensCap: options?.maxTokensCap, promptCaching: options?.promptCaching, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) if (usesOpenAIResponsesApi(provider, modelProvider.model) && !options?.forceCompletions) { try { const stream = getOpenAIResponsesCompletionStream(messages, abortController, tools, { - forceModelProvider: options?.forceModelProvider, - openaiClient: options?.openaiClient, + forceModelProvider: modelProvider, + openaiClient, reasoningEffort: options?.reasoningEffort, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) as any return stream } catch (error) { @@ -1146,7 +1181,7 @@ export async function getCompletion( } // Use Completions API for other providers - const client = options?.openaiClient ?? workspaceAIClients.getOpenaiClient() + const client = openaiClient ?? workspaceAIClients.getOpenaiClient() // gpt-5.5+ refuse function tools here unless reasoning is off, so the Responses API // fallback turns it off where the model can rather than failing the turn. const reasoningEffort = @@ -1187,12 +1222,17 @@ export async function getCompletion( export async function getStreamedCompletionText( messages: ChatCompletionMessageParam[], abortController: AbortController, - options?: { maxTokensCap?: number } + // `workspace` and `info` send it for that workspace, with its AI config, rather than the tab's. + options?: { maxTokensCap?: number; workspace?: string; info?: CopilotInfo } ): Promise { + const modelProvider = modelFor(options?.info) const drain = async (forceCompletions: boolean) => { const stream = await getCompletion(messages, abortController, undefined, { forceCompletions, - maxTokensCap: options?.maxTokensCap + forceModelProvider: modelProvider, + maxTokensCap: options?.maxTokensCap, + workspace: options?.workspace, + info: options?.info }) let text = '' let finished = false @@ -1215,7 +1255,7 @@ export async function getStreamedCompletionText( } catch (error) { // The Responses API stream only fails once iterated, so the fallback to // chat completions for a deployment that doesn't serve it lives here. - const { provider, model } = getCurrentModel() + const { provider, model } = modelProvider if (abortController.signal.aborted || !usesOpenAIResponsesApi(provider, model)) { throw error } diff --git a/frontend/src/lib/components/copilot/loadCopilot.test.ts b/frontend/src/lib/components/copilot/loadCopilot.test.ts index 5bfcf1f547..a54d3be0ec 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.test.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.test.ts @@ -11,7 +11,12 @@ vi.mock('$lib/gen', () => ({ })) import { loadCopilot } from './loadCopilot' -import { copilotWorkspace } from '$lib/aiStore' +import { + copilotInfo, + copilotWorkspace, + getWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo +} from '$lib/aiStore' const config = { providers: { anthropic: { resource_path: 'u/admin/anthropic', models: ['m'] } } } @@ -34,16 +39,34 @@ describe('loadCopilot', () => { it('lets a re-requested workspace win back over the one that superseded it', async () => { const a1 = loadCopilot('a') const b = loadCopilot('b') - // A per-workspace cache would hand back `a1` here — which has already lost the - // apply race to `b`, so `a` would silently never be written. + // `a2` may share `a1`'s download but must apply it on its own token: `a1` already lost + // the apply race to `b`, so handing back `a1` itself would leave `a` never written. const a2 = loadCopilot('a') - expect(requests.map((r) => r.workspace)).toEqual(['a', 'b', 'a']) + expect(requests.map((r) => r.workspace)).toEqual(['a', 'b']) requests[0].resolve(config) requests[1].resolve(config) - requests[2].resolve(config) await Promise.all([a1, b, a2]) expect(get(copilotWorkspace)).toBe('a') }) + + // The config can change elsewhere (another tab, another admin): a refresh of the tab's config + // must also be what a session in that workspace sends with. + it('refreshes the workspace config sessions send with, keeping the old one until then', async () => { + const withModel = (model: string) => ({ + providers: { anthropic: { resource_path: 'u/admin/anthropic', models: [model] } } + }) + const sessionLoad = loadWorkspaceCopilotInfo('refreshed') + requests[0].resolve(withModel('old')) + await sessionLoad + const refresh = loadCopilot('refreshed') + await vi.waitFor(() => expect(requests).toHaveLength(2)) + expect(getWorkspaceCopilotInfo('refreshed')?.aiModels[0]?.model).toBe('old') + requests[1].resolve(withModel('new')) + await refresh + + expect(get(copilotInfo).aiModels[0]?.model).toBe('new') + expect(getWorkspaceCopilotInfo('refreshed')?.aiModels[0]?.model).toBe('new') + }) }) diff --git a/frontend/src/lib/components/copilot/loadCopilot.ts b/frontend/src/lib/components/copilot/loadCopilot.ts index 4b1e53a686..62a97e8dbf 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.ts @@ -1,5 +1,9 @@ -import { WorkspaceService } from '$lib/gen' -import { copilotWorkspace, setCopilotInfo } from '$lib/aiStore' +import { + applyCopilotInfo, + copilotWorkspace, + loadWorkspaceCopilotInfo, + setCopilotInfo +} from '$lib/aiStore' import { setAiClientWorkspace } from './aiClientWorkspace' import { writable } from 'svelte/store' @@ -44,9 +48,11 @@ export function loadCopilot(workspace: string): Promise { async function fetchAndApply(workspace: string, token: number) { setAiClientWorkspace(workspace) try { - const info = await WorkspaceService.getCopilotInfo({ workspace }) + // Through the per-workspace cache: a session in this workspace then sends with the config + // the tab shows. + const info = await loadWorkspaceCopilotInfo(workspace, true) if (token !== loadCopilotToken) return - setCopilotInfo(info) + applyCopilotInfo(info) copilotWorkspace.set(workspace) } catch (err) { if (token !== loadCopilotToken) return diff --git a/frontend/src/lib/components/deploymentRequest/AiReview.svelte b/frontend/src/lib/components/deploymentRequest/AiReview.svelte index 0af4488718..33964f60cc 100644 --- a/frontend/src/lib/components/deploymentRequest/AiReview.svelte +++ b/frontend/src/lib/components/deploymentRequest/AiReview.svelte @@ -1,7 +1,12 @@ + + -{#if showSvg} -
+{#if showSource} +
{code}
+{:else if svg === undefined} + +
+ +
+{:else} +
-{:else} - -
{code}
{/if} From 0e1464e877dcfabdffc8901d2a0735e04b73772e Mon Sep 17 00:00:00 2001 From: Guilhem Date: Tue, 10 Nov 2026 22:53:15 +0100 Subject: [PATCH 09/22] feat: reveal the failed call from a tool group's failed badge (#12320) * feat: reveal the failed call from a tool group's failed badge Co-Authored-By: Claude Opus 5.5 * fix: keep the failed badge's original font Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../copilot/chat/ChatCollapsibleCard.svelte | 4 ++ .../copilot/chat/ToolGroupDisplay.svelte | 51 +++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte index e5a9989365..ac8127dd50 100644 --- a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte +++ b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte @@ -17,6 +17,8 @@ labelMore?: string[] expanded: boolean onToggle: () => void + /** Called once the body has finished opening, when its contents have their final position. */ + onContentShown?: () => void // A card with nothing to reveal keeps the header inert (no chevron, no // hover affordance implying a toggle). toggleable?: boolean @@ -49,6 +51,7 @@ labelMore, expanded, onToggle, + onContentShown, toggleable = true, shimmer = false, settleLabel = false, @@ -161,6 +164,7 @@ {#if expanded && children}
{@render children()} diff --git a/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte index 77f58438da..a77a7bd691 100644 --- a/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte @@ -6,6 +6,8 @@ import { callFailed, groupHeader, type ToolGroup } from './toolGroups' import McpServerIcon from '$lib/components/mcp/McpServerIcon.svelte' import { resolveMcpServerMark } from '$lib/components/mcp/serverMark' + import { Button } from '$lib/components/common' + import { getChatViewHost } from './chatViewHost' interface Props { group: ToolGroup @@ -14,7 +16,30 @@ let { group, entry }: Props = $props() + const chatHost = getChatViewHost() + let expanded = $state(false) + const rows: Record = {} + let scrollOnceOpen = false + + function scrollToFailedCall() { + const failed = group.entries.find((e) => e.message.role === 'tool' && callFailed(e.message)) + if (failed) { + // Here rather than at the click: while the group opens above a chat pinned to its end, + // scroll anchoring keeps it at the end, and that scroll turns automatic scroll back on. + chatHost.disableAutomaticScroll() + rows[failed.index]?.scrollIntoView({ block: 'center' }) + } + } + + function revealFailedCall() { + if (expanded) { + scrollToFailedCall() + } else { + scrollOnceOpen = true + expanded = true + } + } const calls = $derived( group.entries.map((e) => e.message).filter((m): m is ToolDisplayMessage => m.role === 'tool') @@ -59,7 +84,16 @@ {#snippet status()}
{#if failedCount > 0} - {failedCount} failed + {/if} {#if previewCard} @@ -72,7 +106,16 @@ label={header.label} labelMore={header.more} {expanded} - onToggle={() => (expanded = !expanded)} + onToggle={() => { + scrollOnceOpen = false + expanded = !expanded + }} + onContentShown={() => { + if (scrollOnceOpen) { + scrollOnceOpen = false + scrollToFailedCall() + } + }} shimmer={running} settleLabel {liveLine} @@ -83,6 +126,8 @@ contentClass="border-0 border-l rounded-none bg-transparent p-0 pl-2 ml-1.5 mt-0.5" > {#each group.entries as { message, index } (index)} - {@render entry(message, index)} +
+ {@render entry(message, index)} +
{/each} From 9d7adefe23f130168e7e9d77ce4a52c4c4f2223f Mon Sep 17 00:00:00 2001 From: Guilhem Date: Tue, 10 Nov 2026 22:53:31 +0100 Subject: [PATCH 10/22] fix: keep the sessions sidebar icons stable until the workspace list loads (#12322) Co-authored-by: Claude Opus 5.5 --- .../src/lib/components/sessions/SessionPicker.svelte | 10 +++++++--- .../lib/components/sessions/sessionState.svelte.ts | 12 ++++++++++-- .../src/lib/components/sessions/sessionState.test.ts | 8 ++++++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/frontend/src/lib/components/sessions/SessionPicker.svelte b/frontend/src/lib/components/sessions/SessionPicker.svelte index a6c8ceb630..43d17ebf6a 100644 --- a/frontend/src/lib/components/sessions/SessionPicker.svelte +++ b/frontend/src/lib/components/sessions/SessionPicker.svelte @@ -65,7 +65,7 @@ SIDEBAR_RECENT_MS } from '$lib/components/sidebar/SidebarShowOlder.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' - import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' import { workspaceIsFork } from '$lib/utils/workspaceHierarchy' import { WorkspaceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' @@ -88,7 +88,7 @@ } function isForkFor(session: Session): boolean { - return isForkSession(session, $userWorkspaces) + return isForkSession(session, $usersWorkspaceStore ? $userWorkspaces : undefined) } // Compute the unread count for a session. Driven by the per-runtime @@ -420,7 +420,11 @@ }) function isUnavailableFork(session: Session): boolean { - return !!session.workspace_id && !$userWorkspaces.find((w) => w.id === session.workspace_id) + return ( + !!session.workspace_id && + !!$usersWorkspaceStore && + !$userWorkspaces.find((w) => w.id === session.workspace_id) + ) } async function activate(session: Session, restoreFocus: boolean = false) { diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index fed45687c0..e9282f01b8 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -59,9 +59,15 @@ export type SessionTarget = { kind: 'flow' | 'script' | 'raw_app' | 'pipeline'; // Sessions whose committed workspace is no longer in the user's list are // still treated as forks (the "unavailable" terminal state) so we don't // flip them back to Building once access is lost. -export function isForkSession(session: Session, allWorkspaces: UserWorkspace[]): boolean { +// `allWorkspaces` is undefined until the workspace list has loaded: a workspace absent +// from it then says nothing, so only the stored root can tell a fork from a root. +export function isForkSession( + session: Session, + allWorkspaces: UserWorkspace[] | undefined +): boolean { const wsId = session.workspace_id ?? session.pending_workspace_id if (!wsId) return false + if (!allWorkspaces) return !!session.workspace_root_id && wsId !== session.workspace_root_id const ws = allWorkspaces.find((w) => w.id === wsId) if (!ws) return !!session.workspace_id return !!ws.parent_workspace_id @@ -315,7 +321,9 @@ export function sessionInCurrentFamily(s: Session): boolean { function ensureSessionRootId(s: Session): boolean { if (s.workspace_root_id || s.transient) return false const workspaceId = s.workspace_id ?? s.pending_workspace_id - if (workspaceId && get(userWorkspaces).length === 0) return false + // `userWorkspaces` holds `admins` for a superadmin before the list loads, so its + // length alone would stamp a fork's own id as its root. + if (workspaceId && (!get(usersWorkspaceStore) || get(userWorkspaces).length === 0)) return false const root = sessionRootId(s) if (!root) return false s.workspace_root_id = root diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index c670e6dcc8..3c6d7f6d27 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -89,6 +89,14 @@ describe('isForkSession', () => { true ) }) + + it('falls back to the stored root until the workspace list has loaded', () => { + const fork = session({ workspace_id: 'fork', workspace_root_id: 'root' }) + const root = session({ workspace_id: 'root', workspace_root_id: 'root' }) + expect(isForkSession(fork, undefined)).toBe(true) + expect(isForkSession(root, undefined)).toBe(false) + expect(isForkSession(session({ workspace_id: 'fork' }), undefined)).toBe(false) + }) }) describe('commitSessionWorkspace — fork-creation failure', () => { From 949ef234a841dd18eca661addbf2369329dbc9a3 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Tue, 10 Nov 2026 22:53:48 +0100 Subject: [PATCH 11/22] fix: mark delete and discard tool confirmations as destructive (#12324) Co-authored-by: Claude Opus 5.5 --- .../copilot/chat/ToolConfirmationFooter.svelte | 3 +++ .../components/copilot/chat/ToolExecutionDisplay.svelte | 1 + .../src/lib/components/copilot/chat/toolConfirmAction.ts | 9 ++++++--- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte index faf0395bc3..5e3d4048dc 100644 --- a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte @@ -12,6 +12,7 @@ confirmLabel: string /** Omit for a label-only confirm button. */ confirmIcon?: any + confirmDestructive?: boolean class?: string } @@ -22,6 +23,7 @@ rejectDestructive = false, confirmLabel, confirmIcon, + confirmDestructive = false, class: className }: Props = $props() @@ -48,6 +50,7 @@
{#each RUNS_COLUMNS.filter((c) => shownColumns.includes(c.id)) as column (column.id)} -
+
{column.id === 'started' ? '' : column.label}
{/each} @@ -459,10 +459,12 @@ {#if jobs?.length == 0 && (!showExternalJobs || externalJobs?.length == 0)}
No jobs found for the selected filters.
{:else} +
{ e.preventDefault() rightClickPopover?.open(e) @@ -480,7 +482,13 @@ > {#snippet header()}{/snippet} {#snippet item({ index, style })} -
+
{#if flatJobs} {@const jobOrDate = flatJobs[index]} {#if jobOrDate} From d37dcca4c6d8dfdfb52cf96e2b36fbab32896e5a Mon Sep 17 00:00:00 2001 From: Guilhem Date: Wed, 11 Nov 2026 11:52:58 +0100 Subject: [PATCH 21/22] fix: hide your own empty user space with the hide empty folders option (#12345) * fix: hide your own empty user space with the hide empty folders option Co-Authored-By: Claude Opus 5.5 * fix: gate hiding your own empty space on the option being offered Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- frontend/src/lib/components/home/ItemsList.svelte | 9 ++++++--- .../src/lib/components/home/TreeViewRoot.svelte | 13 +++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/frontend/src/lib/components/home/ItemsList.svelte b/frontend/src/lib/components/home/ItemsList.svelte index 042ba83748..2ecb32c73f 100644 --- a/frontend/src/lib/components/home/ItemsList.svelte +++ b/frontend/src/lib/components/home/ItemsList.svelte @@ -963,6 +963,9 @@ !flatList && !searching && ownerFilter == undefined && labelFilter == undefined ) + // Only the unfiltered tree lists folders it holds no rows of. + let hideEmptyFoldersOffered = $derived(treeLazyMode && !archived && keepEmptyFolders) + let listSettingsItems: MenuItem[] = $derived([ { displayName: 'Flat list', @@ -973,10 +976,9 @@ { displayName: 'Hide empty folders', description: - 'Folders with no scripts, flows, apps, agents or data pipelines. They may still hold resources, variables or schedules.', + 'Folders and your user space with no scripts, flows, apps, agents or data pipelines. They may still hold resources, variables or schedules.', toggle: hideEmptyFolders, - // Only the unfiltered tree lists folders it holds no rows of. - hide: !treeLazyMode || archived || !keepEmptyFolders, + hide: !hideEmptyFoldersOffered, action: () => setHideEmptyFolders(!hideEmptyFolders) }, { @@ -2462,6 +2464,7 @@ : undefined} keepEmptyFolders={keepEmptyFolders && !hideEmptyFolders} {keptFolders} + hideEmptySelf={hideEmptyFoldersOffered && hideEmptyFolders} /> {/key} {/if} diff --git a/frontend/src/lib/components/home/TreeViewRoot.svelte b/frontend/src/lib/components/home/TreeViewRoot.svelte index bd8c7ba147..8fc3dfea56 100644 --- a/frontend/src/lib/components/home/TreeViewRoot.svelte +++ b/frontend/src/lib/components/home/TreeViewRoot.svelte @@ -34,7 +34,7 @@ // when it doesn't apply, in which case every owner is injected as before. ownerCounts?: Record // The viewer's own username: their personal space is a fixture of the tree and - // stays even when empty, so they have somewhere to create into. + // stays even when empty, so they have somewhere to create into, unless `hideEmptySelf`. selfUsername?: string ownerLoad?: Record< string, @@ -64,6 +64,8 @@ keepEmptyFolders?: boolean // Folders injected even when empty and `keepEmptyFolders` is off. keptFolders?: string[] + // Drop `selfUsername`'s space too when it holds nothing, instead of keeping it as "0 items". + hideEmptySelf?: boolean } let { @@ -92,7 +94,8 @@ ownerLead, ownerDetail, keepEmptyFolders = false, - keptFolders + keptFolders, + hideEmptySelf = false }: Props = $props() const unruled = inUnruledList() @@ -121,6 +124,7 @@ selfUsername keepEmptyFolders keptFolders + hideEmptySelf untrack(() => { // While searching, `items` is already relevance-ranked and the sort // selector is disabled, so keep that order: a no-op leaf comparator @@ -170,8 +174,9 @@ for (const username of allUsers) { if (presentUsers.has(username)) continue // Your own space is exempt from the drop: it's where you create, so it - // stays visible (as "0 items") when empty rather than disappearing. - if (username !== selfUsername && isEmptyOwner(`u/${username}`)) continue + // stays visible (as "0 items") when empty rather than disappearing, unless `hideEmptySelf`. + if ((hideEmptySelf || username !== selfUsername) && isEmptyOwner(`u/${username}`)) + continue presentUsers.add(username) missingUsers.push({ username, items: [] }) } From abede3a02978f4c65c9c018b27a4167fd31feac2 Mon Sep 17 00:00:00 2001 From: Florian Bienefelt Date: Wed, 11 Nov 2026 11:55:08 +0100 Subject: [PATCH 22/22] fix: back off job polling to 2s after 100 polls (#12344) Co-authored-by: Claude Fable 5.2 --- frontend/src/lib/components/JobLoader.svelte | 6 +++--- frontend/src/lib/components/waitJob.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frontend/src/lib/components/JobLoader.svelte b/frontend/src/lib/components/JobLoader.svelte index fa812cc6e4..2a15f27022 100644 --- a/frontend/src/lib/components/JobLoader.svelte +++ b/frontend/src/lib/components/JobLoader.svelte @@ -972,10 +972,10 @@ return } let nextIteration = 50 - if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { - nextIteration = 500 - } else if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { + if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { nextIteration = 2000 + } else if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { + nextIteration = 500 } setTimeout(() => syncer(id, callbacks), nextIteration) } diff --git a/frontend/src/lib/components/waitJob.ts b/frontend/src/lib/components/waitJob.ts index 483ef4827e..ee17236657 100644 --- a/frontend/src/lib/components/waitJob.ts +++ b/frontend/src/lib/components/waitJob.ts @@ -56,10 +56,10 @@ export async function waitJob(id: string, forceWorkspace?: string) { let nextIteration = 50 - if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { - nextIteration = 500 - } else if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { + if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { nextIteration = 2000 + } else if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { + nextIteration = 500 } setTimeout(checkJob, nextIteration)