From 1f1df1254ebc417a8344801b571c4be8e98636c4 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Thu, 15 Oct 2026 17:21:28 +0200 Subject: [PATCH 01/20] fix: relock scripts and flow steps whose code changed on deploy (#11794) * fix: relock scripts deployed from a draft that carries the deployed lock Co-Authored-By: Claude Opus 5.5 (1M context) * chore: reword fetchDeployed lock comment Co-Authored-By: Claude Opus 5.5 (1M context) * fix: drop the lock of flow steps whose code the chat changed Co-Authored-By: Claude Opus 5.5 (1M context) * fix: drop stale flow step locks at deploy, from drafts and the flow editor Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep locks of copied flows and never block a deploy on the lock check Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep the lock of a renamed or duplicated flow step with unchanged code Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- .../src/lib/components/FlowBuilder.svelte | 11 ++++ .../copilot/chat/global/core.test.ts | 33 +++++++++++ .../components/copilot/chat/global/core.ts | 10 +++- .../components/flows/staleStepLocks.test.ts | 25 ++++++++ .../lib/components/flows/staleStepLocks.ts | 33 +++++++++++ frontend/src/lib/utils_draft_deploy.test.ts | 58 +++++++++++++++++++ frontend/src/lib/utils_draft_deploy.ts | 16 ++++- 7 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 frontend/src/lib/components/flows/staleStepLocks.test.ts create mode 100644 frontend/src/lib/components/flows/staleStepLocks.ts diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 17f984bac9..f533fcc1f0 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -49,6 +49,7 @@ import WorkspaceScriptSettingsDrawer from './flows/content/WorkspaceScriptSettingsDrawer.svelte' import FlowEditorDrawer from './flows/content/FlowEditorDrawer.svelte' import { dfs as dfsApply } from './flows/dfs' + import { dropStaleStepLocks } from './flows/staleStepLocks' import { claimLinkedToolsFetch, invalidateLinkedToolsFetches, @@ -627,6 +628,16 @@ } } + // The editor clears a step's lock when its code is edited, but a draft written elsewhere + // can hold a step whose code changed and whose lock did not. A failed lookup skips the + // check rather than blocking the deploy. + const liveFlowValue = isNewFlow + ? undefined + : await FlowService.getFlowByPath({ workspace: opWorkspace!, path: initialPath }) + .then((f) => f.value) + .catch(() => undefined) + dropStaleStepLocks(flow.value, liveFlowValue) + if (isNewFlow) { await FlowService.createFlow({ workspace: opWorkspace!, diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index ba71ced69b..a07b0102ca 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -4773,6 +4773,39 @@ describe('global AI tools', () => { ).resolves.toBe(code) }) + // The worker reuses a non-empty step lock, so an edited step keeping its lock deploys + // against the old dependencies. + it('set_flow_module_code drops the lock of the edited step only', async () => { + const step = (id: string) => ({ + id, + value: { + type: 'rawscript', + language: 'python3', + content: 'import requests', + lock: 'requests==2.0', + input_transforms: {} + } + }) + seedBackendDraft('flow', 'f/flows/locked', { + path: 'f/flows/locked', + summary: 'f', + description: '', + value: { modules: [step('edited'), step('untouched')] }, + schema: {} + }) + + await callGlobalTool('set_flow_module_code', { + path: 'f/flows/locked', + module_id: 'edited', + code: 'import yaml' + }) + + const [edited, untouched] = getBackendDraft('flow', 'f/flows/locked').value.modules + expect(edited.value.content).toBe('import yaml') + expect(edited.value).not.toHaveProperty('lock') + expect(untouched.value.lock).toBe('requests==2.0') + }) + it('warns about every empty rawscript body (top-level, nested, preprocessor, failure) and skips populated ones', async () => { const result = JSON.parse( await callGlobalTool('write_flow', { diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 3b6064dee6..6f762a4a22 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -52,6 +52,7 @@ import { withAgentDrafts } from '$lib/components/flows/linkedAgentDrafts' import { resolveLinkedAgentTools } from '$lib/components/flows/flowState' import { enabledToolNames, type AgentTool } from '$lib/components/flows/agentToolUtils' import { evalValue } from '$lib/components/flows/utils.svelte' +import { dropStaleStepLocks } from '$lib/components/flows/staleStepLocks' import { quickjsReady } from '$lib/utils/quickjsEval.svelte' import { updateRawAppPolicy } from '$lib/components/raw_apps/rawAppPolicy' import { @@ -5804,7 +5805,12 @@ type ScriptDraftArgs = { const SCRIPT_SPEC: WriteSpec = { probe: (workspace, path) => ScriptService.existsScriptByPath({ workspace, path }), fetchDeployed: async (workspace, path) => { - const existing = await ScriptService.getScriptByPath({ workspace, path }) + // The deployed lock describes the deployed content, not the draft's; the deploy recomputes it. + const { + lock: _lock, + lock_error_logs: _lockErrorLogs, + ...existing + } = await ScriptService.getScriptByPath({ workspace, path }) return { ...(existing as unknown as NewScript), parent_hash: existing.hash } }, buildDraft: async (base, args, path) => { @@ -5903,6 +5909,8 @@ const FLOW_SPEC: WriteSpec = { } } } + // Also checked at deploy; dropped here too because a test run of the draft reads the locks. + dropStaleStepLocks(value, base?.value) return base ? { ...structuredClone(base), diff --git a/frontend/src/lib/components/flows/staleStepLocks.test.ts b/frontend/src/lib/components/flows/staleStepLocks.test.ts new file mode 100644 index 0000000000..ae12860391 --- /dev/null +++ b/frontend/src/lib/components/flows/staleStepLocks.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest' +import { dropStaleStepLocks } from './staleStepLocks' + +const step = (id: string, content: string, lock?: string) => + ({ id, value: { type: 'rawscript', language: 'python3', content, lock } }) as any + +describe('dropStaleStepLocks', () => { + // A rename or duplicate gives the step a new id; its code and lock still match. + it('keeps the lock of a renamed or duplicated step whose code is unchanged', () => { + const base = { modules: [step('a', 'import requests', 'requests==2.0')] } + const value = { + modules: [ + step('a', 'import requests', 'requests==2.0'), + step('a_copy', 'import requests', 'requests==2.0'), + step('a_edited_copy', 'import yaml', 'requests==2.0') + ] + } + dropStaleStepLocks(value as any, base as any) + expect(value.modules.map((m) => m.value.lock)).toEqual([ + 'requests==2.0', + 'requests==2.0', + undefined + ]) + }) +}) diff --git a/frontend/src/lib/components/flows/staleStepLocks.ts b/frontend/src/lib/components/flows/staleStepLocks.ts new file mode 100644 index 0000000000..2b9cacfb72 --- /dev/null +++ b/frontend/src/lib/components/flows/staleStepLocks.ts @@ -0,0 +1,33 @@ +import type { FlowModule, FlowValue } from '$lib/gen' +import { forEachFlowModule } from './dfs' + +/** + * Drops, in place, the lock of every inline step whose code differs from the same step in + * `base`. The worker reuses any non-empty step lock, so a step whose code changed but kept its + * lock runs against the old dependencies. Unchanged steps keep theirs, so a deploy does not + * re-resolve (and possibly upgrade) what nobody touched. A step id `base` lacks (a renamed or + * duplicated step) keeps its lock only when some `base` step has the same code. Without a base + * nothing is dropped: a copied or imported flow carries locks that match its code. + */ +export function dropStaleStepLocks(value: FlowValue, base: FlowValue | undefined): void { + if (!base) return + const allModules = (v: FlowValue) => + [...(v.modules ?? []), v.preprocessor_module, v.failure_module].filter( + (m): m is FlowModule => m != null + ) + const contentOf = (m: FlowModule) => (m.value as { content?: unknown }).content + const baseContentById = new Map() + const baseContents = new Set() + forEachFlowModule(allModules(base), (m) => { + baseContentById.set(m.id, contentOf(m)) + baseContents.add(contentOf(m)) + }) + forEachFlowModule(allModules(value), (m) => { + const step = m.value as { content?: unknown; lock?: unknown } + if (step.lock == undefined) return + const unchanged = baseContentById.has(m.id) + ? baseContentById.get(m.id) === step.content + : baseContents.has(step.content) + if (!unchanged) delete step.lock + }) +} diff --git a/frontend/src/lib/utils_draft_deploy.test.ts b/frontend/src/lib/utils_draft_deploy.test.ts index 5f503989c8..3164a05bfc 100644 --- a/frontend/src/lib/utils_draft_deploy.test.ts +++ b/frontend/src/lib/utils_draft_deploy.test.ts @@ -124,6 +124,64 @@ describe('deployDraft preserves on_behalf_of', () => { }) }) +// The backend skips the dependency job when `lock` is set, so a draft that inherited the +// deployed lock would deploy new content against the old lockfile. +describe('deployDraft: script lock', () => { + beforeEach(() => vi.clearAllMocks()) + + it('never sends the draft lock, so the backend relocks', async () => { + vi.mocked(ScriptService.getScriptByPath).mockResolvedValueOnce({ + hash: 'v1', + draft: { + path: 'f/admin/fetch', + content: 'import requests', + lock: 'certifi==2024.1.1', + lock_error_logs: 'old error' + } + } as any) + + await deployDraft('script', 'f/admin/fetch', 'ws') + const body = vi.mocked(ScriptService.createScript).mock.calls[0][0].requestBody + expect(body).not.toHaveProperty('lock') + expect(body).not.toHaveProperty('lock_error_logs') + }) + + it('flow: drops the lock of a step whose code differs from the deployed one only', async () => { + const step = (id: string, content: string) => ({ + id, + value: { type: 'rawscript', language: 'python3', content, lock: 'requests==2.0' } + }) + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + value: { modules: [step('edited', 'import requests'), step('kept', 'import requests')] }, + draft: { + path: 'f/admin/flow', + value: { modules: [step('edited', 'import yaml'), step('kept', 'import requests')] } + } + } as any) + + await deployDraft('flow', 'f/admin/flow', 'ws') + const [edited, kept] = vi.mocked(FlowService.updateFlow).mock.calls[0][0].requestBody.value + .modules as any[] + expect(edited.value).not.toHaveProperty('lock') + expect(kept.value.lock).toBe('requests==2.0') + }) + + // A never-deployed flow is often a copy or an import, whose locks match its code. + it('flow: keeps every lock when nothing is deployed to compare against', async () => { + const step = { id: 'copied', value: { type: 'rawscript', content: 'x', lock: 'requests==2.0' } } + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + no_deployed: true, + value: { modules: [step] }, + draft: { path: 'f/admin/copy', value: { modules: [step] } } + } as any) + + await deployDraft('flow', 'f/admin/copy', 'ws', { draftOnly: true }) + const [copied] = vi.mocked(FlowService.createFlow).mock.calls[0][0].requestBody.value + .modules as any[] + expect(copied.value.lock).toBe('requests==2.0') + }) +}) + // The resource branch reads the item again when the deploy lands, and falls back to the deployed // row when the draft has gone. That row keeps its value under `value` and carries no `args` at // all, so reading it as a draft (`value: d.args ?? {}`) would replace a live resource with `{}`. diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index 44dec7f124..b17b17cbc7 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -46,6 +46,7 @@ import { setLocalDraftHint } from '$lib/localDraftHints.svelte' import { userStore } from '$lib/stores' import { deployTriggers, type Trigger } from '$lib/components/triggers/utils' import { saveScheduleFromCfg } from '$lib/components/flows/scheduleUtils' +import { dropStaleStepLocks } from '$lib/components/flows/staleStepLocks' import { saveHttpRouteFromCfg } from '$lib/components/triggers/http/utils' import { saveWebsocketTriggerFromCfg } from '$lib/components/triggers/websocket/utils' import { savePostgresTriggerFromCfg } from '$lib/components/triggers/postgres/utils' @@ -469,7 +470,15 @@ export async function deployDraft( const r = (await ScriptService.getScriptByPath({ workspace, path, getDraft: true })) as any const d = r.draft ?? r // Drop editor-only / server-managed keys; deploy as a real (non-draft) version. - const { draft_triggers: draftTriggers, draft_only: _o, ...rest } = d + // A draft seeded from the deployed script carries its `lock`, and the backend skips + // the dependency job whenever `lock` is set, so the new content would keep the old lock. + const { + draft_triggers: draftTriggers, + draft_only: _o, + lock: _lock, + lock_error_logs: _lockErrorLogs, + ...rest + } = d const scriptPath = d.path ?? path // Deploy at the draft's path so a rename in the draft is honored (same as // the editor: createScript at the new path with parent_hash links lineage). @@ -490,6 +499,9 @@ export async function deployDraft( } else if (kind === 'flow') { const r = (await FlowService.getFlowByPath({ workspace, path, getDraft: true })) as any const d = r.draft ?? r + const value = d.value ? structuredClone(d.value) : d.value + // With nothing deployed the server fills `r.value` from the draft itself. + if (value) dropStaleStepLocks(value, draftOnly || r.no_deployed ? undefined : r.value) const requestBody = { // Deploy at the draft's intended path: flow/app/raw-app drafts keep the // user-typed path in `draft_path` (a never-deployed item is parked at a @@ -498,7 +510,7 @@ export async function deployDraft( path: d.draft_path ?? d.path ?? path, summary: d.summary ?? '', description: d.description ?? '', - value: d.value, + value, schema: d.schema, tag: d.tag, dedicated_worker: d.dedicated_worker, From 7da234481333fcbdc348215589e2d3bfe5394b4a Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:21:56 +0200 Subject: [PATCH 02/20] fix: let raw app SDK tokens read the viewer's identity without a toggle (#11790) * feat: grant raw app SDK tokens identity access without a toggle * test: pin the implicit identity scope on raw app SDK tokens * refactor: let raw app SDK tokens reach whoami at the route check --- backend/windmill-api-auth/src/scopes.rs | 12 +++++-- backend/windmill-api/openapi.yaml | 3 +- backend/windmill-api/src/apps.rs | 13 +++++-- .../src/mcp/auto_generated_endpoints.rs | 8 +++-- cli/src/guidance/skills.gen.ts | 4 +-- .../apps/editor/AppEditorHeaderDeploy.svelte | 10 +++--- .../raw_apps/RawAppSdkConsent.svelte | 4 +-- .../lib/components/raw_apps/sdkScopes.test.ts | 36 +++++++++++-------- .../src/lib/components/raw_apps/sdkScopes.ts | 26 +++++++++----- frontend/src/lib/mcpEndpointTools.ts | 8 +++-- system_prompts/auto-generated/prompts.ts | 2 +- .../auto-generated/skills/raw-app/SKILL.md | 4 +-- system_prompts/base/raw-app.md | 4 +-- 13 files changed, 88 insertions(+), 46 deletions(-) diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index 1b605e70eb..bdbab1bfe7 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -73,7 +73,12 @@ pub fn check_route_access( .to_string(), )); } - if required_domain == ScopeDomain::Users && suffix != "users/whoami" { + if required_domain == ScopeDomain::Users { + // Whoami returns what the bundle already has in `window.ctx`, so it + // needs no declared scope. + if suffix == "users/whoami" { + return Ok(()); + } return Err(Error::PermissionDenied( "Access denied. A raw app frontend SDK token can only read the viewer's own identity." .to_string(), @@ -418,8 +423,9 @@ pub fn guest_session_scopes(app_path: &str) -> windmill_common::error::Result) -> bool { diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index db7280dbbf..e9b5732f0a 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -36871,7 +36871,8 @@ components: the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, - flow_conversations:write). + flow_conversations:write). Every such token can call whoami without + consent, whether `users:read` is declared or not. ListableApp: type: object diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 1dcee82e5c..453422403d 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -6779,8 +6779,8 @@ mod embed_token_tests { "POST", ), ("/api/w/test/jobs/restart/f/some-uuid", "POST"), - // `users:read` is presented to the viewer as "read your identity", so - // the workspace member directory must stay out of reach. + // `users:read` reaches whoami only: the workspace member directory must + // stay out of reach. ("/api/w/test/users/list", "GET"), ("/api/w/test/users/list_usage", "GET"), ("/api/w/test/users/username_to_email/admin", "GET"), @@ -6791,6 +6791,15 @@ mod embed_token_tests { "SDK token should deny {method} {path}" ); } + + // Whoami needs no declared scope. + let jobs_only = [ + "jobs:run".to_string(), + windmill_api_auth::scopes::RAW_APP_SDK_SENTINEL.to_string(), + ]; + assert!( + check_scopes_for_route(Some(&jobs_only[..]), "/api/w/test/users/whoami", "GET").is_ok() + ); } /// The token carries path-scoped `apps:run:` and `apps:read:` diff --git a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs index f449902f97..dd3c83a08d 100644 --- a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs +++ b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs @@ -599,6 +599,10 @@ pub fn all_tools() -> Vec { "include_draft_only": { "type": "boolean", "description": "When true, append per-user draft resources whose path has\nno deployed resource. Synthesized rows carry\n`draft_only: true`.\n" + }, + "starred_only": { + "type": "boolean", + "description": "Only the `ai_agent` resources the caller starred" } }, "required": [] @@ -1336,7 +1340,7 @@ is, a different one moves it there and archives the old path"), "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true — an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true — an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } } @@ -1453,7 +1457,7 @@ is, a different one moves it there and archives the old path"), "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true — an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true — an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } }, diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 8d33007984..3b7bfa2298 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6926,14 +6926,14 @@ An app's custom URL is not in \`raw_app.yaml\`: each workspace has its own file ## Sandbox isolation and frontend API access -New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`users:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in \`window.ctx\`, and whoami works with any of them. Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry \`Origin: null\`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or \`localStorage\`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. In \`raw_app.yaml\`: \`\`\`yaml sandbox: true -frontend_api: [jobs:run, users:read] +frontend_api: [jobs:run] \`\`\` A file with a \`sandbox\` key states both settings: \`sandbox: false\` turns isolation off, and a missing \`frontend_api\` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing \`sandbox: true\` does not unsandbox it. \`frontend_api\` needs \`sandbox: true\`; the push fails otherwise. diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte index dd6c163edd..41e0c5c3f2 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte @@ -24,7 +24,7 @@ type OnBehalfOfChoice } from '$lib/components/OnBehalfOfSelector.svelte' import { canUserBypassRuleKind, protectionRulesState } from '$lib/workspaceProtectionRules.svelte' - import { FRONTEND_SDK_SCOPES } from '$lib/components/raw_apps/sdkScopes' + import { FRONTEND_SDK_SCOPES, sdkScopesToConfirm } from '$lib/components/raw_apps/sdkScopes' import { logFeatureUsage } from '$lib/utils/featureUsage' import { useOperatingUser, @@ -436,7 +436,7 @@ tooltip="Each viewer approves these scopes before the app runs. The app's code, or an XSS bug in it, can use them as that viewer." > {#snippet badge()} - {#if policy.frontend_sdk_scopes?.length} + {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length}
{#each FRONTEND_SDK_SCOPES.filter( (s) => policy.frontend_sdk_scopes.includes(s.value) ) as scope (scope.value)} s !== scope.value) // Keep the curated order so the consent banner and the stored - // consent compare stably across deploys. + // consent compare stably across deploys. A leftover implicit scope is + // not in the list, so it drops here rather than keep minting a token + // for an app whose toggles all read off. const ordered = FRONTEND_SDK_SCOPES.map((s) => s.value).filter((s) => next.includes(s) ) @@ -481,7 +483,7 @@
{/each} - {#if policy.frontend_sdk_scopes?.length} + {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length}
A sandboxed app calls the API cross-origin, which older windmill-client diff --git a/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte b/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte index 28940eb02a..babe0b8c85 100644 --- a/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte @@ -2,7 +2,7 @@ import { Button } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' import { ShieldCheck } from 'lucide-svelte' - import { sdkScopeDescription, sdkScopeLabel } from './sdkScopes' + import { sdkScopeDescription, sdkScopeLabel, sdkScopesToConfirm } from './sdkScopes' let { scopes, @@ -35,7 +35,7 @@ The app's code will be able to call the Windmill API on your behalf, restricted to:

    - {#each scopes as scope (scope)} + {#each sdkScopesToConfirm(scopes) as scope (scope)}
  • {sdkScopeLabel(scope)}{#if sdkScopeDescription(scope)} { beforeEach(() => localStorage.clear()) it('only covers scopes the viewer actually approved', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(true) // The app added a scope after the viewer consented: it must ask again // rather than silently minting a broader token. - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read', 'jobs:run'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read', 'jobs:run'])).toBe(false) }) it('does not leak one viewer or app to another', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('b@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(false) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/other', ['users:read'])).toBe(false) - expect(hasStoredSdkConsent('a@w.dev', 'other', 'u/a/app', ['users:read'])).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('b@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/other', ['jobs:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'other', 'u/a/app', ['jobs:read'])).toBe(false) }) it('keeps the editor preview and the deployed app apart, and moves preview consent', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'], true)).toBe(false) - storeSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'], true) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'])).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'], true)).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'], true) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'])).toBe(false) movePreviewSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', 'u/a/real') - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/real', ['users:read'], true)).toBe(true) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'], true)).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/real', ['jobs:read'], true)).toBe(true) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'], true)).toBe(false) + }) + + it('never asks for the identity scope every token carries', () => { + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read', 'users:read'])).toBe(true) }) it('treats unreadable storage as no consent', () => { localStorage.setItem('wm_sdk_consent:a@w.dev:ws:u/a/app', 'not json') - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(false) + // Nothing to ask for: storage must not turn that into an empty prompt. + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) }) }) diff --git a/frontend/src/lib/components/raw_apps/sdkScopes.ts b/frontend/src/lib/components/raw_apps/sdkScopes.ts index 238f1b7278..a4600979ba 100644 --- a/frontend/src/lib/components/raw_apps/sdkScopes.ts +++ b/frontend/src/lib/components/raw_apps/sdkScopes.ts @@ -1,7 +1,12 @@ // Frontend-SDK permissions for raw apps: the curated scopes an app author may // declare in `policy.frontend_sdk_scopes` (mirrors FRONTEND_SDK_ALLOWED_SCOPES -// in the backend `apps.rs` — both lists must stay in sync), plus the viewer-side -// consent persistence for the permission banner. +// in the backend `apps.rs` — both lists must stay in sync, except for the +// implicit scope below), plus the viewer-side consent persistence for the +// permission banner. + +/** Never toggled nor asked for: every SDK token reaches whoami without it, and whoami + * returns what the bundle already gets in `window.ctx`. */ +export const IMPLICIT_SDK_SCOPE = 'users:read' export const FRONTEND_SDK_SCOPES: { value: string; label: string; description: string }[] = [ { @@ -14,11 +19,6 @@ export const FRONTEND_SDK_SCOPES: { value: string; label: string; description: s label: 'Read jobs and results', description: 'Read jobs and their results, and list the runs the viewer can see' }, - { - value: 'users:read', - label: 'Read your identity', - description: 'Call whoami (Read the viewer username, email, groups, is_super_admin...)' - }, { value: 'resources:read', label: 'Read resources', @@ -59,10 +59,18 @@ function sdkConsentKey(viewer: string, workspace: string, path: string, preview: return `wm_sdk_consent:${preview ? 'p:' : ''}${viewer}:${workspace}:${path}` } +/** The declared scopes the viewer is asked to approve. */ +export function sdkScopesToConfirm(scopes: string[]): string[] { + return scopes.filter((s) => s !== IMPLICIT_SDK_SCOPE) +} + /** True when `approved` (a consent the viewer gave) covers every scope the app now * declares. Fewer scopes need no new consent; one more does. */ export function sdkConsentCovers(approved: unknown, scopes: string[]): boolean { - return Array.isArray(approved) && scopes.every((s) => approved.includes(s)) + const needed = sdkScopesToConfirm(scopes) + return ( + needed.length === 0 || (Array.isArray(approved) && needed.every((s) => approved.includes(s))) + ) } /** True when a previously stored "do not ask again" consent covers every @@ -80,7 +88,7 @@ export function hasStoredSdkConsent( ) return sdkConsentCovers(stored, scopes) } catch (_) { - return false + return sdkConsentCovers(null, scopes) } } diff --git a/frontend/src/lib/mcpEndpointTools.ts b/frontend/src/lib/mcpEndpointTools.ts index 2c12e514b9..b3b70cfaa2 100644 --- a/frontend/src/lib/mcpEndpointTools.ts +++ b/frontend/src/lib/mcpEndpointTools.ts @@ -608,6 +608,10 @@ export const mcpEndpointTools: EndpointTool[] = [ "include_draft_only": { "type": "boolean", "description": "When true, append per-user draft resources whose path has\nno deployed resource. Synthesized rows carry\n`draft_only: true`.\n" + }, + "starred_only": { + "type": "boolean", + "description": "Only the `ai_agent` resources the caller starred" } }, "required": [] @@ -1343,7 +1347,7 @@ export const mcpEndpointTools: EndpointTool[] = [ "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } } @@ -1460,7 +1464,7 @@ export const mcpEndpointTools: EndpointTool[] = [ "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } }, diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 9aee298999..69565dd9d4 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1148,7 +1148,7 @@ When a deploy widens who may open the app, tell the user in plain words. ## Sandbox isolation and frontend API access -New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`users:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in \`window.ctx\`, and whoami works with any of them. Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry \`Origin: null\`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or \`localStorage\`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. You cannot turn isolation off; the user does it in the app's deploy settings. diff --git a/system_prompts/auto-generated/skills/raw-app/SKILL.md b/system_prompts/auto-generated/skills/raw-app/SKILL.md index 7a5667c106..df5e7ece6a 100644 --- a/system_prompts/auto-generated/skills/raw-app/SKILL.md +++ b/system_prompts/auto-generated/skills/raw-app/SKILL.md @@ -483,14 +483,14 @@ An app's custom URL is not in `raw_app.yaml`: each workspace has its own file ne ## Sandbox isolation and frontend API access -New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `users:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them. Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. In `raw_app.yaml`: ```yaml sandbox: true -frontend_api: [jobs:run, users:read] +frontend_api: [jobs:run] ``` A file with a `sandbox` key states both settings: `sandbox: false` turns isolation off, and a missing `frontend_api` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing `sandbox: true` does not unsandbox it. `frontend_api` needs `sandbox: true`; the push fails otherwise. diff --git a/system_prompts/base/raw-app.md b/system_prompts/base/raw-app.md index 1323e4228a..dc70d0b94d 100644 --- a/system_prompts/base/raw-app.md +++ b/system_prompts/base/raw-app.md @@ -251,7 +251,7 @@ An app's custom URL is not in `raw_app.yaml`: each workspace has its own file ne ## Sandbox isolation and frontend API access -New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `users:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them. Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. @@ -262,7 +262,7 @@ In `raw_app.yaml`: ```yaml sandbox: true -frontend_api: [jobs:run, users:read] +frontend_api: [jobs:run] ``` A file with a `sandbox` key states both settings: `sandbox: false` turns isolation off, and a missing `frontend_api` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing `sandbox: true` does not unsandbox it. `frontend_api` needs `sandbox: true`; the push fails otherwise. From f827ba05667e3ca5bcd3bc89dac7f51b85dd32b3 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 15 Oct 2026 18:19:23 +0200 Subject: [PATCH 03/20] feat: resolve canceled jobs and re-run them in limited batches (#11797) * feat: resolve canceled jobs and batch re-run them in limited batches Co-Authored-By: Claude Opus 5.5 * fix: offer the re-run batch limit only for failed or canceled filters Co-Authored-By: Claude Opus 5.5 * fix: label an unresolved canceled run as canceled in its status badge Co-Authored-By: Claude Opus 5.5 * fix: tell the user that sources a batch could not re-run block the next batch Co-Authored-By: Claude Opus 5.5 * feat: warn when a re-run batch includes resolved runs and offer to hide them Co-Authored-By: Claude Opus 5.5 * feat: say in the re-run confirmation that failed or canceled sources get resolved Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...ec0859463b1c153950f894a830a4b5ec33fcc.json | 28 ----- ...2ffe92d3cd13915be8a07f9364a14a01e549f.json | 26 ++++ ...603843edce422c522c035b81b88cb169b88b1.json | 28 +++++ backend/tests/batch_rerun.rs | 64 +++++++++- backend/windmill-api/openapi.yaml | 31 +++-- backend/windmill-api/src/jobs.rs | 71 ++++++++++- .../src/mcp/auto_generated_endpoints.rs | 2 +- frontend/src/lib/components/JobStatus.svelte | 4 +- frontend/src/lib/components/RunsPage.svelte | 116 +++++++++++++++--- .../components/runs/JobDetailHeader.svelte | 7 +- .../lib/components/runs/JobStatusIcon.svelte | 7 +- .../components/runs/rerunResolution.svelte.ts | 6 +- .../src/lib/components/runs/runsFilter.ts | 4 +- frontend/src/lib/mcpEndpointTools.ts | 2 +- frontend/src/lib/utils.test.ts | 11 +- frontend/src/lib/utils.ts | 8 +- 16 files changed, 330 insertions(+), 85 deletions(-) delete mode 100644 backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json create mode 100644 backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json create mode 100644 backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json diff --git a/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json b/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json deleted file mode 100644 index 9cdddc5121..0000000000 --- a/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, COALESCE($5, $7), false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = ANY($1)\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status = 'failure'\n -- Resolution is a top-level triage state: a step resolved on its own\n -- would render orange inside a flow whose status is still red.\n AND j.flow_step_id IS NULL\n -- A supersession claim has to be proven, not trusted: a later success of the\n -- same identified runnable, itself visible to the caller. An unproven claim\n -- resolves nothing, so the caller learns it was rejected instead of having\n -- the fiction recorded as provenance.\n AND ($6::UUID IS NULL OR EXISTS (\n SELECT 1 FROM v2_job_completed sc\n JOIN v2_job sj ON sj.id = sc.id\n WHERE sc.id = $6\n AND sc.workspace_id = $2\n -- Tag scope is a read restriction enforced outside RLS, so it has\n -- to bind the evidence as well: otherwise the result reveals\n -- whether an out-of-scope run succeeded.\n AND ($3::TEXT[] IS NULL OR sj.tag = ANY($3))\n AND sc.status = 'success'\n AND sc.completed_at >= c.completed_at\n AND (j.runnable_id IS NOT NULL OR j.runnable_path IS NOT NULL)\n AND sj.runnable_id IS NOT DISTINCT FROM j.runnable_id\n AND sj.runnable_path IS NOT DISTINCT FROM j.runnable_path\n ))\n ON CONFLICT (job_id) DO UPDATE SET\n resolved_at = now(),\n -- Both COALESCEd: `resolution_attribution` returns NULLs outside EE and once the\n -- licence lapses, and bulk selections routinely include already-resolved rows,\n -- so overwriting would erase metadata recorded while it was valid. Clear either\n -- by unresolving first.\n resolved_by = COALESCE($4, job_resolution.resolved_by),\n -- A person's explanation replaces what was there; machine provenance only fills\n -- a blank, so re-running an already-explained failure never erases their words.\n note = COALESCE($5, job_resolution.note, $7),\n -- A human taking over an automatic resolution makes it no longer automatic.\n automatic = false\n RETURNING job_id", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "job_id", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [ - "UuidArray", - "Text", - "TextArray", - "Varchar", - "Text", - "Uuid", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc" -} diff --git a/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json b/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json new file mode 100644 index 0000000000..224e1f62e7 --- /dev/null +++ b/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, $5, false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = $1\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status IN ('failure', 'canceled')\n AND j.flow_step_id IS NULL\n ON CONFLICT (job_id) DO NOTHING\n RETURNING job_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "TextArray", + "Varchar", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f" +} diff --git a/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json b/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json new file mode 100644 index 0000000000..c1ea457a72 --- /dev/null +++ b/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, COALESCE($5, $7), false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = ANY($1)\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status IN ('failure', 'canceled')\n -- Resolution is a top-level triage state: a step resolved on its own\n -- would render orange inside a flow whose status is still red.\n AND j.flow_step_id IS NULL\n -- A supersession claim has to be proven, not trusted: a later success of the\n -- same identified runnable, itself visible to the caller. An unproven claim\n -- resolves nothing, so the caller learns it was rejected instead of having\n -- the fiction recorded as provenance.\n AND ($6::UUID IS NULL OR EXISTS (\n SELECT 1 FROM v2_job_completed sc\n JOIN v2_job sj ON sj.id = sc.id\n WHERE sc.id = $6\n AND sc.workspace_id = $2\n -- Tag scope is a read restriction enforced outside RLS, so it has\n -- to bind the evidence as well: otherwise the result reveals\n -- whether an out-of-scope run succeeded.\n AND ($3::TEXT[] IS NULL OR sj.tag = ANY($3))\n AND sc.status = 'success'\n AND sc.completed_at >= c.completed_at\n AND (j.runnable_id IS NOT NULL OR j.runnable_path IS NOT NULL)\n AND sj.runnable_id IS NOT DISTINCT FROM j.runnable_id\n AND sj.runnable_path IS NOT DISTINCT FROM j.runnable_path\n ))\n ON CONFLICT (job_id) DO UPDATE SET\n resolved_at = now(),\n -- Both COALESCEd: `resolution_attribution` returns NULLs outside EE and once the\n -- licence lapses, and bulk selections routinely include already-resolved rows,\n -- so overwriting would erase metadata recorded while it was valid. Clear either\n -- by unresolving first.\n resolved_by = COALESCE($4, job_resolution.resolved_by),\n -- A person's explanation replaces what was there; machine provenance only fills\n -- a blank, so re-running an already-explained failure never erases their words.\n note = COALESCE($5, job_resolution.note, $7),\n -- A human taking over an automatic resolution makes it no longer automatic.\n automatic = false\n RETURNING job_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "UuidArray", + "Text", + "TextArray", + "Varchar", + "Text", + "Uuid", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1" +} diff --git a/backend/tests/batch_rerun.rs b/backend/tests/batch_rerun.rs index 58cf27db87..9663eea73b 100644 --- a/backend/tests/batch_rerun.rs +++ b/backend/tests/batch_rerun.rs @@ -29,12 +29,21 @@ const FLOW_VERSION: i64 = 2222222222; /// Mark a queued job as completed with success — needed so it's eligible for /// `list_selected_job_groups` / `batch_rerun_jobs` (both join `v2_job_completed`). async fn complete_job(db: &Pool, job_id: Uuid) -> anyhow::Result<()> { + complete_job_with_status(db, job_id, "success").await +} + +async fn complete_job_with_status( + db: &Pool, + job_id: Uuid, + status: &str, +) -> anyhow::Result<()> { sqlx::query( "INSERT INTO v2_job_completed (workspace_id, id, result, status, duration_ms, started_at, completed_at) - VALUES ($1, $2, '{}'::jsonb, 'success', 0, now(), now())", + VALUES ($1, $2, '{}'::jsonb, $3::job_status, 0, now(), now())", ) .bind(WORKSPACE) .bind(job_id) + .bind(status) .execute(db) .await?; Ok(()) @@ -660,3 +669,56 @@ async fn batch_rerun_denies_invisible_source_job(db: Pool) -> anyhow:: assert_eq!(pushed, 0); Ok(()) } + +/// Re-running a failed or canceled job resolves it, pointing at the re-run, which is what lets +/// "hide resolved" exclude it from the next batch. A success has nothing to resolve. +#[sqlx::test(fixtures("base", "batch_rerun"))] +async fn batch_rerun_resolves_failed_and_canceled_sources( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let client = windmill_api_client::create_client( + &format!("http://localhost:{}", server.addr.port()), + "SECRET_TOKEN".to_string(), + ); + + let mut sources = vec![]; + for status in ["success", "failure", "canceled"] { + let id = RunJob::from(script_payload()) + .arg("name".to_string(), json!(status)) + .push(&db) + .await; + complete_job_with_status(&db, id, status).await?; + sources.push(id); + } + + let results = batch_rerun( + &client, + json!({ + "job_ids": sources, + "script_options_by_path": {}, + "flow_options_by_path": {}, + }), + ) + .await?; + assert!(results.iter().all(|r| r.is_ok()), "{results:?}"); + + let resolved: Vec<(String, String)> = sqlx::query_as( + "SELECT o.args->>'name', n.args->>'name' + FROM job_resolution r + JOIN v2_job o ON o.id = r.job_id + JOIN v2_job n ON r.note = 'Re-run as ' || n.id + ORDER BY 1", + ) + .fetch_all(&db) + .await?; + assert_eq!( + resolved, + vec![ + ("canceled".to_string(), "canceled".to_string()), + ("failure".to_string(), "failure".to_string()), + ] + ); + Ok(()) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index e9b5732f0a..d56115d9b0 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -16117,6 +16117,9 @@ paths: /w/{workspace}/jobs/run/batch_rerun_jobs: post: summary: re-run multiple jobs + description: >- + Re-runs each job and marks every failed or canceled original that was re-run as + resolved, with the new job's id in its note. Operators re-run without resolving. operationId: batchReRunJobs tags: - job @@ -16878,6 +16881,7 @@ paths: - job parameters: - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/OrderDesc" - $ref: "#/components/parameters/CreatedBy" - $ref: "#/components/parameters/Label" - $ref: "#/components/parameters/Worker" @@ -16910,8 +16914,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -17222,8 +17226,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -17409,8 +17413,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -18268,11 +18272,12 @@ paths: /w/{workspace}/jobs/completed/resolve: post: - summary: mark failed jobs as resolved + summary: mark failed or canceled jobs as resolved description: >- - Marks failed jobs as handled so triage surfaces stop showing them as failures. - The job status itself is unchanged. Returns the ids actually resolved: ids that - are not visible to the caller or did not fail are silently skipped. + Marks failed or canceled jobs as handled so triage surfaces stop showing them as + unhandled. The job status itself is unchanged. Returns the ids actually resolved: ids + that are not visible to the caller or neither failed nor were canceled are silently + skipped. operationId: resolveCompletedJobs tags: - job @@ -26130,8 +26135,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -31052,7 +31057,7 @@ components: type: boolean resolved: type: boolean - description: whether this failure has been marked as handled + description: whether this failed or canceled run has been marked as handled resolved_by: type: string description: >- diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index b939ba017a..cb8d47df4f 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -7058,6 +7058,7 @@ async fn batch_rerun_handle_job( ) .await; if let Ok((uuid, _, _, _)) = result { + resolve_batch_rerun_source(authed, user_db, w_id, job.id, uuid).await; return Ok(uuid.to_string()); } } @@ -7091,6 +7092,7 @@ async fn batch_rerun_handle_job( .map(|r| r.0) }; if let Ok(uuid) = result { + resolve_batch_rerun_source(authed, user_db, w_id, job.id, uuid).await; return Ok(uuid.to_string()); } } @@ -7101,6 +7103,67 @@ async fn batch_rerun_handle_job( )) } +/// Marks a failed or canceled source of a batch re-run as handled, with the re-run as its note. +/// This is the only moment the link exists (the re-run is pushed with no back-pointer), and it +/// is what lets "hide resolved" exclude already re-run jobs from the next batch. Never fails the +/// re-run, which is already queued: a source that cannot be resolved is logged and left as is. +async fn resolve_batch_rerun_source( + authed: &ApiAuthed, + user_db: &UserDB, + w_id: &str, + source: Uuid, + rerun: Uuid, +) { + if authed.is_operator { + return; + } + let result: error::Result<()> = async { + let mut tx = user_db.clone().begin(authed).await?; + let tags = get_scope_tags(authed); + let (resolved_by, _) = resolution_attribution(authed, None); + // Same authorization and eligibility as `resolve_completed_jobs`. DO NOTHING keeps a + // resolution someone already explained. + let resolved = sqlx::query_scalar!( + "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic) + SELECT c.id, c.workspace_id, $4, $5, false + FROM v2_job_completed c + JOIN v2_job j ON j.id = c.id + WHERE c.id = $1 + AND c.workspace_id = $2 + AND ($3::TEXT[] IS NULL OR j.tag = ANY($3)) + AND c.status IN ('failure', 'canceled') + AND j.flow_step_id IS NULL + ON CONFLICT (job_id) DO NOTHING + RETURNING job_id", + source, + w_id, + tags.as_ref().map(|v| v.as_slice()) as Option<&[&str]>, + resolved_by, + format!("Re-run as {rerun}"), + ) + .fetch_optional(&mut *tx) + .await?; + if resolved.is_some() { + audit_log( + &mut *tx, + authed, + "jobs.resolve", + ActionKind::Update, + w_id, + Some(&source.to_string()), + None, + ) + .await?; + } + tx.commit().await?; + Ok(()) + } + .await; + if let Err(e) = result { + tracing::error!("Could not resolve job {source} after re-running it as {rerun}: {e}"); + } +} + pub async fn run_flow_by_path( authed: ApiAuthed, Extension(db): Extension, @@ -12531,8 +12594,8 @@ fn check_resolution_request( Ok(()) } -/// Marks failed jobs as handled. Returns the ids actually affected: an id that is not -/// visible to the caller, carries an out-of-scope tag, or did not fail is silently +/// Marks failed or canceled jobs as handled. Returns the ids actually affected: an id that is +/// not visible to the caller, carries an out-of-scope tag, or did not fail nor get canceled is silently /// absent rather than an error, so a bulk selection never fails as a whole. async fn resolve_completed_jobs( authed: ApiAuthed, @@ -12547,7 +12610,7 @@ async fn resolve_completed_jobs( let system_note = req.superseded_by.map(|_| SUPERSEDED_NOTE); // The join on v2_job is what authorizes this write: v2_job_completed has RLS // disabled, so v2_job's policies are the only thing scoping rows to the caller. - // `status = 'failure'` keeps the invariant that only a failure can be resolved. + // Only a failed or canceled run can be resolved: a success has nothing to handle. let resolved = sqlx::query_scalar!( "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic) SELECT c.id, c.workspace_id, $4, COALESCE($5, $7), false @@ -12556,7 +12619,7 @@ async fn resolve_completed_jobs( WHERE c.id = ANY($1) AND c.workspace_id = $2 AND ($3::TEXT[] IS NULL OR j.tag = ANY($3)) - AND c.status = 'failure' + AND c.status IN ('failure', 'canceled') -- Resolution is a top-level triage state: a step resolved on its own -- would render orange inside a flow whose status is still red. AND j.flow_step_id IS NULL diff --git a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs index dd3c83a08d..8ff3e9f5c2 100644 --- a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs +++ b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs @@ -1846,7 +1846,7 @@ is, a different one moves it there and archives the old path"), }, "resolved": { "type": "boolean", - "description": "filter on whether a failure has been marked as handled. true keeps only resolved failures, false hides them" + "description": "filter on whether a failed or canceled run has been marked as handled. true keeps only resolved runs, false hides them" }, "is_flow_step": { "type": "boolean", diff --git a/frontend/src/lib/components/JobStatus.svelte b/frontend/src/lib/components/JobStatus.svelte index 7945081482..5e79303371 100644 --- a/frontend/src/lib/components/JobStatus.svelte +++ b/frontend/src/lib/components/JobStatus.svelte @@ -34,7 +34,7 @@ - Failed after {msToReadableTime(job.duration_ms)}, resolved{job.resolved_automatically + {job.canceled ? 'Canceled' : 'Failed'} after {msToReadableTime(job.duration_ms)}, resolved{job.resolved_automatically ? ' automatically' : job.resolved_by ? ` by ${job.resolved_by}` @@ -49,7 +49,7 @@ {:else if job && 'success' in job} - Failed after {msToReadableTime(job.duration_ms)} + {job.canceled ? 'Canceled' : 'Failed'} after {msToReadableTime(job.duration_ms)} {#if job.self_wait_time_ms || job.aggregate_wait_time_ms} void type?: ConfirmationModal['$$prop_def']['type'] @@ -437,6 +438,7 @@ async function reRunJobs(jobIdsToReRun: string[], batchReRunOptions: BatchReRunOptions) { if (!$operatingWorkspace) return + const batching = filterMatchedIds !== undefined if (askingForConfirmation) { askingForConfirmation.loading = true @@ -486,7 +488,11 @@ } if (reRanUuids.length !== jobIdsToReRun.length) { sendUserToast( - `Failed to re-run ${jobIdsToReRun.length - reRanUuids.length} jobs. Check console for details`, + `Failed to re-run ${jobIdsToReRun.length - reRanUuids.length} jobs. Check console for details` + + // Only a re-run resolves its source, so these stay first in line. + (batching + ? '. They stay unresolved and the next batch will try them again: resolve them to skip them' + : ''), true ) // We do not get explicit error from backend if the job script don't exist @@ -509,13 +515,31 @@ jobsLoader?.loadJobs(true, true) } + // Every failed or canceled job "Re-run all jobs matching filters" found, oldest first, so a + // batch limit takes the oldest ones. Re-running resolves them, so under "Hide resolved runs" + // the next click picks up where the previous batch stopped. + let filterMatchedIds: string[] | undefined = $state() + let rerunLimit: number | undefined = $state() + // The pane closes from several places, the table included; a stale match list would then + // offer its limit over a selection it no longer describes. + $effect(() => { + if (!batchRerunOptionsIsOpen) untrack(() => (filterMatchedIds = undefined)) + }) + + function setRerunLimit(limit: number | undefined) { + if (!filterMatchedIds) return + rerunLimit = limit && limit > 0 ? limit : undefined + selectedIds = filterMatchedIds.slice(0, rerunLimit ?? filterMatchedIds.length) + } + async function onRerunAllJobsMatchingFilters() { const selectedFilters = getSelectedFilters() selectedIds = [] const loadingToast = sendUserToast('Loading job ids', 'info') - if (filters.val.job_kinds !== 'runs') { + // Selecting "runs" deletes the key, since it is the default. + if ((filters.val.job_kinds ?? 'runs') !== 'runs') { sendUserToast('Batch re-run is only supported for scripts and flows', true) loadingToast.destroy() return @@ -524,11 +548,21 @@ // workspace. started_at >= minTs implies completed_at >= minTs, so completedAfter adds a // lossless indexed lower bound ((workspace_id, completed_at DESC)); started_at stays the // exact recheck. (completedBefore is omitted: it would drop jobs that finish after maxTs.) - selectedIds = await JobService.listFilteredJobsUuids({ + const ids = await JobService.listFilteredJobsUuids({ ...selectedFilters, completedAfter: selectedFilters.startedAfter, - jobKinds: 'script,flow' + orderDesc: false }) + // Batching needs both halves of its promise: only failed or canceled sources are resolved + // by a re-run, and only a status filter keeps the queue out of the lookup, whose union + // drops the ordering. Anything else re-runs every match, as one batch. + if (selectedFilters.status === 'failure' || selectedFilters.status === 'canceled') { + filterMatchedIds = ids + setRerunLimit(rerunLimit) + } else { + filterMatchedIds = undefined + selectedIds = ids + } loadingToast.destroy() batchRerunOptionsIsOpen = true } @@ -538,6 +572,10 @@ askingForConfirmation = { title: `Confirm re-running the selected jobs`, confirmBtnText: `Re-run ${jobIdsToReRun.length} jobs`, + // The server skips resolution for operators, who cannot resolve. + description: operatingUser.current?.operator + ? undefined + : "Failed or canceled jobs among them will be marked resolved, with the new run's id as the note.", type: 'reload', onConfirm: async () => { await reRunJobs(jobIdsToReRun, batchReRunOptions) @@ -867,6 +905,9 @@ askingForConfirmation = undefined }} > + {#if askingForConfirmation?.description} +

    {askingForConfirmation.description}

    + {/if} {#if askingForConfirmation?.preContent}
    {askingForConfirmation.preContent}
    { manualSelectionMode = 'rerun' selectedIds = [] + filterMatchedIds = undefined batchRerunOptionsIsOpen = true } }, @@ -1128,7 +1170,7 @@ ? [ { // Operators are rejected by the endpoint, so offering it would only 403. - displayName: 'Resolve failed jobs', + displayName: 'Resolve failed or canceled jobs', action: () => ( (manualSelectionMode = 'resolve'), (selectedIds = []), @@ -1210,7 +1252,7 @@ class="rounded-md bg-surface-tertiary border absolute inset-0 mb-4 flex flex-col items-center justify-center gap-3 p-4" >

    - Resolving keeps the run a failure but stops it showing as one in the runs list. + Resolving keeps the run's status but marks it as handled in the runs list.

    ((batchRerunOptionsIsOpen = false), (manualSelectionMode = undefined))} - onConfirm={async (options) => { - await onReRunSelectedJobs(options) - }} - /> - {/await} +
    + {#if filterMatchedIds} +
    +
    + {filterMatchedIds.length} jobs match the filters, re-run at most + rerunLimit?.toString() ?? '', + (v) => setRerunLimit(v ? parseInt(v.toString()) : undefined) + } + /> +
    + {#if filters.val.resolved === 'unresolved'} + + Oldest first. Re-run jobs are marked resolved, so the next batch starts where this one + stops. + + {:else} +
    + + + Resolved runs are included, so the next batch will pick these same jobs again. + + +
    + {/if} +
    + {/if} +
    + {#await import('$lib/components/runs/BatchReRunOptionsPane.svelte') then BatchReRunOptionsPane} + ((batchRerunOptionsIsOpen = false), (manualSelectionMode = undefined))} + onConfirm={async (options) => { + await onReRunSelectedJobs(options) + }} + /> + {/await} +
    +
    {/snippet} {#snippet jobPreview(pending?: Snippet)} diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index 9a1aed6145..5783deaf53 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -514,7 +514,7 @@ variant="subtle" disabled={togglingResolution} onClick={() => setResolution(false)} - title="Show this run as a failure again" + title="Show this run as unhandled again" > Unresolve @@ -525,7 +525,7 @@ size="xs2" variant="subtle" nonCaptureEvent - title="Mark this failure as handled" + title="Mark this run as handled" > Mark resolved @@ -533,8 +533,7 @@ {#snippet content({ close })}

    - Resolving keeps the run a failure but stops it showing as one in the runs - list. + Resolving keeps the run's status but marks it as handled in the runs list.

    {:else if job.canceled && 'success' in job} - + {:else if 'success' in job && job.success} diff --git a/frontend/src/lib/components/runs/rerunResolution.svelte.ts b/frontend/src/lib/components/runs/rerunResolution.svelte.ts index 87911d6c8d..f57d7400c8 100644 --- a/frontend/src/lib/components/runs/rerunResolution.svelte.ts +++ b/frontend/src/lib/components/runs/rerunResolution.svelte.ts @@ -37,7 +37,7 @@ export function offerToResolveOriginal(origin: PendingRerun, onResolved?: () => 'success', [ { - label: 'Resolve the original failure', + label: 'Resolve the original run', callback: async () => { const affected = await JobService.resolveCompletedJobs({ workspace: origin.workspace, @@ -50,10 +50,10 @@ export function offerToResolveOriginal(origin: PendingRerun, onResolved?: () => } }) if (affected.length === 0) { - sendUserToast('Could not resolve the original failure', true) + sendUserToast('Could not resolve the original run', true) return } - sendUserToast('Original failure resolved') + sendUserToast('Original run resolved') onResolved?.() } } diff --git a/frontend/src/lib/components/runs/runsFilter.ts b/frontend/src/lib/components/runs/runsFilter.ts index 3ff8a5e54b..cef8cca6e9 100644 --- a/frontend/src/lib/components/runs/runsFilter.ts +++ b/frontend/src/lib/components/runs/runsFilter.ts @@ -186,7 +186,7 @@ export function buildRunsFilterSearchbarSchema({ ], label: 'Resolution', icon: Wrench, - description: 'Filter by whether a failure has been marked as handled' + description: 'Filter by whether a failed or canceled run has been marked as handled' }, job_trigger_kind: { type: 'oneof' as const, @@ -254,7 +254,7 @@ export const buildRunsFilterPresets = ({ { name: 'Hide schedules', value: 'job_trigger_kind:\\ !schedule' }, { name: 'Hide future jobs', value: 'show_future_jobs:\\ false' }, { name: 'Show skipped', value: 'show_skipped:\\ true' }, - { name: 'Hide resolved failures', value: 'resolved:\\ unresolved' }, + { name: 'Hide resolved runs', value: 'resolved:\\ unresolved' }, ...(isSuperAdminOrDevops && isAdminsWorkspace ? [{ name: 'All workspaces', value: 'all_workspaces:\\ true' }] : []) diff --git a/frontend/src/lib/mcpEndpointTools.ts b/frontend/src/lib/mcpEndpointTools.ts index b3b70cfaa2..e53beeb53b 100644 --- a/frontend/src/lib/mcpEndpointTools.ts +++ b/frontend/src/lib/mcpEndpointTools.ts @@ -1853,7 +1853,7 @@ export const mcpEndpointTools: EndpointTool[] = [ }, "resolved": { "type": "boolean", - "description": "filter on whether a failure has been marked as handled. true keeps only resolved failures, false hides them" + "description": "filter on whether a failed or canceled run has been marked as handled. true keeps only resolved runs, false hides them" }, "is_flow_step": { "type": "boolean", diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts index a37238f91c..07216d341f 100644 --- a/frontend/src/lib/utils.test.ts +++ b/frontend/src/lib/utils.test.ts @@ -13,17 +13,16 @@ import { apiErrorMessage } from './utils' -// Mirrors the backend invariant that only `status = 'failure'` rows can carry a -// resolution; loosening this to `!success` would offer the action on queued and -// canceled runs the API then silently skips. +// Mirrors the backend invariant that only failed or canceled rows can carry a resolution; +// offering the action anywhere else would send ids the API then silently skips. describe('isJobResolvable', () => { const completed = (o: object) => ({ type: 'CompletedJob', ...o }) as any - it('accepts a plain failure', () => { + it('accepts a plain failure and a cancellation', () => { expect(isJobResolvable(completed({ success: false, canceled: false }))).toBe(true) + expect(isJobResolvable(completed({ success: false, canceled: true }))).toBe(true) }) - it('rejects success, cancellation, flow steps and jobs still queued', () => { + it('rejects success, flow steps and jobs still queued', () => { expect(isJobResolvable(completed({ success: true, canceled: false }))).toBe(false) - expect(isJobResolvable(completed({ success: false, canceled: true }))).toBe(false) // a step resolved alone would show orange inside a flow that is still red expect( isJobResolvable(completed({ success: false, canceled: false, is_flow_step: true })) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 8540b964e8..13ae454c92 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -83,13 +83,13 @@ export function isJobReRunnable(j: Job): boolean { return (j.job_kind === 'script' || j.job_kind === 'flow') && j.parent_job === undefined } -// Only a top-level failure can carry a resolution: cancellations and skipped steps are not -// failures, and a flow step resolved on its own would render orange inside a flow whose status -// is still red. The resolve endpoint enforces the same three conditions. +// Only a top-level failed or canceled run can carry a resolution: successes and skipped steps +// have nothing to handle, and a flow step resolved on its own would render orange inside a flow +// whose status is still red. The resolve endpoint enforces the same conditions. // Runs obscured from another workspace stand in with `id: '-'`; they look like failures but // address nothing, and one reaching the endpoint fails the whole batch on UUID parsing. export function isJobResolvable(j: Job): j is CompletedJob { - return j.type === 'CompletedJob' && !j.success && !j.canceled && !j.is_flow_step && j.id !== '-' + return j.type === 'CompletedJob' && !j.success && !j.is_flow_step && j.id !== '-' } // Mirror the caps enforced by /jobs/completed/resolve, so the UI can chunk and validate From a9aa2b8229da0d54ed68eb40e4426e6983ff631e Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 15 Oct 2026 18:51:11 +0200 Subject: [PATCH 04/20] feat: share AI sessions read-only by link, optionally public (#11799) * feat: share AI sessions read-only by link, optionally public Co-Authored-By: Claude Opus 5.5 * fix: render shared session snapshots from an allowlist, without mermaid or remote images Co-Authored-By: Claude Opus 5.5 * style: make the session share button icon-only Co-Authored-By: Claude Opus 5.5 * fix: safe reasoning links, artifact list and full-load exits on shared sessions Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...42162e96499987b17a34bde7bc32d54e6260e.json | 55 +++ ...0a57fd10fc5b32f4e68ab7a217d85264623b6.json | 47 +++ ...95309a55635083a541745552c397a36ac08c4.json | 54 +++ ...a133ea859f243f518197cde803ef0c86eab33.json | 25 ++ ...3a863c3f265ea043cc653f9732bb87860b8d9.json | 65 ++++ .../20261015155831_ai_shared_session.down.sql | 1 + .../20261015155831_ai_shared_session.up.sql | 30 ++ backend/summarized_schema.txt | 1 + backend/tests/ai_shared_sessions.rs | 120 ++++++ backend/windmill-api/openapi.yaml | 187 +++++++++ backend/windmill-api/src/ai.rs | 4 + .../windmill-api/src/ai_shared_sessions.rs | 368 ++++++++++++++++++ backend/windmill-api/src/lib.rs | 5 + .../copilot/chat/AssistantMessage.svelte | 3 +- .../components/copilot/chat/chatViewHost.ts | 3 + .../chat/readOnlyChatViewHost.svelte.ts | 85 ++++ .../copilot/chat/script/CodeDisplay.svelte | 4 +- .../sessions/SessionShareButton.svelte | 231 +++++++++++ .../components/sessions/SessionWrapper.svelte | 8 + .../sessions/SharedSessionTranscript.svelte | 121 ++++++ .../sessions/sessionSharing.test.ts | 59 +++ .../lib/components/sessions/sessionSharing.ts | 188 +++++++++ .../[workspace]/[id]/+page.svelte | 157 ++++++++ 23 files changed, 1819 insertions(+), 2 deletions(-) create mode 100644 backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json create mode 100644 backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json create mode 100644 backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json create mode 100644 backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json create mode 100644 backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json create mode 100644 backend/migrations/20261015155831_ai_shared_session.down.sql create mode 100644 backend/migrations/20261015155831_ai_shared_session.up.sql create mode 100644 backend/tests/ai_shared_sessions.rs create mode 100644 backend/windmill-api/src/ai_shared_sessions.rs create mode 100644 frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts create mode 100644 frontend/src/lib/components/sessions/SessionShareButton.svelte create mode 100644 frontend/src/lib/components/sessions/SharedSessionTranscript.svelte create mode 100644 frontend/src/lib/components/sessions/sessionSharing.test.ts create mode 100644 frontend/src/lib/components/sessions/sessionSharing.ts create mode 100644 frontend/src/routes/(styled)/shared_sessions/[workspace]/[id]/+page.svelte diff --git a/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json b/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json new file mode 100644 index 0000000000..6af78adde7 --- /dev/null +++ b/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json @@ -0,0 +1,55 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE ai_shared_session SET is_public = $4\n WHERE workspace_id = $1 AND id = $2 AND email = $3\n RETURNING id, name, is_public, message_count, created_by, shared_at", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Text", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e" +} diff --git a/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json b/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json new file mode 100644 index 0000000000..7e4de24f7e --- /dev/null +++ b/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_shared_session\n (workspace_id, session_id, email, created_by, name, is_public, message_count, snapshot)\n VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), $7, $8)\n ON CONFLICT (workspace_id, email, session_id) DO UPDATE\n SET created_by = EXCLUDED.created_by,\n name = EXCLUDED.name,\n is_public = COALESCE($6, ai_shared_session.is_public),\n message_count = EXCLUDED.message_count,\n snapshot = EXCLUDED.snapshot,\n shared_at = now()\n RETURNING id, is_public, shared_at, (xmax = 0) AS \"inserted!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "shared_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "inserted!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Int4", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + null + ] + }, + "hash": "8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6" +} diff --git a/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json b/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json new file mode 100644 index 0000000000..e66cfa2881 --- /dev/null +++ b/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json @@ -0,0 +1,54 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, name, is_public, message_count, created_by, shared_at FROM ai_shared_session\n WHERE workspace_id = $1 AND email = $2 AND session_id = $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4" +} diff --git a/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json b/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json new file mode 100644 index 0000000000..73fbc88289 --- /dev/null +++ b/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM ai_shared_session\n WHERE workspace_id = $1 AND id = $2 AND (email = $3 OR $4::bool)\n RETURNING name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Text", + "Bool" + ] + }, + "nullable": [ + false + ] + }, + "hash": "cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33" +} diff --git a/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json b/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json new file mode 100644 index 0000000000..94b5ba8f10 --- /dev/null +++ b/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, email, name, is_public, message_count, created_by, snapshot, shared_at\n FROM ai_shared_session\n WHERE workspace_id = $1 AND id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "snapshot", + "type_info": "Text" + }, + { + "ordinal": 7, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9" +} diff --git a/backend/migrations/20261015155831_ai_shared_session.down.sql b/backend/migrations/20261015155831_ai_shared_session.down.sql new file mode 100644 index 0000000000..bf6a32d4de --- /dev/null +++ b/backend/migrations/20261015155831_ai_shared_session.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ai_shared_session; diff --git a/backend/migrations/20261015155831_ai_shared_session.up.sql b/backend/migrations/20261015155831_ai_shared_session.up.sql new file mode 100644 index 0000000000..37e8939c3b --- /dev/null +++ b/backend/migrations/20261015155831_ai_shared_session.up.sql @@ -0,0 +1,30 @@ +-- A read-only snapshot of an AI session transcript that its author shared by link. Sessions +-- otherwise live only in the author's browser; this row exists only while the share does. +-- Non-public shares are readable by members of the workspace, public ones by anyone with the +-- link, which is why `id` is a random UUID and never derived from the session. +CREATE TABLE ai_shared_session ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + workspace_id VARCHAR(50) NOT NULL REFERENCES workspace(id) ON DELETE CASCADE, + -- The browser-side session id. Unique per author so sharing the same session again + -- moves its one link forward rather than minting a second one. + session_id VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + created_by VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + is_public BOOLEAN NOT NULL DEFAULT false, + message_count INTEGER NOT NULL, + -- JSON kept as text: jsonb refuses the \u0000 escape a transcript can carry. + snapshot TEXT NOT NULL, + shared_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (workspace_id, email, session_id) +); + +GRANT ALL ON ai_shared_session TO windmill_admin; +GRANT ALL ON ai_shared_session TO windmill_user; + +-- The handlers go through the raw pool and scope every query to the workspace themselves. +-- An admin-only policy is the backstop for a future query that reaches this table through +-- UserDB. +ALTER TABLE ai_shared_session ENABLE ROW LEVEL SECURITY; + +CREATE POLICY admin_policy ON ai_shared_session FOR ALL TO windmill_admin USING (true); diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 471a7251b3..43b3d591ea 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -41,6 +41,7 @@ ai_agent_memory: workspace_id(char), conversation_id(uuid), step_id(char), messa ai_free_token_daily_usage: day(date), cost_nanos(bigint), updated_at(ts) ai_free_token_usage: email(char), cost_nanos(bigint), updated_at(ts) ai_shared_artifact: id(uuid), workspace_id(char), artifact_id(char), email(char), created_by(char), name(char), kind(char), version(int), content(text), shared_at(ts) +ai_shared_session: id(uuid), workspace_id(char), session_id(char), email(char), created_by(char), name(char), is_public(bool), message_count(int), snapshot(text), shared_at(ts) FK: (workspace_id) -> workspace(id) ai_token_usage: workspace_id(char), day(date), email(char), provider(char), model(char), session_id(char), input_tokens(bigint), cache_read_tokens(bigint), cache_write_tokens(bigint), output_tokens(bigint), reported_cost_nano_usd(bigint), requests(bigint), updated_at(ts) FK: (workspace_id) -> workspace(id) diff --git a/backend/tests/ai_shared_sessions.rs b/backend/tests/ai_shared_sessions.rs new file mode 100644 index 0000000000..75334a5440 --- /dev/null +++ b/backend/tests/ai_shared_sessions.rs @@ -0,0 +1,120 @@ +//! Shared AI sessions: a private share is served only to members of its workspace, a public +//! one to anyone holding the link, and only its author decides which it is. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const ADMIN: &str = "Bearer SECRET_TOKEN"; +const MEMBER: &str = "Bearer SECRET_TOKEN_2"; +const OTHER_MEMBER: &str = "Bearer SECRET_TOKEN_3"; +const OUTSIDER: &str = "Bearer OUTSIDER_TOKEN"; + +#[sqlx::test(fixtures("base"))] +async fn private_share_is_for_members_and_public_share_for_anyone( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('outsider@windmill.dev', 'not-a-real-hash', 'password', false, true, 'Outsider'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('OUTSIDER_TOKEN'::bytea), 'hex'), 'OUTSIDER_T', 'OUTSIDER_TOKEN', + 'outsider@windmill.dev', 'outsider token', false);", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let authed = format!("http://localhost:{port}/api/w/test-workspace/ai/shared_sessions"); + let get = |id: &str| { + format!("http://localhost:{port}/api/w/test-workspace/ai_u/shared_sessions/get/{id}") + }; + let client = reqwest::Client::new(); + + let resp = client + .post(format!("{authed}/share")) + .header("Authorization", MEMBER) + .json(&json!({ + "session_id": "session-1", + "name": "Debugging", + "message_count": 1, + "snapshot": { "messages": [{ "role": "user", "content": "hi" }], "artifacts": [] }, + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let share: Value = resp.json().await?; + assert_eq!(share["is_public"], false, "a new share must start private"); + let id = share["id"].as_str().unwrap().to_string(); + + let status = |token: Option<&'static str>| { + let mut req = client.get(get(&id)); + if let Some(token) = token { + req = req.header("Authorization", token); + } + async move { anyhow::Ok(req.send().await?.status().as_u16()) } + }; + + assert_eq!(status(Some(OTHER_MEMBER)).await?, 200); + assert_eq!( + status(None).await?, + 401, + "a private share was served anonymously" + ); + assert_eq!( + status(Some(OUTSIDER)).await?, + 401, + "a private share was served to a non-member" + ); + + let resp = client + .post(format!("{authed}/set_public/{id}")) + .header("Authorization", OTHER_MEMBER) + .json(&json!({ "is_public": true })) + .send() + .await?; + assert_eq!( + resp.status(), + 404, + "a member who is not the author made the share public" + ); + + let resp = client + .post(format!("{authed}/set_public/{id}")) + .header("Authorization", MEMBER) + .json(&json!({ "is_public": true })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = client.get(get(&id)).send().await?; + assert_eq!( + resp.status(), + 200, + "a public share was not served anonymously" + ); + let body: Value = resp.json().await?; + assert_eq!(body["snapshot"]["messages"][0]["content"], "hi"); + assert_eq!(body["can_unshare"], false); + + let delete = |token: &'static str| { + client + .delete(format!("{authed}/delete/{id}")) + .header("Authorization", token) + .send() + }; + assert_eq!( + delete(OTHER_MEMBER).await?.status(), + 404, + "a member who is neither the author nor an admin took the share down" + ); + assert_eq!( + delete(ADMIN).await?.status(), + 200, + "an admin could not take the share down" + ); + assert_eq!(status(Some(OTHER_MEMBER)).await?, 404); + + Ok(()) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index d56115d9b0..cedc691eb7 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -14677,6 +14677,168 @@ paths: schema: type: string + /w/{workspace}/ai/shared_sessions/share: + post: + summary: share an AI session transcript by link + description: > + Stores a read-only snapshot of the session that members of the workspace can open by + id, or anyone with the link once it is public. Sharing the same session again updates + that snapshot and keeps its id. + operationId: shareAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - session_id + - name + - message_count + - snapshot + properties: + session_id: + type: string + description: the session's id in the author's browser + name: + type: string + is_public: + type: boolean + description: left as it is on an existing share when absent; a new share starts private + message_count: + type: integer + minimum: 0 + snapshot: + type: object + additionalProperties: true + responses: + "200": + description: the shared snapshot + content: + application/json: + schema: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai/shared_sessions/status: + get: + summary: get the calling user's share of one of their AI sessions + operationId: getAiSessionShareStatus + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: session_id + in: query + required: true + schema: + type: string + responses: + "200": + description: the share, if any + content: + application/json: + schema: + type: object + properties: + share: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai/shared_sessions/set_public/{id}: + post: + summary: make a shared AI session public, or reserve it to workspace members + operationId: setAiSessionSharePublic + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - is_public + properties: + is_public: + type: boolean + responses: + "200": + description: the updated share + content: + application/json: + schema: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai_u/shared_sessions/get/{id}: + get: + summary: get a shared AI session + description: > + A public share is served without authentication; any other one only to a member of + the workspace. + operationId: getSharedAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: the shared session + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/SharedAiSessionInfo" + - type: object + required: + - snapshot + - can_unshare + properties: + snapshot: + type: object + additionalProperties: true + can_unshare: + type: boolean + description: whether the caller authored the share or is a workspace admin + + /w/{workspace}/ai/shared_sessions/delete/{id}: + delete: + summary: stop sharing an AI session + operationId: unshareAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: share deleted + content: + text/plain: + schema: + type: string + /w/{workspace}/apps/get_data/v/{secretWithExtension}: get: summary: get raw app data by @@ -30256,6 +30418,31 @@ components: - shared_at - expires_at + SharedAiSessionInfo: + type: object + properties: + id: + type: string + format: uuid + name: + type: string + is_public: + type: boolean + message_count: + type: integer + created_by: + type: string + shared_at: + type: string + format: date-time + required: + - id + - name + - is_public + - message_count + - created_by + - shared_at + InstanceAIProviderSummary: type: object properties: diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index cf7447ceba..fc7a20c57f 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -713,6 +713,10 @@ pub fn workspaced_service() -> Router { .nest( "/shared_artifacts", crate::ai_shared_artifacts::workspaced_service(), + ) + .nest( + "/shared_sessions", + crate::ai_shared_sessions::workspaced_service(), ); #[cfg(feature = "bedrock")] diff --git a/backend/windmill-api/src/ai_shared_sessions.rs b/backend/windmill-api/src/ai_shared_sessions.rs new file mode 100644 index 0000000000..c6554305db --- /dev/null +++ b/backend/windmill-api/src/ai_shared_sessions.rs @@ -0,0 +1,368 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Read-only snapshots of AI session transcripts, shared by their author. +//! +//! Sessions live in the author's browser; a row here exists only because the author asked for +//! a link. A share is readable by the members of its workspace, or by anyone holding the link +//! once its author makes it public. The snapshot is whatever the author's browser sent, so the +//! viewer treats it as untrusted data. + +use crate::db::{ApiAuthed, DB}; +use axum::{ + extract::{DefaultBodyLimit, Extension, Json, Path, Query}, + routing::{delete, get, post}, + Router, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use uuid::Uuid; +use windmill_api_auth::{is_effectively_unscoped, OptAuthed}; +use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::error::{Error, JsonResult, Result}; + +const MAX_SNAPSHOT_BYTES: usize = 10 * 1024 * 1024; +const MAX_NAME_CHARS: usize = 255; +const MAX_SESSION_ID_CHARS: usize = 255; +const SHARE_BODY_LIMIT: usize = MAX_SNAPSHOT_BYTES + 64 * 1024; + +pub fn workspaced_service() -> Router { + Router::new() + .route( + "/share", + post(share_session).layer(DefaultBodyLimit::max(SHARE_BODY_LIMIT)), + ) + .route("/status", get(get_share_status)) + .route("/set_public/{id}", post(set_public)) + .route("/delete/{id}", delete(unshare_session)) +} + +/// Mounted outside the authenticated router: a public share is served to anyone. +pub fn workspaced_unauthed_service() -> Router { + Router::new().route("/get/{id}", get(get_shared_session)) +} + +#[derive(Deserialize)] +struct ShareSession { + session_id: String, + name: String, + /// Left as it is on an existing share when absent; a new share starts private. + is_public: Option, + message_count: i32, + snapshot: Box, +} + +#[derive(Serialize)] +struct SharedSessionInfo { + id: Uuid, + name: String, + is_public: bool, + message_count: i32, + created_by: String, + shared_at: DateTime, +} + +#[derive(Serialize)] +struct SharedSession { + #[serde(flatten)] + info: SharedSessionInfo, + snapshot: Box, + /// Whether the caller may stop sharing it: its author, or a workspace admin. + can_unshare: bool, +} + +#[derive(Serialize)] +struct ShareStatus { + #[serde(skip_serializing_if = "Option::is_none")] + share: Option, +} + +#[derive(Deserialize)] +struct ShareStatusQuery { + session_id: String, +} + +#[derive(Deserialize)] +struct SetPublic { + is_public: bool, +} + +/// Sharing exposes the author's own browser state, so only the author's own unscoped token may +/// do it: a job token can carry an `on_behalf_of` identity, and every scoped token (guest, +/// embed, app policy, MCP) was minted for something narrower. +fn require_plain_user_token(authed: &ApiAuthed) -> Result<()> { + if authed.job_id.is_some() || !is_effectively_unscoped(authed.scopes.as_deref()) { + return Err(Error::PermissionDenied( + "Shared AI sessions are only reachable with an unscoped user token".to_string(), + )); + } + Ok(()) +} + +/// It is compared against a `VARCHAR(255)` column, and Postgres answers a NUL in a text +/// parameter with an opaque 500. +fn check_session_id(session_id: &str) -> Result<()> { + if session_id.is_empty() || session_id.chars().count() > MAX_SESSION_ID_CHARS { + return Err(Error::BadRequest(format!( + "Session id must be between 1 and {MAX_SESSION_ID_CHARS} characters" + ))); + } + if session_id.contains('\0') { + return Err(Error::BadRequest( + "Session id cannot contain NUL characters".to_string(), + )); + } + Ok(()) +} + +/// Share a session, or move the caller's existing link for it to this snapshot. +async fn share_session( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(payload): Json, +) -> JsonResult { + require_plain_user_token(&authed)?; + check_session_id(&payload.session_id)?; + let name = payload.name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME_CHARS || name.contains('\0') { + return Err(Error::BadRequest(format!( + "Session name must be between 1 and {MAX_NAME_CHARS} characters, without NUL" + ))); + } + let snapshot = payload.snapshot.get(); + if snapshot.len() > MAX_SNAPSHOT_BYTES { + return Err(Error::BadRequest(format!( + "Session snapshot is {} bytes, above the {MAX_SNAPSHOT_BYTES} byte limit", + snapshot.len() + ))); + } + if !snapshot.trim_start().starts_with('{') { + return Err(Error::BadRequest( + "Session snapshot must be a JSON object".to_string(), + )); + } + if payload.message_count < 0 { + return Err(Error::BadRequest( + "Message count cannot be negative".to_string(), + )); + } + + let mut tx = db.begin().await?; + let row = sqlx::query!( + r#"INSERT INTO ai_shared_session + (workspace_id, session_id, email, created_by, name, is_public, message_count, snapshot) + VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), $7, $8) + ON CONFLICT (workspace_id, email, session_id) DO UPDATE + SET created_by = EXCLUDED.created_by, + name = EXCLUDED.name, + is_public = COALESCE($6, ai_shared_session.is_public), + message_count = EXCLUDED.message_count, + snapshot = EXCLUDED.snapshot, + shared_at = now() + RETURNING id, is_public, shared_at, (xmax = 0) AS "inserted!""#, + &w_id, + &payload.session_id, + &authed.email, + &authed.username, + name, + payload.is_public, + payload.message_count, + snapshot, + ) + .fetch_one(&mut *tx) + .await?; + + let id = row.id.to_string(); + let public = row.is_public.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.share", + if row.inserted { + ActionKind::Create + } else { + ActionKind::Update + }, + &w_id, + Some(&id), + Some([("name", name), ("public", public.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(Json(SharedSessionInfo { + id: row.id, + name: name.to_string(), + is_public: row.is_public, + message_count: payload.message_count, + created_by: authed.username.clone(), + shared_at: row.shared_at, + })) +} + +/// The caller's own share of one of their sessions, if any. +async fn get_share_status( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Query(query): Query, +) -> JsonResult { + require_plain_user_token(&authed)?; + check_session_id(&query.session_id)?; + let share = sqlx::query_as!( + SharedSessionInfo, + "SELECT id, name, is_public, message_count, created_by, shared_at FROM ai_shared_session + WHERE workspace_id = $1 AND email = $2 AND session_id = $3", + &w_id, + &authed.email, + &query.session_id, + ) + .fetch_optional(&db) + .await?; + + Ok(Json(ShareStatus { share })) +} + +/// Only the author changes who can open their link; an admin may only take it down. +async fn set_public( + authed: ApiAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, + Json(payload): Json, +) -> JsonResult { + require_plain_user_token(&authed)?; + let mut tx = db.begin().await?; + let info = sqlx::query_as!( + SharedSessionInfo, + "UPDATE ai_shared_session SET is_public = $4 + WHERE workspace_id = $1 AND id = $2 AND email = $3 + RETURNING id, name, is_public, message_count, created_by, shared_at", + &w_id, + id, + &authed.email, + payload.is_public, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| { + Error::NotFound(format!( + "Shared session {id} not found, or not shared by you" + )) + })?; + + let id_str = id.to_string(); + let public = info.is_public.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.set_public", + ActionKind::Update, + &w_id, + Some(&id_str), + Some([("name", info.name.as_str()), ("public", public.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(Json(info)) +} + +/// A public share is served to anyone with the link; any other one only to a member of its +/// workspace, which is what an `ApiAuthed` resolved on a `/w/{workspace_id}` path is. +async fn get_shared_session( + OptAuthed(opt_authed): OptAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, +) -> JsonResult { + let row = sqlx::query!( + "SELECT id, email, name, is_public, message_count, created_by, snapshot, shared_at + FROM ai_shared_session + WHERE workspace_id = $1 AND id = $2", + &w_id, + id, + ) + .fetch_optional(&db) + .await?; + + let not_found = || { + Error::NotFound(format!( + "Shared session {id} not found: it may have been unshared, or be visible only to members of {w_id}" + )) + }; + let member = opt_authed + .as_ref() + .filter(|a| a.job_id.is_none() && is_effectively_unscoped(a.scopes.as_deref())); + let row = match row { + Some(row) if row.is_public || member.is_some() => row, + // A missing share and a private one answer a stranger alike, so the link does not + // confirm that a private share exists. + _ if member.is_none() => { + return Err(Error::NotAuthorized(format!( + "Shared session {id} is not public: sign in as a member of {w_id} to open it" + ))) + } + _ => return Err(not_found()), + }; + + Ok(Json(SharedSession { + can_unshare: member.is_some_and(|a| row.email == a.email || a.is_admin), + snapshot: RawValue::from_string(row.snapshot).map_err(|e| { + Error::internal_err(format!("Stored session snapshot is not valid JSON: {e}")) + })?, + info: SharedSessionInfo { + id: row.id, + name: row.name, + is_public: row.is_public, + message_count: row.message_count, + created_by: row.created_by, + shared_at: row.shared_at, + }, + })) +} + +async fn unshare_session( + authed: ApiAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, +) -> Result { + require_plain_user_token(&authed)?; + let mut tx = db.begin().await?; + let name = sqlx::query_scalar!( + "DELETE FROM ai_shared_session + WHERE workspace_id = $1 AND id = $2 AND (email = $3 OR $4::bool) + RETURNING name", + &w_id, + id, + &authed.email, + authed.is_admin, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| { + Error::NotFound(format!( + "Shared session {id} not found, or not shared by you" + )) + })?; + + let id_str = id.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.unshare", + ActionKind::Delete, + &w_id, + Some(&id_str), + Some([("name", name.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(format!("Stopped sharing {name}")) +} diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 9163256997..732675e78f 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -77,6 +77,7 @@ mod ai_sessions; #[cfg(feature = "parquet")] pub use ai_sessions::sweep_expired_ai_session_backups; mod ai_shared_artifacts; +mod ai_shared_sessions; mod apps; mod apps_raw_bundle; pub use apps::invalidate_app_policy_cache; @@ -924,6 +925,10 @@ pub async fn run_server( .layer(from_extractor::()) .layer(cors.clone()), ) + .nest( + "/w/{workspace_id}/ai_u/shared_sessions", + ai_shared_sessions::workspaced_unauthed_service(), + ) .layer(from_extractor::()) // Deprecated, here for backwards compatibility: user should use /mcp/w/{workspace_id}/mcp instead .nest( diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index 3050dcedf3..ce931213b5 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -98,6 +98,7 @@ }) const candidatePaths = $derived(extractCandidatePaths(message.content)) + const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer } }] const rendererPlugin = { renderer: { pre: CodeDisplay, @@ -158,7 +159,7 @@ labelClass="truncate" contentClass="font-main text-secondary {markdownProse.xs}" > - + {/if} diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index bdacb57615..197b831e7e 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -114,6 +114,9 @@ export interface ChatViewHost { // of their own; the chrome they drive hides itself. mode?: AIMode isSessionChat: boolean + /** Someone else's transcript, replayed for a reader who did not write it: markup that + * would execute or render beyond plain text (mermaid diagrams) stays off. */ + untrustedTranscript?: boolean /** Model + reasoning picker. Off where the model is configured elsewhere. */ supportsModelSettings: boolean /** Click a user message to edit and resend it. Needs a host that can rewind diff --git a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts new file mode 100644 index 0000000000..1e22903e9b --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts @@ -0,0 +1,85 @@ +import { AIAutonomyMode } from './AIChatManager.svelte' +import type { ChatViewHost } from './chatViewHost' +import type { DisplayMessage } from './shared' +import { AttachedFilesStore } from './files/attachedFiles.svelte' +import { SessionArtifactsStore } from './artifacts/artifactsState.svelte' +import type { PersistedArtifact } from './artifacts/artifactsDB' + +const noop = () => {} + +/** + * A host over a finished transcript nobody can continue: every affordance that would send, + * edit, retry or answer is off, so the chat components render it as a record. + */ +export function readOnlyChatViewHost(options: { + messages: DisplayMessage[] + workspace: string + artifacts: PersistedArtifact[] + openArtifact: (artifactId: string) => void +}): ChatViewHost { + const artifacts = new SessionArtifactsStore() + artifacts.artifacts = options.artifacts + return { + displayMessages: options.messages, + messages: [], + contextTokens: 0, + operatingWorkspace: options.workspace, + loading: false, + sendPending: false, + runHeldElsewhere: false, + loadingLabel: undefined, + compacting: false, + currentReply: '', + currentReasoning: '', + currentReasoningActive: false, + reasoningHiddenIndicatorLabel: undefined, + automaticScroll: false, + enableAutomaticScroll: noop, + disableAutomaticScroll: noop, + + instructions: '', + sendInFlight: false, + sendRequest: async () => false, + cancel: noop, + setAiChatInput: noop, + queuedMessage: '', + queuedContext: undefined, + queuedImages: [], + queuedFiles: [], + queuedBlobs: [], + queueMessage: noop, + dequeueMessage: noop, + setComposerStaged: noop, + setComposerHasDraft: noop, + clearComposerStaged: noop, + attachmentBytesExcluding: () => 0, + + storedImages: () => undefined, + retryRequest: noop, + restartGeneration: noop, + handleUserQuestionAnswer: () => false, + handleToolConfirmation: noop, + hasPendingRunForm: false, + isRunFormPending: () => false, + + isSessionChat: true, + untrustedTranscript: true, + supportsModelSettings: false, + supportsMessageEditing: false, + supportsMessageAttachments: false, + requiresMessageText: false, + supportsLinkedFolders: false, + attachmentAccept: '', + attachmentsAsBlobs: false, + tools: [], + autonomyMode: AIAutonomyMode.DEFAULT, + setAutonomyMode: noop, + autoAcceptEditsActive: false, + autoAcceptEditsAvailable: false, + autoAcceptToolConfirmationsAvailable: false, + planModeAvailable: false, + attachedFiles: new AttachedFilesStore(), + artifacts, + openArtifact: (artifactId) => options.openArtifact(artifactId) + } +} diff --git a/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte b/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte index 2be52a32d2..e83c163302 100644 --- a/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte @@ -3,11 +3,13 @@ import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte' import { AIMode } from '../AIChatManager.svelte' import { getAiChatManager } from '../aiChatManagerContext' + import { getChatViewHost } from '../chatViewHost' import { Check, Play } from 'lucide-svelte' // Chat `pre` renderer: the shared MarkdownCodeBlock plus the chat-only Apply // button (wired to the script editor) and mermaid diagrams. const aiChatManager = getAiChatManager() + const chatHost = getChatViewHost() const astNode = getAstNode() let code = $derived(astNode.current.children?.[0]?.children?.[0]?.value) @@ -34,5 +36,5 @@ {showApplyButton} onApplyCode={handleApplyCode} applyButtonIcon={aiChatManager.pendingNewCode ? Check : Play} - renderMermaid + renderMermaid={!chatHost.untrustedTranscript} /> diff --git a/frontend/src/lib/components/sessions/SessionShareButton.svelte b/frontend/src/lib/components/sessions/SessionShareButton.svelte new file mode 100644 index 0000000000..59f2fd19cb --- /dev/null +++ b/frontend/src/lib/components/sessions/SessionShareButton.svelte @@ -0,0 +1,231 @@ + + + + {#snippet trigger()} + + +
    +
    + +
    + {:else} +
    + +
    + {/if} +
+ {/snippet} + diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index 703a18967b..05a0cdda41 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -26,6 +26,7 @@ } from 'lucide-svelte' import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' import SessionChangesBar from './SessionChangesBar.svelte' + import SessionShareButton from './SessionShareButton.svelte' import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte' import { composerFocusRequest, @@ -432,6 +433,13 @@ {/snippet} + + {/snippet} {#if headerInPage} diff --git a/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte new file mode 100644 index 0000000000..19239fe48c --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte @@ -0,0 +1,121 @@ + + +{#snippet messageRow(message: DisplayMessage, messageIndex: number, inGroup: boolean)} + +{/snippet} +{#snippet groupRow(message: DisplayMessage, messageIndex: number)} + {@render messageRow(message, messageIndex, true)} +{/snippet} + +{#if snapshot.artifacts.length > 0} + +
+ Artifacts + {#each snapshot.artifacts as artifact (artifact.id)} + + {/each} +
+{/if} + +
+ {#each chatItems as item (chatItemKey(item))} + {#if item.kind === 'group'} +
+
+ +
+
+ {:else} + {@render messageRow(item.message, item.index, false)} + {/if} + {/each} +
+ + + drawer?.closeDrawer()}> + {#if openArtifact} + + {:else} + This artifact was not part of the share. + {/if} + + diff --git a/frontend/src/lib/components/sessions/sessionSharing.test.ts b/frontend/src/lib/components/sessions/sessionSharing.test.ts new file mode 100644 index 0000000000..a7720666fa --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionSharing.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' + +import { readSessionSnapshot } from './sessionSharing' + +describe('readSessionSnapshot', () => { + it('keeps only inline images and the rows and artifacts the viewer can render', () => { + const snapshot = readSessionSnapshot({ + messages: [ + { + role: 'user', + content: 'hi', + images: [ + { dataUrl: 'https://tracker.example/u.png', mediaType: 'image/png' }, + { dataUrl: 'data:image/png;base64,AAAA', mediaType: 'image/png' } + ] + }, + { role: 'tool', content: 'shot', imageUrl: 'https://tracker.example/t.png' }, + { role: 'tool', content: 'shot', imageUrl: 'data:image/png;base64,BBBB' }, + { + role: 'tool', + content: 'Run', + isLoading: true, + needsConfirmation: true, + runForm: { kind: 'test', code: 'export async function main() {}' }, + userQuestion: { question: 'ok?' }, + actions: [{ label: 'Open' }], + inspectedRun: { jobId: 'j', workspace: 'w', runId: 'j' } + }, + { role: 'system', content: 'not a chat row' }, + 'not an object' + ], + artifacts: [ + { id: 'a', name: 'Plan', kind: 'md', content: '# Plan' }, + { id: 'b', name: 'Bad', kind: 'svg', content: '' } + ] + }) + + expect(snapshot.messages.map((m) => m.role)).toEqual(['user', 'tool', 'tool', 'tool']) + expect(snapshot.messages[0]).toMatchObject({ + images: [{ dataUrl: 'data:image/png;base64,AAAA' }] + }) + expect((snapshot.messages[1] as { imageUrl?: string }).imageUrl).toBeUndefined() + expect(snapshot.messages[2]).toMatchObject({ imageUrl: 'data:image/png;base64,BBBB' }) + // Every affordance that would act as the reader is gone, pending state included. + expect(snapshot.messages[3]).toEqual({ + role: 'tool', + tool_call_id: 'shared-3', + content: 'Run', + showDetails: false, + blockedByPlanMode: false, + declinedByUser: false + }) + expect(snapshot.artifacts.map((a) => a.id)).toEqual(['a']) + }) + + it('reads a malformed snapshot as an empty one', () => { + expect(readSessionSnapshot('nope')).toEqual({ messages: [], artifacts: [] }) + }) +}) diff --git a/frontend/src/lib/components/sessions/sessionSharing.ts b/frontend/src/lib/components/sessions/sessionSharing.ts new file mode 100644 index 0000000000..3ecbe214e9 --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionSharing.ts @@ -0,0 +1,188 @@ +import type { DisplayMessage } from '$lib/components/copilot/chat/shared' +import type { ImageMediaType } from '$lib/components/copilot/chat/imageUtils' +import type { + ArtifactKind, + PersistedArtifact +} from '$lib/components/copilot/chat/artifacts/artifactsDB' + +/** The server's `MAX_SNAPSHOT_BYTES`. */ +export const MAX_SNAPSHOT_BYTES = 10 * 1024 * 1024 + +export type SharedSessionArtifact = { + id: string + name: string + kind: ArtifactKind + content: string + role?: 'plan' +} + +export type SessionSnapshot = { + messages: DisplayMessage[] + artifacts: SharedSessionArtifact[] +} + +export function sharedSessionUrl(workspaceId: string, shareId: string): string { + return `${window.location.origin}/shared_sessions/${encodeURIComponent( + workspaceId + )}/${encodeURIComponent(shareId)}` +} + +/** A row as it reads once the turn is over: the viewer can neither wait on nor answer it. */ +function settled(message: DisplayMessage, keepImages: boolean): DisplayMessage { + switch (message.role) { + case 'tool': + return { + ...message, + isLoading: false, + isQueued: false, + isStreamingArguments: false, + needsConfirmation: false, + resultStream: undefined + } + case 'assistant': + return { ...message, streaming: false } + case 'user': + return keepImages ? message : { ...message, images: undefined } + default: + return message + } +} + +/** + * The snapshot a share carries. Images go first when the whole would not fit: the + * transcript is what the link is for. + */ +export function buildSessionSnapshot( + messages: DisplayMessage[], + artifacts: PersistedArtifact[] +): SessionSnapshot { + const sharedArtifacts: SharedSessionArtifact[] = artifacts.map((a) => ({ + id: a.id, + name: a.name, + kind: a.kind, + content: a.content, + role: a.role + })) + for (const keepImages of [true, false]) { + const snapshot: SessionSnapshot = { + messages: messages.map((m) => settled(m, keepImages)), + artifacts: sharedArtifacts + } + if (new TextEncoder().encode(JSON.stringify(snapshot)).length <= MAX_SNAPSHOT_BYTES) { + return snapshot + } + } + throw new Error( + `the session is larger than the ${MAX_SNAPSHOT_BYTES / 1024 / 1024} MB a share can hold` + ) +} + +function isInlineImage(url: unknown): url is string { + return typeof url === 'string' && url.startsWith('data:image/') +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function str(value: unknown): string | undefined { + return typeof value === 'string' ? value : undefined +} + +function records(value: unknown): Record[] { + return Array.isArray(value) ? value.filter(isRecord) : [] +} + +/** + * A row rebuilt from the fields that only display. Everything else the live chat carries on a + * row is an affordance acting as whoever has the page open (a run form, a question to answer, + * a run to inspect, an item to open) or a pending state that mounts one, so it never survives: + * the author controls every byte of the snapshot. + */ +function readMessage(m: Record, index: number): DisplayMessage | undefined { + const content = str(m.content) ?? '' + switch (m.role) { + case 'user': + return { + role: 'user', + content, + index, + images: records(m.images) + .filter((i) => isInlineImage(i.dataUrl)) + .map((i) => ({ + dataUrl: i.dataUrl as string, + mediaType: i.mediaType as ImageMediaType, + name: str(i.name) + })), + pastes: records(m.pastes) + .filter((p) => typeof p.id === 'number' && typeof p.content === 'string') + .map((p) => ({ + id: p.id as number, + lines: typeof p.lines === 'number' ? p.lines : 0, + content: p.content as string + })), + files: records(m.files) + .filter((f) => typeof f.name === 'string' && typeof f.content === 'string') + .map((f) => ({ name: f.name as string, content: f.content as string })) + } + case 'assistant': + return { + role: 'assistant', + content, + reasoning: str(m.reasoning), + reasoningDurationMs: + typeof m.reasoningDurationMs === 'number' ? m.reasoningDurationMs : undefined, + createdAt: str(m.createdAt) + } + case 'tool': + return { + role: 'tool', + tool_call_id: str(m.tool_call_id) ?? `shared-${index}`, + content, + toolName: str(m.toolName), + parameters: m.parameters, + result: m.result, + logs: str(m.logs), + error: str(m.error), + showDetails: m.showDetails === true, + imageUrl: isInlineImage(m.imageUrl) ? m.imageUrl : undefined, + planArtifactId: str(m.planArtifactId), + planVersion: typeof m.planVersion === 'number' ? m.planVersion : undefined, + blockedByPlanMode: m.blockedByPlanMode === true, + declinedByUser: m.declinedByUser === true + } + case 'summary': + return { role: 'summary', content } + default: + return undefined + } +} + +/** + * A snapshot as the viewer may render it: rows rebuilt by {@link readMessage}, and an attached + * image only from an inline data URL, since any other source would load a third-party resource + * on behalf of whoever opens the link. Images inside rendered text are left to the viewer + * page's `img-src` policy. + */ +export function readSessionSnapshot(raw: unknown): SessionSnapshot { + const snapshot = isRecord(raw) ? raw : {} + const messages = records(snapshot.messages) + .map(readMessage) + .filter((m): m is DisplayMessage => m !== undefined) + const artifacts = records(snapshot.artifacts) + .filter( + (a) => + typeof a.id === 'string' && + typeof a.name === 'string' && + typeof a.content === 'string' && + (a.kind === 'md' || a.kind === 'html') + ) + .map((a) => ({ + id: a.id as string, + name: a.name as string, + kind: a.kind as ArtifactKind, + content: a.content as string, + role: a.role === 'plan' ? ('plan' as const) : undefined + })) + return { messages, artifacts } +} diff --git a/frontend/src/routes/(styled)/shared_sessions/[workspace]/[id]/+page.svelte b/frontend/src/routes/(styled)/shared_sessions/[workspace]/[id]/+page.svelte new file mode 100644 index 0000000000..57e0ca654b --- /dev/null +++ b/frontend/src/routes/(styled)/shared_sessions/[workspace]/[id]/+page.svelte @@ -0,0 +1,157 @@ + + + + + + + +
+
+
+ + {#if found} +
+
+

+ {found.session.name} +

+ {#if found.session.is_public} + Public + {:else} + {workspace} + {/if} +
+ + Read-only AI session shared by {found.session.created_by} · {displayDate( + found.session.shared_at + )} + +
+ {#if found.session.can_unshare} + + {/if} + {:else} + Shared AI session + {/if} +
+
+ +
+ {#if found} + {#if found.snapshot.messages.length > 0} + {#key found.session.id} + + {/key} + {:else} + + {/if} + {:else if shared.current?.state === 'signin'} + + + + {:else if shared.current?.state === 'gone'} + + {:else if shared.current?.state === 'error'} + + {:else} + + {/if} +
+
From eda43ddc41c10b3f7263103016275926a33bf768 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Thu, 15 Oct 2026 18:51:24 +0200 Subject: [PATCH 05/20] feat: let the session agent read folder and group permissions (#11796) * feat: let the session agent read folder and group permissions * fix: keep group extraPerms in the session agent's group listing --- .../copilot/chat/global/core.test.ts | 24 +- .../components/copilot/chat/global/core.ts | 206 ++++++++++++++---- .../copilot/chat/global/workspaceItems.ts | 4 + 3 files changed, 192 insertions(+), 42 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index a07b0102ca..546459cee2 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -1211,6 +1211,28 @@ describe('global AI tools', () => { expect(raw).not.toContain('db_draft_input') }) + // The flow read is rebuilt field by field for the model, so a field missing there is + // silently absent and reads as "shared with nobody". + it('reports who a deployed flow is shared with', async () => { + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + path: 'f/flows/shared', + summary: 'Shared flow', + value: { modules: [] }, + schema: {}, + extra_perms: { 'g/finance': false } + } as any) + + const item = JSON.parse( + await callGlobalTool('read_workspace_item', { + type: 'flow', + path: 'f/flows/shared', + version: 'deployed' + }) + ) + + expect(item.extraPerms).toEqual({ 'g/finance': false }) + }) + it('redacts variable draft values when reading workspace items', async () => { await callGlobalTool('write_variable', { path: 'f/secrets/api_key', @@ -7409,7 +7431,7 @@ describe('prepareGlobalSystemMessage', () => { }) expect(content).toContain('As a workspace admin you can write to any existing folder.') expect(content).toContain( - 'Folders here include `f/marketing`, `f/data_engineering` (you can also write to others not listed).' + 'Folders here include `f/marketing`, `f/data_engineering` (you can also write to others not listed; list_workspace_items with type "folder" lists them all).' ) expect(content).toContain( 'If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.' diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 6f762a4a22..e8f8fc1467 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -7,6 +7,7 @@ import { FlowService, FolderService, GcpTriggerService, + GroupService, HttpTriggerService, JobService, KafkaTriggerService, @@ -379,6 +380,14 @@ export type GlobalUserMessageOptions = { } const itemTypeSchema = z.enum(ITEM_TYPES) +// Folders and groups only carry permissions, so they are readable but kept out of +// `itemTypeSchema`, which the draft, deploy and delete tools share. +const ACCESS_TYPES = ['folder', 'group'] as const +type AccessType = (typeof ACCESS_TYPES)[number] +const readableTypeSchema = z.enum([...ITEM_TYPES, ...ACCESS_TYPES]) +function isAccessType(type: string): type is AccessType { + return (ACCESS_TYPES as readonly string[]).includes(type) +} const instructionSubjectSchema = z.enum(ALL_INSTRUCTION_SUBJECTS) const triggerKindSchema = z.enum(TRIGGER_KINDS) const scriptLangSchema = z.enum($ScriptLang.enum) @@ -455,10 +464,10 @@ const listPipelinesSchema = z.object({}) const listWorkspaceItemsSchema = z.object({ types: z - .array(itemTypeSchema) + .array(readableTypeSchema) .optional() .describe( - 'Optional item types to list. Defaults to scripts and flows. Pass schedule or trigger explicitly when needed (listing triggers spans 9 kinds and is heavier).' + 'Optional item types to list. Defaults to scripts and flows. Pass schedule or trigger explicitly when needed (listing triggers spans 9 kinds and is heavier). "folder" lists folders with their owners and extraPerms; "group" lists groups with their extraPerms (read one for its members). path_prefix does not apply to these two.' ), query: z.string().optional().describe('Optional case-insensitive path or summary search string.'), path_prefix: z @@ -485,11 +494,11 @@ const listWorkspaceItemsSchema = z.object({ }) const readWorkspaceItemSchema = z.object({ - type: itemTypeSchema, + type: readableTypeSchema, path: z .string() .describe( - 'Workspace path of the item to read, or a hub/// path from search_hub_scripts to read a hub script.' + 'Workspace path of the item to read, or a hub/// path from search_hub_scripts to read a hub script. For a folder or group, its name.' ), trigger_kind: triggerKindSchema .optional() @@ -1400,16 +1409,19 @@ const createFolderSchema = z.object({ // `folders`/`foldersRead` are undefined when the user's role in this workspace could not // be resolved. -type FolderPromptContext = { folders?: string[]; foldersRead?: string[]; isAdmin: boolean } +type FolderPromptContext = { + folders?: string[] + foldersRead?: string[] + groups?: string[] + isAdmin: boolean +} // Renders the folders the current user can act on into the system prompt so the -// model can pick an `f//...` path without a discovery round-trip (there -// is no folder-listing tool). For a non-admin, `folders` (from whoami) is exactly -// the writable set, so read-only folders are listed separately as off-limits. -// Admins bypass folder ACLs and can write anywhere, but `folders` only carries -// their explicitly-permissioned subset, so for admins it is offered as a -// non-exhaustive hint alongside permission-agnostic guidance (the complete set -// needs a folder-listing tool — follow-up). +// model can pick an `f//...` path without a discovery round-trip. For a +// non-admin, `folders` (from whoami) is exactly the writable set, so read-only +// folders are listed separately as off-limits. Admins bypass folder ACLs and can +// write anywhere, but `folders` only carries their explicitly-permissioned subset, +// so for admins it is a non-exhaustive hint and list_workspace_items has the rest. // Capped so a folder-heavy workspace can't dominate the prompt. function buildFolderGuidance( username: string, @@ -1429,7 +1441,7 @@ function buildFolderGuidance( if (ctx.isAdmin) { const known = writable.length > 0 - ? ` Folders here include ${fmt(writable)} (you can also write to others not listed).` + ? ` Folders here include ${fmt(writable)} (you can also write to others not listed; list_workspace_items with type "folder" lists them all).` : '' return `- As a workspace admin you can write to any existing folder.${known} If the user names a folder, use it;${canCreateFolder ? ' if they explicitly ask for a new folder, create it with `create_folder`;' : ''} otherwise ask them which folder to use rather than guessing${canCreateFolder ? ' or creating one unprompted' : ''}.` } @@ -1536,6 +1548,13 @@ const buildGlobalSystemPrompt = ( const when = (cond: boolean, block: string) => (cond ? block : '') const folderGuidance = buildFolderGuidance(username, folderCtx, canCreateFolder) const folderGuidanceBlock = folderGuidance ? `\n${folderGuidance}` : '' + // A grant to `g/` reaches the user only through membership, which no permission + // list shows. Outside the folder guidance, which a role that cannot draft never gets. + const memberOf = (folderCtx?.groups ?? []).filter((g) => g !== 'all') + const groupMembershipRule = + memberOf.length > 0 + ? `- The user is a member of ${memberOf.map((g) => `\`g/${g}\``).join(', ')}, so a grant to one of those groups is a grant to them.\n` + : '' // `previewTools` doubles as "this is a session chat" — sessions are the only // chats that get the preview tool set. The alpha heads-up only makes sense // there, where the chat actively builds the pipeline on the canvas; the @@ -1628,7 +1647,7 @@ Rules:${when( - Draft tools create or update drafts only; they do not deploy or mutate deployed workspace items.` )} - Use list_workspace_items to find items and read_workspace_item before changing an existing item. For triggers, pass trigger_kind. -- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed. +${groupMembershipRule}- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed. - If the user message includes an ACTIVE EDITOR section, treat it as the currently open item and use it for references like "this", "current", or "open editor".${activePreviewRule}${when( canWriteAnyDraft && canDeployAnyKind, ` @@ -1852,6 +1871,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { path: item.path, summary: item.summary, isSecret: item.isSecret, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -1869,6 +1889,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { value: summarizeAppValue(item.value as AppDraftValue), rawApp: item.rawApp, executionMode: item.executionMode, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -1882,6 +1903,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { path: item.path, summary: item.summary, value: editable, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -2404,34 +2426,43 @@ async function readWorkspaceItem( getDraft: !deployedOnly }) const draft = deployedOnly ? undefined : (script.draft as Script | undefined) - return scriptToItem(draft ?? script, true) + return { ...scriptToItem(draft ?? script, true), extraPerms: script.extra_perms } } case 'flow': { // Prefer the DB draft (newer than the deployed version) when one exists, // unless the caller explicitly asked for the deployed state. const flow = await FlowService.getFlowByPath({ workspace, path, getDraft: !deployedOnly }) const draft = deployedOnly ? undefined : (flow.draft as Flow | undefined) - return flowToItem(draft ?? flow, true) + return { ...flowToItem(draft ?? flow, true), extraPerms: flow.extra_perms } } - case 'schedule': - return scheduleToItem(await ScheduleService.getSchedule({ workspace, path }), true) - case 'trigger': + case 'schedule': { + const schedule = await ScheduleService.getSchedule({ workspace, path }) + return { ...scheduleToItem(schedule, true), extraPerms: schedule.extra_perms } + } + case 'trigger': { if (!triggerKind) { throw new Error('trigger_kind is required when type is trigger.') } - return triggerToItem( - triggerKind, - await triggerServices[triggerKind].get({ workspace, path }), - true - ) - case 'resource': - return resourceToItem(await ResourceService.getResource({ workspace, path }), true) - case 'variable': + const trigger = await triggerServices[triggerKind].get({ workspace, path }) + return { + ...triggerToItem(triggerKind, trigger, true), + extraPerms: (trigger as { extra_perms?: Record }).extra_perms + } + } + case 'resource': { + const resource = await ResourceService.getResource({ workspace, path }) + return { ...resourceToItem(resource, true), extraPerms: resource.extra_perms } + } + case 'variable': { // Never expose the value, even when read directly. Pass decryptSecret=false // to avoid materializing secret values server-side. - return variableToItem( - await VariableService.getVariable({ workspace, path, decryptSecret: false }) - ) + const variable = await VariableService.getVariable({ + workspace, + path, + decryptSecret: false + }) + return { ...variableToItem(variable), extraPerms: variable.extra_perms } + } case 'app': { // Returns lightweight metadata only — file/runnable contents come via read_app_file. const app = await AppService.getAppByPath({ workspace, path }) @@ -2445,6 +2476,7 @@ async function readWorkspaceItem( summary: app.summary, rawApp: false, executionMode, + extraPerms: app.extra_perms, isDraft: false } } @@ -2457,12 +2489,78 @@ async function readWorkspaceItem( value: metadata as unknown as AppDraftValue, rawApp: app.raw_app, executionMode, + extraPerms: app.extra_perms, isDraft: false } } } } +// Accepts the `f/` / `g/` form the model sees in extra_perms keys and paths. +function accessEntityName(type: AccessType, path: string): string { + const prefix = type === 'folder' ? 'f/' : 'g/' + const name = path.startsWith(prefix) ? path.slice(prefix.length) : path + return name.replace(/\/+$/, '') +} + +async function readAccessEntity(type: AccessType, path: string, workspace: string) { + const name = accessEntityName(type, path) + if (type === 'folder') { + const folder = await FolderService.getFolder({ workspace, name }) + return { + type, + name: folder.name, + summary: folder.summary, + owners: folder.owners, + extraPerms: folder.extra_perms, + defaultPermissionedAs: folder.default_permissioned_as + } + } + const group = await GroupService.getGroup({ workspace, name }) + return { + type, + name: group.name, + summary: group.summary, + members: group.members, + extraPerms: group.extra_perms + } +} + +type AccessEntityRow = { + type: AccessType + path: string + summary?: string + owners?: string[] + extraPerms?: Record +} + +// Group rows omit members: the list endpoint does not return them. +async function listAccessEntities( + types: AccessType[], + workspace: string, + perPage: number, + page?: number +): Promise { + const rows: AccessEntityRow[] = [] + if (types.includes('folder')) { + for (const f of await FolderService.listFolders({ workspace, perPage, page })) { + rows.push({ + type: 'folder', + path: f.name, + summary: f.summary, + owners: f.owners, + extraPerms: f.extra_perms + }) + } + } + if (types.includes('group')) { + for (const g of await GroupService.listGroups({ workspace, perPage, page })) { + rows.push({ type: 'group', path: g.name, summary: g.summary, extraPerms: g.extra_perms }) + } + } + return rows +} + async function listWorkspaceItems( types: WorkspaceItemType[], workspace: string, @@ -3054,6 +3152,7 @@ export type GlobalPromptIdentity = { is_admin?: boolean folders?: string[] folders_read?: string[] + groups?: string[] } // `userWorkspaces` carries the real per-workspace username for every membership at no @@ -3076,7 +3175,8 @@ export async function resolveGlobalPromptIdentity( username: u.username, is_admin: u.is_admin, folders: u.folders, - folders_read: u.folders_read + folders_read: u.folders_read, + groups: u.groups } } // Headless callers (the eval harness) hold no workspace and pass their own identity. @@ -3876,10 +3976,23 @@ export const globalTools: SessionTool<{}>[] = [ planModeSafe: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = listWorkspaceItemsSchema.parse(args) - const types = getRequestedTypes(parsed.types) + const accessTypes = (parsed.types ?? []).filter(isAccessType) + const itemTypes = (parsed.types ?? []).filter((t): t is WorkspaceItemType => !isAccessType(t)) + // Asking only for folders or groups must not fall back to the default scripts and flows. + const types = + accessTypes.length > 0 && itemTypes.length === 0 ? [] : getRequestedTypes(itemTypes) const limit = parsed.limit ?? 50 toolCallbacks.setToolStatus(toolId, { content: 'Listing workspace items...' }) + const accessRows = ( + await listAccessEntities( + accessTypes, + workspace, + Math.min(limit, MAX_LIST_LIMIT), + parsed.page + ) + ).filter((row) => itemMatches(row, parsed.query)) + const byKey = new Map() const workspaceItems = await listWorkspaceItems( types, @@ -3923,7 +4036,10 @@ export const globalTools: SessionTool<{}>[] = [ // No cross-type truncation: each type is already capped at `limit` rows by // its own list call, and slicing the concatenation would silently drop the // later types' rows while their next page skips past them. - const results = Array.from(byKey.values()).filter((item) => itemMatches(item, parsed.query)) + const results = [ + ...Array.from(byKey.values()).filter((item) => itemMatches(item, parsed.query)), + ...accessRows + ] toolCallbacks.setToolStatus(toolId, { content: `Listed ${results.length} workspace item(s)` @@ -3953,12 +4069,19 @@ export const globalTools: SessionTool<{}>[] = [ def: createToolDef( readWorkspaceItemSchema, 'read_workspace_item', - 'Read one workspace item or draft. Prefers your draft when one exists; pass version: "deployed" to read the deployed state instead.' + 'Read one workspace item or draft. Prefers your draft when one exists; pass version: "deployed" to read the deployed state instead. A deployed item carries extraPerms (a draft does not; pass version: "deployed" for it): who it is shared with beyond its owner, as u/ or g/ → true (write) or false (read-only). A folder returns its owners and extraPerms; a group returns its members and extraPerms (who may manage it). For a folder or group, path is its name. A g/ entry grants every member of that group (g/all is everyone), and workspace admins can read and write every folder and item whatever these lists say.' ), planModeSafe: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = readWorkspaceItemSchema.parse(args) - if (parsed.type === 'trigger' && !parsed.trigger_kind) { + const { type } = parsed + if (isAccessType(type)) { + toolCallbacks.setToolStatus(toolId, { content: `Reading ${type} "${parsed.path}"...` }) + const entity = await readAccessEntity(type, parsed.path, workspace) + toolCallbacks.setToolStatus(toolId, { content: `Read ${type} "${entity.name}"` }) + return JSON.stringify(entity, null, 2) + } + if (type === 'trigger' && !parsed.trigger_kind) { const message = 'trigger_kind is required when type is trigger.' toolCallbacks.setToolStatus(toolId, { content: message, error: message }) return JSON.stringify({ success: false, error: message }) @@ -3966,16 +4089,16 @@ export const globalTools: SessionTool<{}>[] = [ const draft = parsed.version === 'deployed' || isHubPath(parsed.path) ? null - : await getGlobalDraft(workspace, parsed.type, parsed.path, parsed.trigger_kind) + : await getGlobalDraft(workspace, type, parsed.path, parsed.trigger_kind) if (draft) { toolCallbacks.setToolStatus(toolId, { - content: `Read draft ${parsed.type} "${parsed.path}"` + content: `Read draft ${type} "${parsed.path}"` }) // The mode reported is the draft's, which is what deploying it will write. The // deployed app's own mode is a different question, asked with version: // "deployed", and must not be fetched here. const executionMode = - parsed.type === 'app' + type === 'app' ? await describeAppExposure( workspace, (draft.value as AppDraftValue)?.policy?.execution_mode @@ -3985,16 +4108,16 @@ export const globalTools: SessionTool<{}>[] = [ } toolCallbacks.setToolStatus(toolId, { - content: `Reading ${parsed.type} "${parsed.path}"...` + content: `Reading ${type} "${parsed.path}"...` }) const item = await readWorkspaceItem( - parsed.type, + type, parsed.path, workspace, parsed.trigger_kind, parsed.version === 'deployed' ) - toolCallbacks.setToolStatus(toolId, { content: `Read ${parsed.type} "${parsed.path}"` }) + toolCallbacks.setToolStatus(toolId, { content: `Read ${type} "${parsed.path}"` }) return JSON.stringify(serializeWorkspaceItemForRead(item), null, 2) } }, @@ -9368,6 +9491,7 @@ export function prepareGlobalSystemMessage( ? { folders: user.folders, foldersRead: user.folders_read ?? user.folders, + groups: user.groups, isAdmin: user.is_admin ?? false } : undefined diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts index 3d922a3b72..d08fe4fd58 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts @@ -151,6 +151,10 @@ export type WorkspaceItem = { * app, not in listings — a listing carrying it would make absence read as * proof of no exposure. */ executionMode?: string + /** Who a deployed item is shared with beyond its path owner, as `u/` / + * `g/` → true for write, false for read-only. A draft has no permissions of + * its own, so a draft read leaves it unset rather than reporting the item unshared. */ + extraPerms?: Record isDraft: boolean isLiveDraft?: boolean } From 4361a41b3b03fa0e3b181d85f9a4eafcac5f9c6f Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 15 Oct 2026 18:57:10 +0200 Subject: [PATCH 06/20] chore(main): release 1.836.0 (#11784) * chore(main): release 1.836.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 31 +++ backend/Cargo.lock | 180 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 168 insertions(+), 137 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a533c73dbf..84ce810af3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.835.0" + ".": "1.836.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 57ec310ab9..ddd54e1aa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## [1.836.0](https://github.com/windmill-labs/windmill/compare/v1.835.0...v1.836.0) (2026-10-15) + + +### Features + +* **cli:** sync an app's custom path as a workspace-specific file ([#11786](https://github.com/windmill-labs/windmill/issues/11786)) ([718aad7](https://github.com/windmill-labs/windmill/commit/718aad7396397fe12295a27a947c76221f37ad10)) +* let operators save resource and variable drafts ([#11736](https://github.com/windmill-labs/windmill/issues/11736)) ([8c0185d](https://github.com/windmill-labs/windmill/commit/8c0185d55a1a8c6fbc5e41b8b9d77865563f515b)) +* let raw app backend runnables import each other ([#11777](https://github.com/windmill-labs/windmill/issues/11777)) ([526da60](https://github.com/windmill-labs/windmill/commit/526da60da92832cc6e9c2942cea1f7729b3a05fd)) +* let the session agent read folder and group permissions ([#11796](https://github.com/windmill-labs/windmill/issues/11796)) ([eda43dd](https://github.com/windmill-labs/windmill/commit/eda43ddc41c10b3f7263103016275926a33bf768)) +* resolve canceled jobs and re-run them in limited batches ([#11797](https://github.com/windmill-labs/windmill/issues/11797)) ([f827ba0](https://github.com/windmill-labs/windmill/commit/f827ba05667e3ca5bcd3bc89dac7f51b85dd32b3)) +* run duckdb jobs out of process under job isolation, drop the engine fork, bump to 1.5.6 ([#11780](https://github.com/windmill-labs/windmill/issues/11780)) ([f9513e8](https://github.com/windmill-labs/windmill/commit/f9513e82eed3721ecbfd87004d1cd385ac740903)) +* run previews as the runnable's on_behalf_of identity ([#11778](https://github.com/windmill-labs/windmill/issues/11778)) ([4f71231](https://github.com/windmill-labs/windmill/commit/4f712318c3b52366b03bf7f941ecae4730fbf967)) +* sandbox new low-code and raw apps by default ([#11760](https://github.com/windmill-labs/windmill/issues/11760)) ([813c080](https://github.com/windmill-labs/windmill/commit/813c080d4684eecd144ef82706b04339c8f8d35a)) +* share AI sessions read-only by link, optionally public ([#11799](https://github.com/windmill-labs/windmill/issues/11799)) ([a9aa2b8](https://github.com/windmill-labs/windmill/commit/a9aa2b8229da0d54ed68eb40e4426e6983ff631e)) + + +### Bug Fixes + +* **cli:** include script modules in wmill dev previews ([#11787](https://github.com/windmill-labs/windmill/issues/11787)) ([b563f5c](https://github.com/windmill-labs/windmill/commit/b563f5cb5121c431f525c2e0266994c6d655185b)) +* let raw app SDK tokens read the viewer's identity without a toggle ([#11790](https://github.com/windmill-labs/windmill/issues/11790)) ([7da2344](https://github.com/windmill-labs/windmill/commit/7da234481333fcbdc348215589e2d3bfe5394b4a)) +* let Teams handlers post with job tokens again ([#11792](https://github.com/windmill-labs/windmill/issues/11792)) ([64e1630](https://github.com/windmill-labs/windmill/commit/64e1630d497af1b50a772aa66ef123f675ea6bb1)) +* relock apps in place so imported script changes reach them ([#11789](https://github.com/windmill-labs/windmill/issues/11789)) ([aca7fed](https://github.com/windmill-labs/windmill/commit/aca7fed33ddffa17b0e78d50a39ded032f6d8ba2)) +* relock scripts and flow steps whose code changed on deploy ([#11794](https://github.com/windmill-labs/windmill/issues/11794)) ([1f1df12](https://github.com/windmill-labs/windmill/commit/1f1df1254ebc417a8344801b571c4be8e98636c4)) +* send Azure Foundry gpt-5.5+ models to the Responses API ([#11788](https://github.com/windmill-labs/windmill/issues/11788)) ([ab89835](https://github.com/windmill-labs/windmill/commit/ab8983543b0641c96a8b4a2cbd829cc4040e9f41)) +* show the app's summary in the app viewer's page header ([#11782](https://github.com/windmill-labs/windmill/issues/11782)) ([3bee9c9](https://github.com/windmill-labs/windmill/commit/3bee9c94012474b7bb230d719fa34df0c0a6c25e)) + + +### Performance Improvements + +* drive schedule already-exists check from an indexed queue lookup ([#11783](https://github.com/windmill-labs/windmill/issues/11783)) ([7eee210](https://github.com/windmill-labs/windmill/commit/7eee210d761d332f8165b4f8a6f0ee6f1ec8864f)) + ## [1.835.0](https://github.com/windmill-labs/windmill/compare/v1.834.0...v1.835.0) (2026-10-14) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index bc5b9aa55c..e52b446817 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2571,9 +2571,9 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -3926,9 +3926,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -3936,21 +3936,21 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror 2.0.21", ] @@ -5554,9 +5554,9 @@ dependencies = [ [[package]] name = "frostem" -version = "1.20260821.7" +version = "1.20260821.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28c70238056ad1dbfdf035222a571d2e9baf5b6a4c308cfa87bc8cbe7f2f3840" +checksum = "9e2488a10218a17366ce6bd38b6d081b4387a9548d350029db9feddc9bb44d6d" [[package]] name = "fs4" @@ -15486,7 +15486,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.835.0" +version = "1.836.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15611,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15767,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15790,7 +15790,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15807,7 +15807,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -15833,7 +15833,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.835.0" +version = "1.836.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15843,7 +15843,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15860,7 +15860,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "base64 0.22.1", @@ -15882,7 +15882,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -15905,7 +15905,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15921,7 +15921,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15943,7 +15943,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15965,7 +15965,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -15979,7 +15979,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-nats", @@ -16015,7 +16015,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -16041,7 +16041,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -16069,7 +16069,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -16091,7 +16091,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -16111,7 +16111,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -16153,7 +16153,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -16182,7 +16182,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.835.0" +version = "1.836.0" dependencies = [ "lazy_static", "serde", @@ -16194,7 +16194,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.835.0" +version = "1.836.0" dependencies = [ "argon2", "axum", @@ -16218,7 +16218,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -16232,7 +16232,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.835.0" +version = "1.836.0" dependencies = [ "axum", "chrono", @@ -16271,7 +16271,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.835.0" +version = "1.836.0" dependencies = [ "chrono", "lazy_static", @@ -16286,7 +16286,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "axum", @@ -16305,7 +16305,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.835.0" +version = "1.836.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16421,7 +16421,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.835.0" +version = "1.836.0" dependencies = [ "chrono", "futures", @@ -16441,7 +16441,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.835.0" +version = "1.836.0" dependencies = [ "regex", "serde", @@ -16458,7 +16458,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16485,7 +16485,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "futures", @@ -16502,7 +16502,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.835.0" +version = "1.836.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16518,7 +16518,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -16540,7 +16540,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -16571,7 +16571,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "arc-swap", @@ -16596,7 +16596,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-stream", @@ -16632,7 +16632,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "futures", @@ -16651,7 +16651,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.835.0" +version = "1.836.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16660,7 +16660,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16672,7 +16672,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -16684,7 +16684,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "gosyn", @@ -16696,7 +16696,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16708,7 +16708,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -16720,7 +16720,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "nu-parser", @@ -16731,7 +16731,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16742,7 +16742,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16754,7 +16754,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16765,7 +16765,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-recursion", @@ -16788,7 +16788,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -16800,7 +16800,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16814,7 +16814,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16831,7 +16831,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16844,7 +16844,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde", @@ -16856,7 +16856,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16874,7 +16874,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16890,7 +16890,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16907,7 +16907,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -16921,7 +16921,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-recursion", @@ -16960,7 +16960,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "const_format", @@ -16998,7 +16998,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.835.0" +version = "1.836.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17009,7 +17009,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-recursion", @@ -17044,7 +17044,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17068,7 +17068,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17101,7 +17101,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17128,7 +17128,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17161,7 +17161,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17181,7 +17181,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17215,7 +17215,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17252,7 +17252,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17275,7 +17275,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17299,7 +17299,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-nats", @@ -17323,7 +17323,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17358,7 +17358,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17386,7 +17386,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-trait", @@ -17411,7 +17411,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17430,7 +17430,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-once-cell", @@ -17548,7 +17548,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.835.0" +version = "1.836.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 6fc1341d53..f872c6d4d9 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.835.0" +version = "1.836.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.835.0" +version = "1.836.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index cdd8ab75f5..9aae112987 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.835.0" +version = "1.836.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.835.0" +version = "1.836.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.835.0" +version = "1.836.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.835.0" +version = "1.836.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index aa6c5cc297..514a902dfa 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.835.0" +version = "1.836.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index cedc691eb7..d07e036e15 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.835.0 + version: 1.836.0 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 1c810190d3..14f4702b9c 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.835.0"; +export const VERSION = "v1.836.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 99b3647dc4..161b3152d1 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.835.0", + "version": "1.836.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.835.0", + "version": "1.836.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index e590d8656a..2436affdbc 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.835.0", + "version": "1.836.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 77e085584f..7f124ce338 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.835.0"; +export const VERSION = "1.836.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index a448bfbb25..519b4a4132 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.835.0", + "version": "1.836.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.835.0", + "version": "1.836.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 9983885013..383e24b8be 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.835.0", + "version": "1.836.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index 78e1dc12eb..7ae4592632 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.835.0" +wmill = ">=1.836.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index ddca38afc8..847c830589 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.835.0 + version: 1.836.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index ad1592c244..0bea86345b 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.835.0' + ModuleVersion = '1.836.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index f01450a8b4..74cfc54998 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.835.0" +version = "1.836.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 52ba2d7886..aae26464bc 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.835.0", + "version": "1.836.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index dcaca9fda0..29ca0a25a0 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.835.0", + "version": "1.836.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index d9020f0403..7df5ec3ae3 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.835.0 +1.836.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index f724904b5b..ed6867f680 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.835.0", + "version": "1.836.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.835.0", + "version": "1.836.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 424d7458d1..8a2726a094 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.835.0", + "version": "1.836.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 0b980546b104cf46f385133af553dfbe5f533eca Mon Sep 17 00:00:00 2001 From: hugocasa Date: Thu, 15 Oct 2026 19:31:21 +0200 Subject: [PATCH 07/20] feat: agents run on behalf of their deployer (#11430) * Revert "docs: agent editor comments describe runs as the caller" This reverts commit d94919c9feb3239980276a4ceb1e905fc0a6c1a3. * Revert "refactor: agents run as the caller, with a note on what a shared one needs" This reverts commit 0748a2fb51592b1d7c44687577937d52a8c89116. * fix: a run as an identity continues only the caller's own conversation Co-Authored-By: Claude Opus 5.5 * fix: an agent run as its identity takes only attachments its caller may read Co-Authored-By: Claude Opus 5.5 * fix: the resource editor keeps an agent's identity on an admin's save Co-Authored-By: Claude Opus 5.5 * chore: regenerate workspace tool schemas for preserve_on_behalf_of Co-Authored-By: Claude Opus 5.5 * fix: the rust client sets preserve_on_behalf_of on resource writes Co-Authored-By: Claude Opus 5.5 * feat: agents run on behalf of their identity only when they opt in Co-Authored-By: Claude Opus 5.5 * fix: an agent holds an identity only while it runs on behalf of it Co-Authored-By: Claude Opus 5.5 * chore: reduce the agent identity migration to clearing untrusted keys Co-Authored-By: Claude Opus 5.5 * fix: refuse decoded variable references in inputs to an agent run as its identity Co-Authored-By: Claude Opus 5.5 * fix: user renames and offboarding re-point an agent's identity Co-Authored-By: Claude Opus 5.5 * fix: refuse model-written tool arguments that the tool's job would interpolate Co-Authored-By: Claude Opus 5.5 * chore: agent on-behalf-of migration after main's Co-Authored-By: Claude Opus 5.5 * fix: the agent identity migration also clears trashed agents Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...8d801e8c121f1e0cd904a77ce55bcf9bc5053.json | 29 +++ ...611e11c7a05d69b4b7907f8909aec82fb1eb2.json | 15 -- ...3eb83d5c19e32aef199bf161e8ba8d1adf176.json | 16 ++ ...20261015135223_agent_on_behalf_of.down.sql | 1 + .../20261015135223_agent_on_behalf_of.up.sql | 19 ++ .../tests/flow_conversation_running_turn.rs | 14 +- backend/tests/v2_job_delete_orphans.rs | 1 + .../tests/agent_on_behalf_of.rs | 216 ++++++++++++++++++ .../tests/agent_runs.rs | 60 ----- .../tests/fork_clone_on_behalf_of.rs | 37 ++- .../tests/offboarding.rs | 32 ++- backend/windmill-api-jobs/src/execution.rs | 1 + backend/windmill-api-users/src/users.rs | 9 + .../windmill-api-workspaces/src/workspaces.rs | 56 ++++- backend/windmill-api/openapi.yaml | 11 +- backend/windmill-api/src/agent_runs.rs | 116 +++++++++- backend/windmill-api/src/offboarding.rs | 22 ++ backend/windmill-api/src/users.rs | 28 ++- backend/windmill-api/src/workspaces_export.rs | 9 +- .../windmill-common/src/flow_conversations.rs | 18 +- backend/windmill-common/src/variables.rs | 9 + backend/windmill-store/src/resources.rs | 185 ++++++++++++++- backend/windmill-worker/src/ai/tools.rs | 67 +++++- backend/windmill-worker/src/common.rs | 13 +- cli/src/commands/resource/resource.ts | 69 +++++- cli/src/commands/sync/sync.ts | 1 + cli/src/core/permissioned_as.ts | 12 + cli/src/types.ts | 2 +- cli/test/deploy_on_behalf_of_unit.test.ts | 25 ++ ...precheck_permissioned_as_apps_unit.test.ts | 13 ++ cli/test/resource_push_agent_obo_unit.test.ts | 57 +++++ cli/windmill-utils-internal/src/deploy.ts | 30 ++- .../lib/components/CompareWorkspaces.svelte | 22 +- .../src/lib/components/DeployWorkspace.svelte | 14 +- .../lib/components/OnBehalfOfSelector.svelte | 4 +- .../src/lib/components/ResourceEditor.svelte | 9 +- .../copilot/chat/workspaceToolsZod.gen.ts | 3 +- .../components/details/OnBehalfOfBadge.svelte | 9 +- .../lib/components/flows/agentDraft.svelte.ts | 41 +++- .../components/flows/agentResourceUtils.ts | 2 + .../flows/content/AgentEditorHost.svelte | 17 +- .../flows/content/AgentEditorModal.svelte | 1 + .../flows/content/AgentSettings.svelte | 34 ++- frontend/src/lib/utils_draft_deploy.test.ts | 19 ++ frontend/src/lib/utils_draft_deploy.ts | 16 +- frontend/src/lib/utils_workspace_deploy.ts | 45 +++- .../agents/get/[...path]/+page.svelte | 6 + rust-client/src/client.rs | 2 + 48 files changed, 1265 insertions(+), 172 deletions(-) create mode 100644 backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json delete mode 100644 backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json create mode 100644 backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json create mode 100644 backend/migrations/20261015135223_agent_on_behalf_of.down.sql create mode 100644 backend/migrations/20261015135223_agent_on_behalf_of.up.sql create mode 100644 backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs delete mode 100644 backend/windmill-api-integration-tests/tests/agent_runs.rs create mode 100644 cli/test/resource_push_agent_obo_unit.test.ts diff --git a/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json b/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json new file mode 100644 index 0000000000..6510374dfc --- /dev/null +++ b/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT resource_type, value AS \"value: sqlx::types::Json>\"\n FROM resource WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "resource_type", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "value: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053" +} diff --git a/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json b/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json deleted file mode 100644 index d710d59055..0000000000 --- a/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by)\n SELECT $2, path, value, description, resource_type, extra_perms, edited_at, created_by\n FROM resource\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar" - ] - }, - "nullable": [] - }, - "hash": "748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2" -} diff --git a/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json b/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json new file mode 100644 index 0000000000..d6b261b56c --- /dev/null +++ b/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by)\n SELECT $2, path,\n CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent'\n AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of'\n THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text))\n ELSE value END,\n description, resource_type, extra_perms, edited_at, created_by\n FROM resource\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176" +} diff --git a/backend/migrations/20261015135223_agent_on_behalf_of.down.sql b/backend/migrations/20261015135223_agent_on_behalf_of.down.sql new file mode 100644 index 0000000000..62cbe2e5de --- /dev/null +++ b/backend/migrations/20261015135223_agent_on_behalf_of.down.sql @@ -0,0 +1 @@ +-- Nothing to undo: older versions ignore both keys, and clearing them would drop toggles set since. diff --git a/backend/migrations/20261015135223_agent_on_behalf_of.up.sql b/backend/migrations/20261015135223_agent_on_behalf_of.up.sql new file mode 100644 index 0000000000..fce313d09a --- /dev/null +++ b/backend/migrations/20261015135223_agent_on_behalf_of.up.sql @@ -0,0 +1,19 @@ +-- An AI agent's `run_on_behalf_of` makes runs from its page take the identity in its +-- `on_behalf_of`, which the server resolves on every write. Before this, both keys were ordinary +-- JSON any writer of the agent could set, so a value written then could name someone else's +-- identity unchecked: clear them, and every agent starts with the toggle off. +UPDATE resource + SET value = value - 'on_behalf_of' - 'run_on_behalf_of' + WHERE resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' + AND (value ? 'on_behalf_of' OR value ? 'run_on_behalf_of'); + +-- A deleted agent comes back from the trash as stored, so its copy there is cleared too. +UPDATE trashbin + SET item_data = jsonb_set(item_data, '{row,value}', + (item_data->'row'->'value') - 'on_behalf_of' - 'run_on_behalf_of') + WHERE item_kind = 'resource' + AND item_data->'row'->>'resource_type' = 'ai_agent' + AND jsonb_typeof(item_data->'row'->'value') = 'object' + AND (item_data->'row'->'value' ? 'on_behalf_of' + OR item_data->'row'->'value' ? 'run_on_behalf_of'); diff --git a/backend/tests/flow_conversation_running_turn.rs b/backend/tests/flow_conversation_running_turn.rs index 392ff6f5cf..db8cf4d956 100644 --- a/backend/tests/flow_conversation_running_turn.rs +++ b/backend/tests/flow_conversation_running_turn.rs @@ -16,9 +16,17 @@ const CONV: Uuid = Uuid::from_u128(0x5eed); /// Takes the conversation for a turn, as a run does, without keeping what it writes. async fn take_conversation(db: &Pool) -> windmill_common::error::Result { let mut tx = db.begin().await?; - let result = - get_or_create_conversation_with_id(&mut tx, WS, "f/flow", "test-user", "t", CONV, false) - .await; + let result = get_or_create_conversation_with_id( + &mut tx, + WS, + "f/flow", + "test-user", + false, + "t", + CONV, + false, + ) + .await; tx.rollback().await?; result.map(|c| c.id) } diff --git a/backend/tests/v2_job_delete_orphans.rs b/backend/tests/v2_job_delete_orphans.rs index 45029f024d..fa621fb2a2 100644 --- a/backend/tests/v2_job_delete_orphans.rs +++ b/backend/tests/v2_job_delete_orphans.rs @@ -325,6 +325,7 @@ async fn test_new_turns_wait_for_conversation_cleanup_and_recreate( WS, "f/flow", "test-user", + false, "hi again", conv_id, false, diff --git a/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs new file mode 100644 index 0000000000..628614056c --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs @@ -0,0 +1,216 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const AGENT: &str = "u/test-user-3/agent"; + +async fn post( + base_url: &str, + token: &str, + route: &str, + body: serde_json::Value, +) -> anyhow::Result<(u16, String)> { + let resp = reqwest::Client::new() + .post(format!("{base_url}/w/test-workspace/{route}")) + .header("Authorization", format!("Bearer {token}")) + .json(&body) + .send() + .await?; + Ok((resp.status().as_u16(), resp.text().await?)) +} + +async fn agent_identity(db: &Pool) -> anyhow::Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT value->>'on_behalf_of' FROM resource + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .fetch_one(db) + .await?) +} + +async fn job_identity(db: &Pool, id: &str) -> anyhow::Result<(String, String)> { + Ok( + sqlx::query_as("SELECT permissioned_as, created_by FROM v2_job WHERE id = $1::uuid") + .bind(id) + .fetch_one(db) + .await?, + ) +} + +/// The identity an agent runs as is in its value, which anyone who can write the agent writes: it +/// is kept only for an admin asking to keep it, and every other write makes it the writer's own, +/// so a writer cannot change what runs while it keeps running as someone else. It exists only +/// while the agent opts into running as it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_write_resets_identity(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + let value = json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-2", + "run_on_behalf_of": true }); + + let (status, body) = post( + &base_url, + "SECRET_TOKEN", + "resources/create", + json!({ "path": AGENT, "resource_type": "ai_agent", "value": value, + "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "create: {status} {body}"); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/test-user-2")); + + // The agent's owner, not an admin, asking to keep it. + let (status, body) = post( + &base_url, + "SECRET_TOKEN_3", + &format!("resources/update/{AGENT}"), + json!({ "value": value, "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "update: {status} {body}"); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/test-user-3")); + + let mut off = value.clone(); + off["run_on_behalf_of"] = json!(false); + let (status, body) = post( + &base_url, + "SECRET_TOKEN", + &format!("resources/update/{AGENT}"), + json!({ "value": off, "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "toggle off: {status} {body}"); + assert_eq!(agent_identity(&db).await?, None); + + Ok(()) +} + +/// Reading an agent is what allows running it. The run is the caller's unless the agent opts into +/// running as its identity: then `test-user-2`, a plain member, runs as `test-user-3`. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_run_identity_and_needs_read(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', $1, $2, 'ai_agent', '{}', 'test-user-3')", + ) + .bind(AGENT) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-3" })) + .execute(&db) + .await?; + + let run = format!("jobs/run/agent/{AGENT}"); + let (status, body) = post(&base_url, "SECRET_TOKEN_2", &run, json!({})).await?; + assert_eq!(status, 404, "an unreadable agent: {body}"); + + sqlx::query( + "UPDATE resource SET extra_perms = '{\"u/test-user-2\": false}' + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .execute(&db) + .await?; + let (status, body) = post( + &base_url, + "SECRET_TOKEN_2", + &run, + json!({ "user_message": "hi" }), + ) + .await?; + assert_eq!(status, 201, "a readable agent: {body}"); + assert_eq!( + job_identity(&db, &body).await?, + ("u/test-user-2".into(), "test-user-2".into()) + ); + + sqlx::query( + "UPDATE resource SET value = value || '{\"run_on_behalf_of\": true}' + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .execute(&db) + .await?; + let (status, body) = post( + &base_url, + "SECRET_TOKEN_2", + &run, + json!({ "user_message": "hi" }), + ) + .await?; + assert_eq!(status, 201, "an agent run on behalf of: {body}"); + assert_eq!( + job_identity(&db, &body).await?, + ("u/test-user-3".into(), "test-user-2".into()) + ); + + // The worker would resolve it with the identity's token, however the JSON spells the `$`. + for raw in [ + r#"{"user_message":"$var:u/test-user-3/secret"}"#, + r#"{"user_message":"\u0024var:u/test-user-3/secret"}"#, + ] { + let resp = reqwest::Client::new() + .post(format!("{base_url}/w/test-workspace/{run}")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .header("Content-Type", "application/json") + .body(raw) + .send() + .await?; + assert_eq!(resp.status().as_u16(), 400, "a reference in {raw}"); + } + + // The run takes its conversation outside the caller's row policy, so a reader must not + // continue another user's conversation; an admin still may, as the policy allows. + let chat = format!("{run}?memory_id=7d3f6a52-1c4e-4b8a-9f2d-0e5c6b7a8d91"); + let msg = json!({ "user_message": "hi" }); + let (status, body) = post(&base_url, "SECRET_TOKEN_3", &chat, msg.clone()).await?; + assert_eq!(status, 201, "the owner starts it: {body}"); + let (status, body) = post(&base_url, "SECRET_TOKEN_2", &chat, msg.clone()).await?; + assert_eq!(status, 400, "another reader: {body}"); + assert!(body.contains("another user"), "{body}"); + let (status, body) = post(&base_url, "SECRET_TOKEN", &chat, msg).await?; + assert_eq!( + status, 409, + "an admin passes ownership, held only by the running turn: {body}" + ); + + Ok(()) +} + +/// The identity is a username inside the value, so renaming the user has to move it there too. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_identity_follows_user_rename(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ('test-workspace', $1, $2, 'ai_agent', 'test-user-3')", + ) + .bind(AGENT) + .bind(json!({ "run_on_behalf_of": true, "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; + let email: String = + sqlx::query_scalar("SELECT email FROM usr WHERE username = 'test-user-2' LIMIT 1") + .fetch_one(&db) + .await?; + + let resp = reqwest::Client::new() + .post(format!("{base_url}/users/rename/{email}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ "new_username": "renamed" })) + .send() + .await?; + let status = resp.status().as_u16(); + assert_eq!(status, 200, "rename: {}", resp.text().await?); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/renamed")); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/agent_runs.rs b/backend/windmill-api-integration-tests/tests/agent_runs.rs deleted file mode 100644 index b0302187cb..0000000000 --- a/backend/windmill-api-integration-tests/tests/agent_runs.rs +++ /dev/null @@ -1,60 +0,0 @@ -use serde_json::json; -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -const AGENT: &str = "u/test-user-3/agent"; - -async fn run(base_url: &str, token: &str) -> anyhow::Result<(u16, String)> { - let resp = reqwest::Client::new() - .post(format!( - "{base_url}/w/test-workspace/jobs/run/agent/{AGENT}" - )) - .header("Authorization", format!("Bearer {token}")) - .json(&json!({ "user_message": "hi" })) - .send() - .await?; - Ok((resp.status().as_u16(), resp.text().await?)) -} - -/// Reading an agent is what allows running it, and the run is the caller's own: `test-user-2`, a -/// plain member, runs `test-user-3`'s agent once it may read it, lending nobody's permissions. -#[sqlx::test(migrations = "../migrations", fixtures("base"))] -async fn test_agent_run_needs_read_and_runs_as_caller(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - let server = ApiServer::start(db.clone()).await?; - let base_url = format!("http://localhost:{}/api", server.addr.port()); - - sqlx::query( - "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) - VALUES ('test-workspace', $1, $2, 'ai_agent', '{}', 'test-user-3')", - ) - .bind(AGENT) - .bind(json!({ "system_prompt": "hi" })) - .execute(&db) - .await?; - - let (status, body) = run(&base_url, "SECRET_TOKEN_2").await?; - assert_eq!(status, 404, "an unreadable agent: {body}"); - - sqlx::query( - "UPDATE resource SET extra_perms = '{\"u/test-user-2\": false}' - WHERE workspace_id = 'test-workspace' AND path = $1", - ) - .bind(AGENT) - .execute(&db) - .await?; - let (status, body) = run(&base_url, "SECRET_TOKEN_2").await?; - assert_eq!(status, 201, "a readable agent: {body}"); - - let (permissioned_as, created_by) = sqlx::query_as::<_, (String, String)>( - "SELECT permissioned_as, created_by FROM v2_job WHERE id = $1::uuid", - ) - .bind(&body) - .fetch_one(&db) - .await?; - assert_eq!(permissioned_as, "u/test-user-2"); - assert_eq!(created_by, "test-user-2"); - - Ok(()) -} diff --git a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs index bc6c10f1ee..10fc0a8028 100644 --- a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs @@ -62,14 +62,31 @@ async fn fork_with_public_app( /// An app policy's `on_behalf_of` is the identity anonymous and publisher executions queue jobs /// under, and the fork's endpoint outlives any revocation in the parent — so a creator who may -/// not preserve someone else's identity must not receive one by forking. `test-user-2` is a -/// plain member of the parent. +/// not preserve someone else's identity must not receive one by forking. The same goes for the +/// one an agent's value carries. `test-user-2` is a plain member of the parent. #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_fork_repoints_app_identity_for_unprivileged_creator( db: Pool, ) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/agent', $1, 'ai_agent', '{}', 'test-user')", + ) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user" })) + .execute(&db) + .await?; let (policy, custom_path) = fork_with_public_app(&db, "SECRET_TOKEN_2").await?; + assert_eq!( + sqlx::query_scalar::<_, String>( + "SELECT value->>'on_behalf_of' FROM resource + WHERE workspace_id = 'wm-fork-app' AND path = 'u/test-user/agent'" + ) + .fetch_one(&db) + .await?, + "u/test-user-2" + ); + assert_eq!(policy["on_behalf_of"], json!("u/test-user-2")); assert_eq!(policy["on_behalf_of_email"], json!("test2@windmill.dev")); // `execution_mode` rides along untouched — see `clone_apps`. @@ -312,8 +329,9 @@ async fn test_fork_keeps_only_resolvable_on_behalf_of(db: Pool) -> any Ok(()) } -/// Apps, schedules, triggers and their drafts cannot drop an identity the way scripts and flows -/// do, so one naming nobody in the fork goes to its creator while one that still resolves stays. +/// Apps, agents, schedules, triggers and their drafts cannot drop an identity the way scripts and +/// flows do, so one naming nobody in the fork goes to its creator while one that still resolves +/// stays. /// Forked as an admin, whose app policies the clone otherwise keeps. #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyhow::Result<()> { @@ -367,6 +385,13 @@ async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyho )) .execute(&db) .await?; + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/stranger', $1, 'ai_agent', '{}', 'test-user')", + ) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; sqlx::query( "INSERT INTO schedule (workspace_id, path, edited_by, schedule, script_path, email, permissioned_as, enabled) VALUES ('test-workspace', 'u/test-user/stranger', 'test-user', '0 0 * * * *', 'u/test-user/s', 'test2@windmill.dev', 'u/test-user-2', false)", @@ -424,6 +449,10 @@ async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyho text("SELECT value->>'permissioned_as' FROM draft WHERE workspace_id = 'wm-fork-repoint' AND typ = 'trigger_websocket'").await?, "u/test-user" ); + assert_eq!( + text("SELECT value->>'on_behalf_of' FROM resource WHERE workspace_id = 'wm-fork-repoint' AND path = 'u/test-user/stranger'").await?, + "u/test-user" + ); assert_eq!( text("SELECT permissioned_as || ' ' || email FROM schedule WHERE workspace_id = 'wm-fork-repoint'").await?, "u/test-user test@windmill.dev" diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index 7bdeab924b..8dc8079096 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -90,6 +90,25 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .execute(&db) .await?; + // An agent records who it runs as inside its value, on a path the user does not own. + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ('test-workspace', 'f/shared/agent', $1, 'ai_agent', 'test-user')", + ) + .bind(json!({ "run_on_behalf_of": true, "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; + let preview: serde_json::Value = + authed(client().get(ws_url(port, "offboard_preview/test-user-2"))) + .send() + .await? + .json() + .await?; + assert_eq!( + preview["executing_on_behalf"]["resources"], + json!(["f/shared/agent"]) + ); + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) .json(&json!({ "reassign_to": "u/test-user", @@ -100,6 +119,14 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .await?; assert_eq!(resp.status(), 200); + let agent_obo: Option = sqlx::query_scalar( + "SELECT value->>'on_behalf_of' FROM resource + WHERE path = 'f/shared/agent' AND workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!(agent_obo.as_deref(), Some("u/test-user")); + let body: serde_json::Value = resp.json().await?; assert!(body["conflicts"].as_array().map_or(true, |a| a.is_empty())); assert!(body["summary"].is_object()); @@ -117,7 +144,10 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .fetch_one(&db) .await?; assert_eq!( - (obo.on_behalf_of.as_deref(), obo.on_behalf_of_email.as_deref()), + ( + obo.on_behalf_of.as_deref(), + obo.on_behalf_of_email.as_deref() + ), (Some("u/test-user"), Some("test@windmill.dev")), "the reassignment moves the whole identity, not just the half this release reads" ); diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index 330e96c2fb..da77acbf7c 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -946,6 +946,7 @@ pub async fn handle_chat_conversation_messages( w_id, flow_path, &authed.username, + authed.is_admin, &user_message, memory_id, is_test, diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 46bd6825e8..9c853d8ef8 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -2120,6 +2120,15 @@ async fn change_user_email( .execute(&mut *tx) .await?; + sqlx::query( + "UPDATE resource SET value = jsonb_set(value, '{on_behalf_of}', to_jsonb($1::text)) + WHERE resource_type = 'ai_agent' AND value->>'on_behalf_of' = $2", + ) + .bind(&new_principal) + .bind(&old_principal) + .execute(&mut *tx) + .await?; + sqlx::query!( "UPDATE script SET on_behalf_of = $1 WHERE on_behalf_of = $2", &new_principal, diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 6443bf7e2a..aa0dc764ec 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -7130,7 +7130,7 @@ async fn clone_workspace_data( clone_resource_types(tx, source_workspace_id, target_workspace_id).await?; // Clone resources - clone_resources(tx, source_workspace_id, target_workspace_id).await?; + clone_resources(tx, source_workspace_id, target_workspace_id, authed).await?; // Clone variables (including external secret backend replication) clone_variables(tx, db, source_workspace_id, target_workspace_id).await?; @@ -7667,18 +7667,30 @@ async fn clone_resource_types( Ok(()) } +/// An agent's value carries the identity it runs as, re-pointed at the fork's creator when they +/// may not preserve someone else's, as `clone_apps` does an app's policy. The rest is swept by +/// `repoint_unresolvable_cloned_identities` once the fork's membership is final. async fn clone_resources( tx: &mut Transaction<'_, Postgres>, source_workspace_id: &str, target_workspace_id: &str, + authed: &ApiAuthed, ) -> Result<()> { + let repoint = (!windmill_common::can_preserve_on_behalf_of(authed)) + .then(|| username_to_permissioned_as(&authed.username)); sqlx::query!( "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by) - SELECT $2, path, value, description, resource_type, extra_perms, edited_at, created_by + SELECT $2, path, + CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of' + THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text)) + ELSE value END, + description, resource_type, extra_perms, edited_at, created_by FROM resource WHERE workspace_id = $1", source_workspace_id, target_workspace_id, + repoint, ) .execute(&mut **tx) .await?; @@ -8165,6 +8177,18 @@ async fn repoint_unresolvable_cloned_identities( .await?; } + sqlx::query(&format!( + "UPDATE resource SET value = jsonb_set(value, '{{on_behalf_of}}', to_jsonb($2::text)) + WHERE workspace_id = $1 AND resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of' + AND NOT ({})", + principal_resolves_sql("(value->>'on_behalf_of')") + )) + .bind(target_workspace_id) + .bind(&principal) + .execute(&mut **tx) + .await?; + // `email` is still written for workers that predate `permissioned_as`. sqlx::query(&format!( "UPDATE schedule SET permissioned_as = $2, email = $3 @@ -13941,17 +13965,18 @@ async fn compare_two_flows( }); } -/// The policy minus the identity pair. Deploying cannot converge a difference there — the -/// target recomputes the identity from the deployer's own choice, which offers its current -/// value, the deployer, or a typed-in one, never the source's — so listing an app for it -/// alone leaves an entry no deploy can clear. `script` and `flow` compare no identity either. -fn policy_without_identity(policy: &serde_json::Value) -> serde_json::Value { - let mut policy = policy.clone(); - if let Some(obj) = policy.as_object_mut() { +/// An app's policy or an agent's value minus the identity it carries. Deploying cannot converge +/// a difference there — the target recomputes the identity from the deployer's own choice, which +/// offers its current value, the deployer, or a typed-in one, never the source's — so listing an +/// item for it alone leaves an entry no deploy can clear. `script` and `flow` compare no identity +/// either. +fn without_identity(value: &serde_json::Value) -> serde_json::Value { + let mut value = value.clone(); + if let Some(obj) = value.as_object_mut() { obj.remove("on_behalf_of"); obj.remove("on_behalf_of_email"); } - policy + value } async fn compare_two_apps( @@ -13994,7 +14019,7 @@ async fn compare_two_apps( // Check metadata and content differences if let (Some(source), Some(target)) = (&source_app, &target_app) { if source.summary != target.summary - || policy_without_identity(&source.policy) != policy_without_identity(&target.policy) + || without_identity(&source.policy) != without_identity(&target.policy) || source.value != target.value || source.raw_app != target.raw_app { @@ -14072,7 +14097,14 @@ async fn compare_two_resources( // Check metadata differences if let (Some(source), Some(target)) = (&source_resource, &target_resource) { - if source.value != target.value + let agent = source.resource_type == "ai_agent" && target.resource_type == "ai_agent"; + let values_differ = if agent { + source.value.as_ref().map(without_identity) + != target.value.as_ref().map(without_identity) + } else { + source.value != target.value + }; + if values_differ || source.description != target.description || source.resource_type != target.resource_type { diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index d07e036e15..ef23328cb9 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -16783,8 +16783,9 @@ paths: summary: run a saved AI agent description: | Runs the `ai_agent` resource at `path` as stored, for any caller who can read it - (operators included), as the caller, who needs access to the agent's AI resource and to - whatever its tools use. With `memory_id`, the run is a turn + (operators included). The run is the caller's, or the agent's `on_behalf_of` when its + `run_on_behalf_of` is set; the caller's inputs may then not reference variables or + resources. With `memory_id`, the run is a turn of the caller's conversation with the agent; without, a single run. operationId: runAgent tags: @@ -32686,6 +32687,9 @@ components: type: string ws_specific: type: boolean + preserve_on_behalf_of: + type: boolean + description: ai_agent only. Keep the identity `value.on_behalf_of` names (`u/`, `g/`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller. required: - path - value @@ -32710,6 +32714,9 @@ components: type: string ws_specific: type: boolean + preserve_on_behalf_of: + type: boolean + description: ai_agent only. Keep the identity `value.on_behalf_of` names (`u/`, `g/`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller. Resource: type: object diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index 76f729e7e0..ebd83a52a5 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -2,8 +2,9 @@ //! //! The run is built here from the stored agent rather than sent by the client, which is what lets //! anyone who can read the agent run it, operators included, the way a deployed flow runs by path: -//! a preview takes arbitrary code, this takes only the run's inputs. It runs as the caller, who -//! needs access to the agent's AI resource and to whatever its tools use. +//! a preview takes arbitrary code, this takes only the run's inputs. It runs as the caller, or as +//! the agent's `on_behalf_of` when its `run_on_behalf_of` is set; the server resolves +//! `on_behalf_of` on every write of the agent. use std::collections::HashMap; @@ -20,13 +21,16 @@ use windmill_common::{ jobs::JobPayload, users::username_to_permissioned_as, utils::{not_found_if_none, StripPath}, + variables::arg_needs_interpolation, }; use windmill_queue::{push, PushArgs, PushIsolationLevel}; use crate::ai_evals::run::config_to_draft; use crate::ai_evals::subject::AgentDraft; use crate::db::{ApiAuthed, DB}; -use crate::jobs::{handle_chat_conversation_messages, set_flow_memory_id, RunJobQuery}; +use crate::jobs::{ + handle_chat_conversation_messages, run_end_user_email, set_flow_memory_id, RunJobQuery, +}; /// The id the agent's step carries in the run, as the editor's chat names it. A token scoped to /// `jobs:run:agents:` reads its runs back by it (`require_job_within_read_scope`). @@ -59,11 +63,20 @@ pub(crate) async fn run_agent( .fetch_optional(&mut *tx) .await?; tx.commit().await?; - let Some(sqlx::types::Json(value)) = not_found_if_none(value, "Agent", path)? else { + let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { return Err(Error::BadRequest(format!( "Agent {path} has no configuration" ))); }; + // Who the agent runs as, not one of its inputs: its identity when it opts in, as a deployed + // flow does. + let obj = value.as_object_mut(); + let (agent_obo, run_obo) = obj + .map(|o| (o.remove("on_behalf_of"), o.remove("run_on_behalf_of"))) + .unwrap_or_default(); + let agent_obo = agent_obo + .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) + .and_then(|v| v.as_str().map(str::to_string)); let config = config_to_draft(value)?; // A chat turn is filed where the agent's chat lists its conversations, which a flow cannot @@ -83,11 +96,47 @@ pub(crate) async fn run_agent( &["memory_id", "previous_messages"], )?; - let push_authed = authed.clone().into(); + let on_behalf_of = + windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), &w_id, &db) + .await?; + // As `run_flow` picks the identity of a deployed flow: the agent's own when it has one, the + // caller's otherwise, which lends nobody's permissions. + let (email, permissioned_as, push_authed, isolation) = if let Some(obo) = on_behalf_of.as_ref() + { + ( + &obo.email, + obo.permissioned_as.clone(), + None, + PushIsolationLevel::IsolatedRoot(db.clone()), + ) + } else { + ( + &authed.email, + username_to_permissioned_as(&authed.username), + Some(authed.clone().into()), + PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()), + ) + }; + if let Some(obo) = on_behalf_of.as_ref() { + // The worker would interpolate such an input with the job's token, which is the + // identity's. Checked on the decoded value: the raw JSON can spell `$` as `\u0024`. + if args.values().any(|v| { + serde_json::from_str::(v.get()) + .is_ok_and(|v| arg_needs_interpolation(&v.to_string())) + }) { + return Err(Error::BadRequest(format!( + "Agent {path} runs on behalf of {}, so its inputs cannot reference variables or resources", + obo.permissioned_as + ))); + } + #[cfg(all(feature = "parquet", feature = "private"))] + check_attachments_readable(&db, &authed, &w_id, &args).await?; + } let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?; + let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?; let (uuid, mut tx) = push( &db, - PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()), + isolation, &w_id, JobPayload::RawFlow { value: flow_value, @@ -96,8 +145,8 @@ pub(crate) async fn run_agent( }, PushArgs::from(&args), authed.display_username(), - &authed.email, - username_to_permissioned_as(&authed.username), + email, + permissioned_as, authed.token_prefix.as_deref(), authed.username_override.as_deref(), None, @@ -114,9 +163,9 @@ pub(crate) async fn run_agent( None, None, None, - Some(&push_authed), + push_authed.as_ref(), false, - None, + end_user_email, authed.trigger_or_fallback(None), None, scope_ceiling.as_deref(), @@ -127,7 +176,8 @@ pub(crate) async fn run_agent( set_flow_memory_id(&mut tx, uuid, memory_id).await?; } if chat { - // A real conversation, not a test one: this is the agent as deployed, not a draft. + // The caller's conversation, whoever the agent runs as, and a real one: this is the + // agent as deployed, not a draft under test. handle_chat_conversation_messages( &mut tx, &authed, @@ -146,6 +196,50 @@ pub(crate) async fn run_agent( Ok((StatusCode::CREATED, uuid.to_string())) } +/// The step fetches the message's files with its job's token, so a run as the agent's identity +/// would read any file that identity can: a caller attaches only what they could download +/// themselves, checked as `sign_s3_objects` checks a key before signing it. +#[cfg(all(feature = "parquet", feature = "private"))] +async fn check_attachments_readable( + db: &DB, + authed: &ApiAuthed, + w_id: &str, + args: &HashMap>, +) -> Result<()> { + use crate::job_helpers_oss::{ + get_large_file_storage, get_workspace_s3_resource_and_check_paths, + }; + use windmill_common::db::DbWithOptAuthed; + use windmill_types::s3::{S3Object, S3Permission}; + + let Some(raw) = args.get("user_attachments") else { + return Ok(()); + }; + let attachments: Option> = serde_json::from_str(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))?; + for attachment in attachments.iter().flatten().filter(|a| !a.s3.is_empty()) { + // The path check is skipped, not failed, when the storage does not resolve. + if get_large_file_storage(db, w_id, attachment.storage.clone()) + .await? + .is_none() + { + return Err(windmill_object_store::workspace_storage_not_found( + attachment.storage.as_deref(), + )); + } + get_workspace_s3_resource_and_check_paths( + &DbWithOptAuthed::from_authed(authed, db.clone(), None), + Some(authed), + w_id, + attachment.storage.clone(), + &[(&attachment.s3, S3Permission::READ)], + None, + ) + .await?; + } + Ok(()) +} + /// The agent as a one-step flow, validated by deserializing through `FlowValue` rather than /// trusted as raw JSON. Its own transforms are the step's, minus `without`, and the run's inputs /// supply the message and the attachments over the top. Always inlined, never a link to the diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index b7f83dfd96..cc77f2bdbd 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -266,6 +266,17 @@ async fn get_offboard_preview( departing.as_deref(), &user_prefix, w_id ).fetch_all(db).await?; + // An agent's identity sits in its value, under any path, the user's own included: those + // move with the path but keep running as the departing user until re-pointed. + let obo_agents: Vec = sqlx::query_scalar( + "SELECT path FROM resource WHERE resource_type = 'ai_agent' + AND value->>'on_behalf_of' = $1 AND workspace_id = $2", + ) + .bind(departing.as_deref()) + .bind(w_id) + .fetch_all(db) + .await?; + let obo_schedules = sqlx::query_scalar!( "SELECT path FROM schedule WHERE permissioned_as = $1 AND NOT path LIKE $2 AND workspace_id = $3", &user_owner, &user_prefix, w_id @@ -354,6 +365,7 @@ async fn get_offboard_preview( scripts: obo_scripts, flows: obo_flows, apps: obo_apps, + resources: obo_agents, schedules: obo_schedules, triggers: obo_triggers, ..Default::default() @@ -1007,6 +1019,16 @@ async fn offboard_user_from_workspace<'c>( .await? .unwrap_or(0); + sqlx::query( + "UPDATE resource SET value = jsonb_set(value, '{on_behalf_of}', to_jsonb($1::text)) + WHERE resource_type = 'ai_agent' AND value->>'on_behalf_of' = $2 AND workspace_id = $3", + ) + .bind(new_permissioned_as) + .bind(departing.as_deref()) + .bind(w_id) + .execute(&mut **tx) + .await?; + // ---- eval datasets ---- // The foreign keys cascade the rename onto cases and experiments; the paths held inside JSONB // (an experiment's subject, a dataset's scorers) are rewritten separately since the cascade diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 5b26cf57b8..9d59a85dee 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -297,8 +297,21 @@ async fn rename_user( // keeps a like-named member of some other workspace out of it. if let Some(old_username) = old_instance_username.filter(|u| *u != ru.new_username) { let old_principal = windmill_common::users::username_to_permissioned_as(&old_username); - let new_principal = - windmill_common::users::username_to_permissioned_as(&ru.new_username); + let new_principal = windmill_common::users::username_to_permissioned_as(&ru.new_username); + // An agent records no address, so a workspace where the name is a member's own is + // left to the per-workspace sweep: there the principal is that member. + sqlx::query( + "UPDATE resource SET value = jsonb_set(value, '{on_behalf_of}', to_jsonb($1::text)) + WHERE resource_type = 'ai_agent' AND value->>'on_behalf_of' = $2 + AND NOT EXISTS (SELECT 1 FROM usr + WHERE usr.workspace_id = resource.workspace_id + AND usr.username = $3)", + ) + .bind(&new_principal) + .bind(&old_principal) + .bind(&old_username) + .execute(&mut *tx) + .await?; sqlx::query!( "UPDATE app SET policy = jsonb_set(policy, ARRAY['on_behalf_of'], to_jsonb($1::text)) WHERE policy->>'on_behalf_of' = $2 AND policy->>'on_behalf_of_email' = $3", @@ -817,6 +830,17 @@ async fn update_username_in_workpsace<'c>( .execute(&mut **tx) .await?; + sqlx::query( + "UPDATE resource SET value = jsonb_set(value, '{on_behalf_of}', to_jsonb('u/' || $1)) + WHERE resource_type = 'ai_agent' AND value->>'on_behalf_of' = ('u/' || $2) + AND workspace_id = $3", + ) + .bind(new_username) + .bind(old_username) + .bind(w_id) + .execute(&mut **tx) + .await?; + // An app draft carries a copy of the deployed policy, so the rename must reach it // there too — same reason as the script/flow draft sweep above. sqlx::query!( diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index bff261093a..39227e49ee 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -894,7 +894,14 @@ pub(crate) async fn tarball_workspace( .fetch_all(&mut *tx) .await?; - for resource in resources { + for mut resource in resources { + // An agent's identity belongs to this workspace, and whoever writes it elsewhere gets + // their own, as `to_string_without_metadata` leaves out a flow's. + if resource.resource_type == "ai_agent" { + if let Some(obj) = resource.value.as_mut().and_then(|v| v.as_object_mut()) { + obj.remove("on_behalf_of"); + } + } let resource_str = &to_string_without_metadata(&resource, ExtraPermsBehavior::Drop, None).unwrap(); archive diff --git a/backend/windmill-common/src/flow_conversations.rs b/backend/windmill-common/src/flow_conversations.rs index bde4d5ccce..571877ead2 100644 --- a/backend/windmill-common/src/flow_conversations.rs +++ b/backend/windmill-common/src/flow_conversations.rs @@ -64,12 +64,13 @@ pub async fn get_or_create_conversation_with_id( w_id: &str, flow_path: &str, username: &str, + is_admin: bool, title: &str, conversation_id: Uuid, is_test: bool, ) -> Result { if let Some(existing) = lock_conversation(tx, w_id, conversation_id).await? { - let existing = same_kind(existing, is_test)?; + let existing = same_kind(owned(existing, username, is_admin)?, is_test)?; refuse_running_turn(tx, conversation_id).await?; return Ok(existing); } @@ -106,7 +107,7 @@ pub async fn get_or_create_conversation_with_id( "conversation {conversation_id} belongs to another workspace" )) })?; - let existing = same_kind(existing, is_test)?; + let existing = same_kind(owned(existing, username, is_admin)?, is_test)?; refuse_running_turn(tx, conversation_id).await?; Ok(existing) } @@ -176,6 +177,19 @@ pub async fn running_turns<'e, E: sqlx::PgExecutor<'e>>( .collect()) } +/// The `see_own` policy on `flow_conversation`, for a turn whose transaction bypasses it: a run +/// as a flow's or agent's `on_behalf_of` takes the conversation in a root transaction, and must +/// not continue, or read the memory of, another user's conversation. +fn owned(existing: FlowConversation, username: &str, is_admin: bool) -> Result { + if is_admin || existing.created_by == username { + return Ok(existing); + } + Err(crate::error::Error::BadRequest(format!( + "conversation {} belongs to another user; start a new conversation", + existing.id + ))) +} + /// `memory_id` is the caller's to choose, so a preview run could name a deployed /// conversation and the reverse. A conversation's kind is fixed at creation and nothing /// would show the mixing afterwards, so the turn is refused before it starts. diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index ac9c43269a..f3ad826136 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -23,6 +23,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; lazy_static::lazy_static! { pub static ref SECRET_SALT: Option = std::env::var("SECRET_SALT").ok(); static ref RESERVED_WM_VAR_NAME: regex::Regex = regex::Regex::new(r"^WM_[A-Z_]+$").unwrap(); + static ref RE_RES_VAR: regex::Regex = + regex::Regex::new(r#"\$(?:var|jsonvar|res|encrypted)\:"#).unwrap(); +} + +/// Whether a job argument, as JSON text, holds a `$var:`/`$jsonvar:`/`$res:`/`$encrypted:` +/// reference, which makes the worker interpolate the whole argument with the job's token, +/// `$`-prefixed reserved variables included. +pub fn arg_needs_interpolation(json: &str) -> bool { + RE_RES_VAR.is_match(json) } /// Escape a string so it can be safely embedded inside a single-quoted JS diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 0940e91d98..059819a802 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -236,6 +236,10 @@ pub struct CreateResource { pub labels: Option>, #[serde(default)] pub ws_specific: Option, + /// `ai_agent` only: keep the identity `value.on_behalf_of` names, for a caller allowed to + /// (see `resolve_agent_on_behalf_of`). + #[serde(default)] + pub preserve_on_behalf_of: Option, } #[derive(Deserialize)] struct EditResource { @@ -245,6 +249,7 @@ struct EditResource { resource_type: Option, labels: Option>, ws_specific: Option, + preserve_on_behalf_of: Option, } #[derive(Deserialize)] @@ -1254,7 +1259,20 @@ async fn create_resource( check_path_conflict(&mut tx, &w_id, &resource.path).await?; } - let res_value = resource.value.unwrap_or_default(); + let mut res_value = resource.value.unwrap_or_default(); + if resource.resource_type == "ai_agent" { + res_value = resolve_agent_raw_value( + &mut tx, + &authed, + &db, + &w_id, + &resource.path, + &res_value, + resource.preserve_on_behalf_of.unwrap_or(false), + true, + ) + .await?; + } let raw_json = sqlx::types::Json(res_value.as_ref()); if resource.path.starts_with("f/app_themes/") { @@ -2095,9 +2113,6 @@ async fn update_resource( if let Some(npath) = &ns.path { sqlb.set_str("path", npath); } - if let Some(nvalue) = &ns.value { - sqlb.set_str("value", nvalue.to_string()); - } if let Some(nrt) = &ns.resource_type { sqlb.set_str("resource_type", nrt); } @@ -2205,6 +2220,49 @@ async fn update_resource( } } + lock_resource_row(&mut tx, &w_id, path).await?; + let current = sqlx::query!( + "SELECT resource_type, value AS \"value: sqlx::types::Json>\" + FROM resource WHERE workspace_id = $1 AND path = $2", + &w_id, + path + ) + .fetch_optional(&mut *tx) + .await?; + let resource_type = ns + .resource_type + .clone() + .or_else(|| current.as_ref().map(|c| c.resource_type.clone())); + // Retyping a resource into an agent makes its value an agent's, identity included, so it is + // resolved as a written one is. + let retyped = ns.resource_type.as_deref() == Some("ai_agent") + && current + .as_ref() + .is_some_and(|c| c.resource_type != "ai_agent"); + let nvalue = match &ns.value { + Some(v) => Some(v.clone()), + None if retyped => current.and_then(|c| c.value).map(|v| v.0), + None => None, + }; + if let Some(nvalue) = nvalue { + let nvalue = if resource_type.as_deref() == Some("ai_agent") { + resolve_agent_raw_value( + &mut tx, + &authed, + &db, + &w_id, + ns.path.as_deref().unwrap_or(path), + &nvalue, + ns.preserve_on_behalf_of.unwrap_or(false), + false, + ) + .await? + } else { + nvalue + }; + sqlb.set_str("value", nvalue.to_string()); + } + let sql = sqlb.sql().map_err(|e| Error::internal_err(e.to_string()))?; let npath_o: Option = sqlx::query_scalar(&sql) .fetch_optional(&mut *tx) @@ -2374,6 +2432,110 @@ async fn update_resource_value( Ok(format!("value of resource {} updated", path)) } +/// Rewrites the identity an `ai_agent` runs as (`value.on_behalf_of`), resolved on every write of +/// it as a flow's `on_behalf_of` is on every deploy. It exists only while the agent's +/// `run_on_behalf_of` is set: then the writer's own, unless one allowed to keep the one the value +/// names asks to, and a folder's default for a new agent. The value is written by anyone who can +/// write the agent, so the key it arrives with is only a request. +async fn resolve_agent_on_behalf_of( + tx: &mut Transaction<'_, Postgres>, + authed: &ApiAuthed, + db: &DB, + w_id: &str, + path: &str, + value: &mut serde_json::Value, + preserve: bool, + created: bool, +) -> Result<()> { + let Some(obj) = value.as_object_mut() else { + return Ok(()); + }; + let mut requested = obj + .remove("on_behalf_of") + .and_then(|v| v.as_str().map(str::to_string)); + if obj.get("run_on_behalf_of").and_then(|v| v.as_bool()) != Some(true) { + return Ok(()); + } + let mut preserve = preserve; + let explicit = + requested.is_some() && preserve && windmill_common::can_preserve_on_behalf_of(authed); + if created && !explicit && windmill_common::can_preserve_on_behalf_of(authed) { + if let Some((_, folder_default)) = + windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await? + { + requested = Some(folder_default); + preserve = true; + } + } + let own = windmill_common::users::username_to_permissioned_as(&authed.username); + // Nothing requested is the writer's own. + let resolved = windmill_common::resolve_on_behalf_of( + None, + Some(requested.as_deref().unwrap_or(&own)), + preserve, + authed, + w_id, + db, + ) + .await?; + if let Some(resolved) = resolved.as_ref() { + obj.insert("on_behalf_of".to_string(), resolved.clone().into()); + } + if let Some(kept) = windmill_common::check_on_behalf_of_preservation( + resolved.as_deref(), + preserve, + authed, + &own, + ) { + audit_log( + &mut **tx, + authed, + "resources.on_behalf_of", + if created { + ActionKind::Create + } else { + ActionKind::Update + }, + w_id, + Some(path), + Some([("on_behalf_of", kept.as_str())].into()), + ) + .await?; + } + Ok(()) +} + +/// Held until the write commits: whether a value is resolved as an agent's depends on the type +/// read after this, and a concurrent retype into an agent must not land between the two. +async fn lock_resource_row( + tx: &mut Transaction<'_, Postgres>, + w_id: &str, + path: &str, +) -> Result<()> { + sqlx::query("SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 FOR UPDATE") + .bind(w_id) + .bind(path) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// `resolve_agent_on_behalf_of` on a value as the request carried it. +async fn resolve_agent_raw_value( + tx: &mut Transaction<'_, Postgres>, + authed: &ApiAuthed, + db: &DB, + w_id: &str, + path: &str, + value: &RawValue, + preserve: bool, + created: bool, +) -> Result> { + let mut parsed: serde_json::Value = serde_json::from_str(value.get())?; + resolve_agent_on_behalf_of(tx, authed, db, w_id, path, &mut parsed, preserve, created).await?; + Ok(serde_json::value::to_raw_value(&parsed)?) +} + /// Write a resource's value and run everything that has to follow it: a version row, the audit /// entry, deployment metadata, the webhook, and dependent CI tests. Shared with version restore /// so a restored value is indistinguishable downstream from any other edit. @@ -2402,6 +2564,21 @@ async fn set_resource_value( let mut tx = user_db.clone().begin(authed).await?; + let mut value = value; + if let Some(v) = value.as_mut() { + lock_resource_row(&mut tx, w_id, path).await?; + let resource_type = sqlx::query_scalar!( + "SELECT resource_type FROM resource WHERE workspace_id = $1 AND path = $2", + w_id, + path + ) + .fetch_optional(&mut *tx) + .await?; + if resource_type.as_deref() == Some("ai_agent") { + resolve_agent_on_behalf_of(&mut tx, authed, db, w_id, path, v, false, false).await?; + } + } + // `RETURNING resource_type` rather than a second lookup: the advisory below has to know the // type to leave `state` and `cache` alone, and this statement already runs. let updated = sqlx::query_scalar!( diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index 9ff1815ad4..1a478292cb 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -19,6 +19,7 @@ use std::{collections::HashMap, sync::Arc, time::Duration}; use uuid::Uuid; use windmill_ai::{ai_types::OpenAIToolCall, query_builder::StreamEventSink, types::*}; use windmill_common::jobs::JobPayload; +use windmill_common::variables::arg_needs_interpolation; #[cfg(feature = "mcp")] use windmill_mcp::McpClient; @@ -153,6 +154,8 @@ pub async fn execute_tool_calls( final_events_str, ) .await?; + } else if tool.module.is_some() && interpolating_args(tool_call) { + refuse_tool_call(&mut ctx, tool_call, &mut messages, final_events_str).await?; } else if tool.module.is_some() { let mut batch = vec![(tool_call, tool)]; while let Some(next_call) = calls.peek() { @@ -168,6 +171,9 @@ pub async fn execute_tool_calls( }) else { break; }; + if interpolating_args(next_call) { + break; + } batch.push((calls.next().unwrap(), next_tool)); } execute_windmill_tools(&mut ctx, &batch, actions, &mut messages, final_events_str) @@ -189,6 +195,44 @@ pub async fn execute_tool_calls( Ok((messages, final_content, used_structured_output_tool)) } +/// Whether the model wrote an argument the tool's job would interpolate with the agent's token, +/// which may be an identity it runs on behalf of. Only the step's own input transforms may name +/// variables and resources; the model's arguments are text from whoever talks to it. +fn interpolating_args(tool_call: &OpenAIToolCall) -> bool { + serde_json::from_str::(&tool_call.function.arguments) + .is_ok_and(|v| arg_needs_interpolation(&v.to_string())) +} + +async fn refuse_tool_call( + ctx: &mut ToolExecutionContext<'_>, + tool_call: &OpenAIToolCall, + messages: &mut Vec, + final_events_str: &mut String, +) -> Result<(), Error> { + let error_msg = "Tool call refused: its arguments cannot reference variables or resources \ + ($var:, $jsonvar:, $res:, $encrypted:)" + .to_string(); + messages.push(OpenAIMessage { + role: "tool".to_string(), + content: Some(OpenAIContent::Text(error_msg.clone())), + tool_call_id: Some(tool_call.id.clone()), + ..Default::default() + }); + if let Some(stream_event_processor) = ctx.stream_event_processor { + let event = StreamingEvent::ToolResult { + call_id: tool_call.id.clone(), + function_name: tool_call.function.name.clone(), + result: error_msg.clone(), + success: false, + }; + stream_event_processor.send(event, final_events_str).await?; + } + let (content, extras) = windmill_tool_row(tool_call, false, &error_msg); + let agent_job_id = ctx.job.id; + add_tool_message_to_chat(ctx, Some(agent_job_id), &content, false, Some(extras)).await; + Ok(()) +} + /// Execute an MCP tool call async fn execute_mcp_tool_call( ctx: &mut ToolExecutionContext<'_>, @@ -618,10 +662,8 @@ async fn enqueue_windmill_tool( // narrows that further. windmill_common::scopes::intersect_job_token_scopes( ctx.job.job_token_scopes.as_deref(), - windmill_common::scopes::step_job_token_scopes( - tool_module.job_token_scopes.as_deref(), - ) - .as_deref(), + windmill_common::scopes::step_job_token_scopes(tool_module.job_token_scopes.as_deref()) + .as_deref(), ) .as_deref(), ) @@ -1051,7 +1093,7 @@ async fn add_tool_message_to_chat( #[cfg(test)] mod tests { - use super::{extract_ai_agent_output, windmill_tool_row}; + use super::{extract_ai_agent_output, interpolating_args, windmill_tool_row}; use serde_json::value::RawValue; use windmill_ai::ai_types::{OpenAIFunction, OpenAIToolCall}; @@ -1088,6 +1130,21 @@ mod tests { ); } + #[test] + fn a_model_written_reference_is_caught_however_it_is_spelled() { + let call = |arguments: &str| OpenAIToolCall { + id: "call_1".to_string(), + function: OpenAIFunction { name: "t".to_string(), arguments: arguments.to_string() }, + r#type: "function".to_string(), + extra_content: None, + }; + assert!(interpolating_args(&call(r#"{"x":"$var:u/a/s"}"#))); + assert!(interpolating_args(&call( + r#"{"x":{"y":["\u0024res:u/a/r"]}}"# + ))); + assert!(!interpolating_args(&call(r#"{"x":"$5 and var: 3"}"#))); + } + #[test] fn extracts_only_the_output_of_an_agent_result() { let envelope = RawValue::from_string( diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index 2fa9a7a5ff..63c5d8d647 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -13,6 +13,7 @@ use sqlx::types::Json; use sqlx::{Pool, Postgres}; use tokio::process::Command; use tokio::{fs::File, io::AsyncReadExt}; +use windmill_common::variables::arg_needs_interpolation; use windmill_common::flows::Step; use windmill_common::global_settings::NSJAIL_TMP_BACKING_DISK; @@ -173,15 +174,11 @@ pub async fn write_file_binary(dir: &str, path: &str, content: &[u8]) -> error:: Ok(file) } -lazy_static::lazy_static! { - static ref RE_RES_VAR: Regex = Regex::new(r#"\$(?:var|jsonvar|res|encrypted)\:"#).unwrap(); -} - /// Returns true if any value in `vs` contains a `$var:`/`$jsonvar:`/`$res:`/`$encrypted:` /// reference that would need interpolation by `transform_json`. Cheap pre-check that /// callers can use to skip the DB roundtrip + clone path when nothing requires resolution. pub(crate) fn map_needs_resolution(vs: &HashMap>) -> bool { - vs.values().any(|v| (*RE_RES_VAR).is_match(v.get())) + vs.values().any(|v| arg_needs_interpolation(v.get())) } pub async fn transform_json<'a>( @@ -194,7 +191,7 @@ pub async fn transform_json<'a>( let mut has_match = false; for (_, v) in vs { let inner_vs = v.get(); - if (*RE_RES_VAR).is_match(inner_vs) { + if arg_needs_interpolation(inner_vs) { has_match = true; break; } @@ -205,7 +202,7 @@ pub async fn transform_json<'a>( let mut r = HashMap::new(); for (k, v) in vs { let inner_vs = v.get(); - if (*RE_RES_VAR).is_match(inner_vs) { + if arg_needs_interpolation(inner_vs) { let value = serde_json::from_str(inner_vs).map_err(|e| { error::Error::internal_err(format!("Error while parsing inner arg: {e:#}")) })?; @@ -232,7 +229,7 @@ pub async fn transform_json_as_values<'a>( let mut r: HashMap = HashMap::new(); for (k, v) in vs { let inner_vs = v.get(); - if (*RE_RES_VAR).is_match(inner_vs) { + if arg_needs_interpolation(inner_vs) { let value = serde_json::from_str(inner_vs).map_err(|e| { error::Error::internal_err(format!("Error while parsing inner arg: {e:#}")) })?; diff --git a/cli/src/commands/resource/resource.ts b/cli/src/commands/resource/resource.ts index 7cef4caf1f..87c31b331a 100644 --- a/cli/src/commands/resource/resource.ts +++ b/cli/src/commands/resource/resource.ts @@ -20,6 +20,11 @@ import { Resource } from "../../../gen/types.gen.ts"; import { readInlinePathSync, readTextFile } from "../../utils/utils.ts"; import { isWorkspaceSpecificFile } from "../../core/specific_items.ts"; import { getCurrentGitBranch } from "../../utils/git.ts"; +import { + buildPermissionedAsContext, + type PermissionedAsContext, +} from "../../core/permissioned_as.ts"; +import { readEffectiveSyncBehavior } from "../../core/conf.ts"; export interface ResourceFile { value: any; @@ -83,6 +88,7 @@ export async function pushResource( // only round-trip the canonical layout); the standalone `resource push` // command pushes a single explicit file, where any pointer is fine. enforceCanonicalFileset?: boolean, + permissionedAsContext?: PermissionedAsContext, ): Promise { remotePath = removeType(remotePath, "resource"); try { @@ -93,6 +99,11 @@ export async function pushResource( } catch { // flow doesn't exist } + const claimed = agentOnBehalfOf( + resource, + localResource, + permissionedAsContext + ); // Helper function to resolve inline content const resolveInlineContent = async () => { @@ -133,11 +144,23 @@ export async function pushResource( // Only resolve inline content if we're actually updating await resolveInlineContent(); + if (claimed) { + log.info(`Preserving ${claimed} as permissioned_as for agent ${remotePath}`); + } await wmill.updateResource({ workspace: workspace, path: remotePath.replaceAll(SEP, "/"), - requestBody: { ...localResource, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}) }, + requestBody: { + ...localResource, + ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), + ...(claimed + ? { + value: { ...localResource.value, on_behalf_of: claimed }, + preserve_on_behalf_of: true, + } + : {}), + }, }); } else { // New resource - resolve inline content @@ -163,6 +186,42 @@ export async function pushResource( } } +/** + * An agent with `run_on_behalf_of` runs as the identity in its value's + * `on_behalf_of`, which the backend sets to whoever writes the agent and clears + * while the toggle is off. Like an app's, it is never taken from the + * tracked file, which the pull leaves it out of: the deployed one is claimed + * back only by a pusher the backend lets keep it, an admin or a `wm_deployers` + * member. Strips the key from `localResource` (and from the deployed value, so + * an unchanged agent still compares equal) and returns the identity to claim. + */ +export function agentOnBehalfOf( + deployed: ResourceFile | Resource | undefined, + localResource: ResourceFile, + permissionedAsContext: PermissionedAsContext | undefined +): string | undefined { + // What the push writes is the tracked file's type: an agent retyped into + // another resource keeps its value exactly as the file states it. + if (localResource.resource_type !== "ai_agent") { + return undefined; + } + const local = localResource.value; + if (local && typeof local === "object") { + delete local.on_behalf_of; + } + const value = deployed?.resource_type === "ai_agent" ? deployed.value : undefined; + const onBehalfOf = + value && typeof value === "object" ? value.on_behalf_of : undefined; + if (deployed && onBehalfOf !== undefined) { + const { on_behalf_of: _, ...rest } = value; + deployed.value = rest; + } + if (!onBehalfOf || !permissionedAsContext?.userIsAdminOrDeployer) { + return undefined; + } + return onBehalfOf; +} + type PushOptions = GlobalOptions; async function push(opts: PushOptions, filePath: string, remotePath: string) { const workspace = await resolveWorkspace(opts); @@ -184,7 +243,13 @@ async function push(opts: PushOptions, filePath: string, remotePath: string) { remotePath, undefined, parseFromFile(filePath), - filePath // Pass the local file path for branch-specific inline content resolution + filePath, // Pass the local file path for branch-specific inline content resolution + undefined, + undefined, + await buildPermissionedAsContext( + workspace.workspaceId, + await readEffectiveSyncBehavior(opts, workspace) + ) ); log.info(colors.bold.underline.green(`Resource ${remotePath} pushed`)); } diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 3563089d17..43bba850ed 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -6065,6 +6065,7 @@ export async function push( resourceFilePath, isFileResWsSpecific ? true : undefined, true, + permissionedAsContext, ); } // Already-synced parents got the full content this run. diff --git a/cli/src/core/permissioned_as.ts b/cli/src/core/permissioned_as.ts index 87ee37a8cb..dd0b3de8be 100644 --- a/cli/src/core/permissioned_as.ts +++ b/cli/src/core/permissioned_as.ts @@ -250,6 +250,18 @@ export async function preCheckPermissionedAs( if (match) { currentOwner = match[1]; } + } else if (typeStr === "resource") { + // An agent with `run_on_behalf_of` runs as someone, and the file never says who. + if ( + /["']?resource_type["']?\s*:\s*["']?ai_agent\b/.test(beforeContent) && + /["']?run_on_behalf_of["']?\s*:\s*true\b/.test(beforeContent) + ) { + wouldChangeItems.push({ + path: change.path, + currentOwner: "(agent owner)", + }); + } + continue; } else if (typeStr.endsWith("_trigger")) { wouldChangeItems.push({ path: change.path, diff --git a/cli/src/types.ts b/cli/src/types.ts index 1c97c4d7a4..3ae2b8d6a4 100644 --- a/cli/src/types.ts +++ b/cli/src/types.ts @@ -254,7 +254,7 @@ export async function pushObj( } else if (typeEnding === "resource") { if (!alreadySynced.includes(p)) { alreadySynced.push(p); - await pushResource(workspace, p, befObj, newObj, originalLocalPath || p, wsSpecific, true); + await pushResource(workspace, p, befObj, newObj, originalLocalPath || p, wsSpecific, true, permissionedAsContext); } } else if (typeEnding === "resource-type") { await pushResourceType(workspace, p, befObj, newObj); diff --git a/cli/test/deploy_on_behalf_of_unit.test.ts b/cli/test/deploy_on_behalf_of_unit.test.ts index 7e21b24832..a0db663589 100644 --- a/cli/test/deploy_on_behalf_of_unit.test.ts +++ b/cli/test/deploy_on_behalf_of_unit.test.ts @@ -105,3 +105,28 @@ test("deployItem: never sends the source workspace's on_behalf_of", async () => expect("on_behalf_of" in JSON.parse(JSON.stringify(identity))).toBe(false); } }); + +// An agent carries its principal inside its resource value, and is handed the chosen one as a +// principal. The source's must never be sent: without a choice the key is dropped, leaving the +// backend to make the agent the deployer's. +test("deployItem: an agent takes the chosen principal, never the source's", async () => { + const captured: any[] = []; + const provider = { + existsResource: async () => true, + getResource: async () => ({ + path: "f/x/agent", + resource_type: "ai_agent", + description: "", + value: { system_prompt: "hi", on_behalf_of: "u/alice" }, + }), + updateResource: async (p: any) => void captured.push(p.requestBody), + } as any; + + await deployItem(provider, "resource" as any, "f/x/agent", "src", "dst", "u/bob"); + await deployItem(provider, "resource" as any, "f/x/agent", "src", "dst", undefined); + + expect(captured[0].value).toEqual({ system_prompt: "hi", on_behalf_of: "u/bob" }); + expect(captured[0].preserve_on_behalf_of).toBe(true); + expect(captured[1].value).toEqual({ system_prompt: "hi" }); + expect(captured[1].preserve_on_behalf_of).toBe(false); +}); diff --git a/cli/test/precheck_permissioned_as_apps_unit.test.ts b/cli/test/precheck_permissioned_as_apps_unit.test.ts index 4a224a43c0..9651b59cc1 100644 --- a/cli/test/precheck_permissioned_as_apps_unit.test.ts +++ b/cli/test/precheck_permissioned_as_apps_unit.test.ts @@ -145,3 +145,16 @@ test("an app is listed once however many of its files changed", async () => { expect(message).toContain("2 item(s)"); }); + +// An agent has an identity only while `run_on_behalf_of` is on, so only then +// can a push take it over. +test("an agent warns only while it runs on behalf of someone", async () => { + const agent = (run: boolean) => ({ + name: "edited" as const, + path: "f/test/bot.resource.yaml", + before: `resource_type: ai_agent\nvalue:\n system_prompt: hi\n run_on_behalf_of: ${run}\n`, + }); + + expect(await precheck([agent(true)])).toContain("f/test/bot.resource.yaml"); + expect(await precheck([agent(false)])).toBeUndefined(); +}); diff --git a/cli/test/resource_push_agent_obo_unit.test.ts b/cli/test/resource_push_agent_obo_unit.test.ts new file mode 100644 index 0000000000..d9b8361c8a --- /dev/null +++ b/cli/test/resource_push_agent_obo_unit.test.ts @@ -0,0 +1,57 @@ +/** + * An agent's run-as identity lives in its value, which the pull leaves out. A + * push must neither see that gap as a change nor let the file pick who the + * agent runs as: only the deployed identity is claimed back, and only by a + * pusher the backend lets keep it. + */ + +import { expect, test } from "bun:test"; +import { isSuperset } from "../src/types.ts"; +import { agentOnBehalfOf } from "../src/commands/resource/resource.ts"; + +const ctx = (userIsAdminOrDeployer: boolean) => ({ + userCache: new Map(), + userIsAdminOrDeployer, + userEmail: "me@x.dev", +}); + +function agents(localObo?: string) { + const deployed = { + resource_type: "ai_agent", + value: { system_prompt: "hi", on_behalf_of: "u/bob" }, + } as any; + const local = { + resource_type: "ai_agent", + value: { system_prompt: "hi", ...(localObo ? { on_behalf_of: localObo } : {}) }, + } as any; + return { deployed, local }; +} + +test("an unchanged agent still compares equal to the deployed one", () => { + const { deployed, local } = agents(); + agentOnBehalfOf(deployed, local, ctx(true)); + expect(isSuperset(local, deployed)).toBe(true); +}); + +test("an admin or deployer claims the deployed identity, never the file's", () => { + const { deployed, local } = agents("u/admin"); + expect(agentOnBehalfOf(deployed, local, ctx(true))).toBe("u/bob"); + expect(local.value.on_behalf_of).toBeUndefined(); +}); + +test("anyone else claims nothing", () => { + const { deployed, local } = agents("u/bob"); + expect(agentOnBehalfOf(deployed, local, ctx(false))).toBeUndefined(); + expect(agentOnBehalfOf(agents().deployed, agents().local, undefined)).toBeUndefined(); + expect(local.value.on_behalf_of).toBeUndefined(); +}); + +test("other resources are left alone, an agent retyped into one included", () => { + for (const deployedType of ["json", "ai_agent"]) { + const deployed = { resource_type: deployedType, value: { on_behalf_of: "u/bob" } } as any; + const local = { resource_type: "json", value: { on_behalf_of: "u/x" } } as any; + expect(agentOnBehalfOf(deployed, local, ctx(true))).toBeUndefined(); + expect(local.value.on_behalf_of).toBe("u/x"); + expect(deployed.value.on_behalf_of).toBe("u/bob"); + } +}); diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index 71447c6b1f..d73cb3562c 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -637,15 +637,26 @@ export async function deployItem( workspace: workspaceFrom, path, }); + let value = resource.value ?? ""; + // An agent's value carries the principal it runs as, as a trigger's row does: the source's + // names nobody in the target, so it is replaced by the chosen one or dropped, leaving the + // backend to make it the deployer's. + const agent = resource.resource_type === "ai_agent" && typeof value === "object"; + if (agent) { + const { on_behalf_of: _, ...rest } = value; + value = onBehalfOf ? { ...rest, on_behalf_of: onBehalfOf } : rest; + } + const agentPreserve = agent ? { preserve_on_behalf_of: preserveOnBehalfOf } : {}; if (alreadyExists) { await provider.updateResource({ workspace: workspaceTo, path, requestBody: { path, - value: resource.value ?? "", + value, description: resource.description ?? "", labels: resource.labels, + ...agentPreserve, }, }); } else { @@ -653,10 +664,11 @@ export async function deployItem( workspace: workspaceTo, requestBody: { path, - value: resource.value ?? "", + value, resource_type: resource.resource_type, description: resource.description ?? "", labels: resource.labels, + ...agentPreserve, }, }); } @@ -917,6 +929,11 @@ export async function getItemValue( return variable.value; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); + // Each workspace resolves its own agent identity, which a deploy never copies. + if (resource.resource_type === "ai_agent" && resource.value) { + const { on_behalf_of: _, ...value } = resource.value; + return value; + } return resource.value; } else if (kind === "resource_type") { const rt = await provider.getResourceType({ workspace, path }); @@ -1002,7 +1019,8 @@ function stripTriggerOrScheduleRuntimeFields(row: unknown): unknown { /** * Fetch the on_behalf_of value for a deployable item. - * Returns an email for flows/scripts/apps, or undefined if not applicable. + * Returns an email for flows/scripts/apps, a principal (u/username, g/group) for + * triggers/schedules and agents, or undefined if not applicable. */ export async function getOnBehalfOf( provider: DeployProvider, @@ -1020,6 +1038,12 @@ export async function getOnBehalfOf( } else if (kind === "app" || kind === "raw_app") { const app = await provider.getAppByPath({ workspace, path }); return app.policy?.on_behalf_of_email; + } else if (kind === "resource") { + // Only an agent runs as anyone, and like a trigger it records the principal. + const resource = await provider.getResource({ workspace, path }); + return resource.resource_type === "ai_agent" + ? resource.value?.on_behalf_of + : undefined; } else if (kind === "schedule") { const schedule = await provider.getSchedule({ workspace, path }); return schedule.permissioned_as; diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 18c765e13b..e139d22910 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -612,12 +612,13 @@ } async function fetchOnBehalfOfInfo(diffs: WorkspaceItemDiff[]) { - // Runnables carry an email; triggers/schedules carry `permissioned_as`. - // `getOnBehalfOf` handles the dispatch — we just need to skip kinds that - // have no on_behalf_of concept (resource, variable, folder, resource_type). + // Runnables carry an email; triggers/schedules and agents carry `permissioned_as`. + // `getOnBehalfOf` handles the dispatch (a resource that is not an agent has none) — we + // just need to skip kinds that have no on_behalf_of concept (variable, folder, resource_type). const itemsWithOnBehalfOf = diffs.filter( (d) => - ['flow', 'script', 'app', 'raw_app'].includes(d.kind) || isTriggerOrScheduleKind(d.kind) + ['flow', 'script', 'app', 'raw_app', 'resource'].includes(d.kind) || + isTriggerOrScheduleKind(d.kind) ) const pair = [ { workspace: currentWorkspaceId, side: 'fork' as const }, @@ -679,17 +680,22 @@ }) ) + /** Triggers, schedules and agents record who they run as by principal, the rest by address. */ + function usesPrincipal(kind: Kind): boolean { + return kind === 'trigger' || isTriggerOrScheduleKind(kind) || kind === 'resource' + } + /** * Get the on_behalf_of value for deployment based on user's choice. - * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for triggers/schedules. + * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for + * triggers/schedules and agents. */ function getOnBehalfOfForDeploy(itemKey: string, kind: Kind): string | undefined { const choice = onBehalfOfChoice[itemKey] if (choice === 'target') return getTargetOnBehalfOf(itemKey) if (choice === 'custom') { const details = customOnBehalfOf[itemKey] - const wantsPermissionedAs = kind === 'trigger' || isTriggerOrScheduleKind(kind) - return wantsPermissionedAs ? details?.permissionedAs : details?.email + return usesPrincipal(kind) ? details?.permissionedAs : details?.email } // 'me' or undefined = don't pass, backend will use deploying user's identity return undefined @@ -701,7 +707,7 @@ * returning undefined clears the source item's value rather than keeping it. */ function getOnBehalfOfPermissionedAsForDeploy(itemKey: string, kind: Kind): string | undefined { - if (kind === 'trigger' || isTriggerOrScheduleKind(kind)) return undefined + if (usesPrincipal(kind)) return undefined if (onBehalfOfChoice[itemKey] !== 'custom') return undefined return customOnBehalfOf[itemKey]?.permissionedAs } diff --git a/frontend/src/lib/components/DeployWorkspace.svelte b/frontend/src/lib/components/DeployWorkspace.svelte index 7913240188..daf944ff37 100644 --- a/frontend/src/lib/components/DeployWorkspace.svelte +++ b/frontend/src/lib/components/DeployWorkspace.svelte @@ -110,16 +110,22 @@ return needsOnBehalfOfSelection(kind, sourceOnBehalfOfInfo[statusPath]) } + /** Triggers and agents record who they run as by principal, the rest by address. */ + function usesPrincipal(kind: Kind): boolean { + return kind === 'trigger' || kind === 'resource' + } + /** * Get the on_behalf_of value for deployment based on user's choice. - * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for triggers/schedules. + * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for + * triggers/schedules and agents. */ function getOnBehalfOfForDeploy(statusPath: string, kind: Kind): string | undefined { const choice = onBehalfOfChoice[statusPath] if (choice === 'target') return targetOnBehalfOfInfo[statusPath] if (choice === 'custom') { const details = customOnBehalfOf[statusPath] - return kind === 'trigger' ? details?.permissionedAs : details?.email + return usesPrincipal(kind) ? details?.permissionedAs : details?.email } // 'me' or undefined = don't pass, backend will use deploying user's identity return undefined @@ -134,7 +140,7 @@ statusPath: string, kind: Kind ): string | undefined { - if (kind === 'trigger' || onBehalfOfChoice[statusPath] !== 'custom') return undefined + if (usesPrincipal(kind) || onBehalfOfChoice[statusPath] !== 'custom') return undefined return customOnBehalfOf[statusPath]?.permissionedAs } @@ -205,7 +211,7 @@ // Fetch on_behalf_of_email for flows, scripts, apps, and triggers from both workspaces for (const dep of sortedSet.filter((d) => - ['flow', 'script', 'app', 'trigger'].includes(d.kind) + ['flow', 'script', 'app', 'trigger', 'resource'].includes(d.kind) )) { const key = computeStatusPath(dep.kind, dep.path) let source: string | undefined diff --git a/frontend/src/lib/components/OnBehalfOfSelector.svelte b/frontend/src/lib/components/OnBehalfOfSelector.svelte index 99ce21714e..127e21a9e2 100644 --- a/frontend/src/lib/components/OnBehalfOfSelector.svelte +++ b/frontend/src/lib/components/OnBehalfOfSelector.svelte @@ -19,7 +19,9 @@ kind === 'app' || kind === 'raw_app' || kind === 'trigger' || - isTriggerOrScheduleKind(kind) + isTriggerOrScheduleKind(kind) || + // Only an agent's value carries an identity, so no other resource has a source value. + kind === 'resource' if (!supported) return false return !!sourceValue } diff --git a/frontend/src/lib/components/ResourceEditor.svelte b/frontend/src/lib/components/ResourceEditor.svelte index bd9d51638d..33ab00abbf 100644 --- a/frontend/src/lib/components/ResourceEditor.svelte +++ b/frontend/src/lib/components/ResourceEditor.svelte @@ -652,6 +652,11 @@ const s = states[ws].draft! const ini = initialStates[ws] if (existedInitially[ws]) { + const fetched = fetchedResources[ws] + // An agent keeps the identity its value names, as its own editor keeps it: without + // the flag an admin's save would take it over. The backend resets it to the writer + // for anyone not allowed to keep it. + const keepAgentObo = fetched?.resource_type === 'ai_agent' && !!s.args?.on_behalf_of await ResourceService.updateResource({ workspace: ws, path: ini.path, @@ -660,10 +665,10 @@ value: s.args, description: s.description, labels: s.labels, - ws_specific: s.wsSpecific + ws_specific: s.wsSpecific, + preserve_on_behalf_of: keepAgentObo ? true : undefined } }) - const fetched = fetchedResources[ws] if (fetched?.resource_type === 'json_schema') { clearJsonSchemaResourceCache(ini.path, ws) } diff --git a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts index 0b393e6969..c6b03cee68 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts @@ -501,7 +501,8 @@ export const resourceRequestSchema = z.object({ "description": z.string().describe("The description of the resource").optional(), "resource_type": z.string().describe("The resource_type associated with the resource"), "labels": z.array(z.string()).optional(), - "ws_specific": z.boolean().optional() + "ws_specific": z.boolean().optional(), + "preserve_on_behalf_of": z.boolean().describe("ai_agent only. Keep the identity `value.on_behalf_of` names (`u/`, `g/`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller.").optional() }) export const triggerRequestSchemas = { diff --git a/frontend/src/lib/components/details/OnBehalfOfBadge.svelte b/frontend/src/lib/components/details/OnBehalfOfBadge.svelte index 13bd94b122..3b098555f1 100644 --- a/frontend/src/lib/components/details/OnBehalfOfBadge.svelte +++ b/frontend/src/lib/components/details/OnBehalfOfBadge.svelte @@ -8,7 +8,7 @@ onBehalfOf: string | undefined /** Address of the account `onBehalfOf` names, derived from it on the read paths. */ onBehalfOfEmail: string | undefined - kind: 'script' | 'flow' + kind: 'script' | 'flow' | 'agent' } let { onBehalfOf, onBehalfOfEmail, kind }: Props = $props() @@ -25,7 +25,12 @@ {#if onBehalfOf} {#snippet text()} - Every run of this {kind} is permissioned as {detailed}, whoever starts it. + {#if kind === 'agent'} + Runs of this agent from its page and the API are permissioned as {detailed}, whoever + starts them. + {:else} + Every run of this {kind} is permissioned as {detailed}, whoever starts it. + {/if} {/snippet} On behalf of {onBehalfOf} diff --git a/frontend/src/lib/components/flows/agentDraft.svelte.ts b/frontend/src/lib/components/flows/agentDraft.svelte.ts index cb6081ef46..c0b2ba8bc4 100644 --- a/frontend/src/lib/components/flows/agentDraft.svelte.ts +++ b/frontend/src/lib/components/flows/agentDraft.svelte.ts @@ -144,18 +144,29 @@ export function agentDraftDeployRefusal( */ type AgentWriteResult = { ok: true } | { ok: false; error: string; notAnAgent?: true } +/** Who a deploy makes the agent run as. The server resolves it as it does a flow's: without + * `preserve`, or from someone not allowed to keep another identity, it is the deployer. */ +export interface AgentRunAs { + permissionedAs: string | undefined + preserve: boolean +} + async function writeAgentResource( workspace: string, fromPath: string, state: AgentResourceState, - noDeployed: boolean + noDeployed: boolean, + runAs?: AgentRunAs ): Promise { const body = { path: state.path, - value: state.args, + value: runAs?.permissionedAs + ? { ...state.args, on_behalf_of: runAs.permissionedAs } + : state.args, description: state.description, labels: state.labels, - ws_specific: state.wsSpecific + ws_specific: state.wsSpecific, + preserve_on_behalf_of: runAs?.preserve || undefined } try { if (noDeployed) { @@ -221,9 +232,12 @@ export interface AgentDraftHandle { /** Why this path cannot be edited here, if it cannot. Render it instead of the form. */ readonly refusal: string | undefined readonly sync: TriggerDraftSync + /** Who the deployed agent runs as when run from its page; undefined when nothing is deployed + * or it runs as whoever runs it. */ + readonly onBehalfOf: string | undefined /** Write the current state to the resource and drop the draft. Resolves to the path written, * which differs from the one loaded when the draft renames the agent, or undefined on failure. */ - deploy: () => Promise + deploy: (runAs?: AgentRunAs) => Promise } /** @@ -237,6 +251,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { let loading = $state(true) let noDeployed = $state(false) let canWriteResource = $state(true) + let onBehalfOf = $state(undefined) /** Guards the load against a path that changed under a slow response. */ let loadedFor = $state(undefined) /** Why the loaded path cannot be edited here, if it cannot. Gates the sync for as long as that @@ -324,10 +339,15 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { return } noDeployed = Boolean((r as any).no_deployed) + // Who it runs as is the deploy's to decide, not a setting the form or a draft holds. + const { on_behalf_of, ...args } = (r.value ?? {}) as AIAgentConfig & { + on_behalf_of?: string + } + onBehalfOf = noDeployed ? undefined : on_behalf_of const deployedState: AgentResourceState = { path: r.path, description: r.description ?? '', - args: (r.value ?? {}) as AIAgentConfig, + args, // Only where nothing else answers for the type: with a deployed row both the // create below and the review page's `deployDraft` read it from there, and // carrying it would make every draft the generic resource editor writes — which @@ -414,7 +434,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { }) }) - async function deploy(): Promise { + async function deploy(runAs?: AgentRunAs): Promise { const ws = opts.workspace() const fromPath = opts.path() const s = state @@ -430,7 +450,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { // made during the request as saved, and the banner would clear on a value the server never // received; against the snapshot it stays a draft, which is what it is. const submitted = structuredClone($state.snapshot(s)) as AgentResourceState - const written = await writeAgentResource(ws, fromPath, submitted, noDeployed) + const written = await writeAgentResource(ws, fromPath, submitted, noDeployed, runAs) if (!written.ok) { // A path that is no longer an agent tears this editor down; anything else is a plain error // the user can retry from the form as it stands. @@ -449,6 +469,10 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { const firstSave = noDeployed deployed = submitted noDeployed = false + // What the server resolved, which a request to keep an identity does not decide alone. + void ResourceService.getResource({ workspace: ws, path: submitted.path }) + .then((r) => (onBehalfOf = (r.value as { on_behalf_of?: string } | undefined)?.on_behalf_of)) + .catch(() => {}) const renamed = submitted.path !== fromPath // Only when the form still holds exactly what was sent. `discard` resets the handle's cell to // what it is given, and the apply-effect copies that back over the form: against an edit made @@ -490,6 +514,9 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { get refusal() { return refusal }, + get onBehalfOf() { + return onBehalfOf + }, sync, deploy } diff --git a/frontend/src/lib/components/flows/agentResourceUtils.ts b/frontend/src/lib/components/flows/agentResourceUtils.ts index 9eb81a39c9..bf6668a4f1 100644 --- a/frontend/src/lib/components/flows/agentResourceUtils.ts +++ b/frontend/src/lib/components/flows/agentResourceUtils.ts @@ -118,6 +118,8 @@ export interface AIAgentConfig { temperature?: number max_iterations?: number tools?: AgentTool[] + /** Runs from the agent's page take its `on_behalf_of` rather than the caller's identity. */ + run_on_behalf_of?: boolean } /** Extract the static brain values from a step's input_transforms into a flat agent config. */ diff --git a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte index 658a7adb77..b902b69bfa 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte @@ -50,7 +50,7 @@ keepsManagedMemory } from '../agentFormFields' import { toolDisplayName, type AgentTool } from '../agentToolUtils' - import { useAgentDraft } from '../agentDraft.svelte' + import { useAgentDraft, type AgentRunAs } from '../agentDraft.svelte' import { sendUserToast } from '$lib/toast' interface Props { @@ -359,8 +359,8 @@ inputs?: Record ): Promise { if (!agentModule) return undefined - // A view runs the deployed agent, which anyone who can read it may do; the editor previews - // the draft. Both run as the caller. + // A view runs the deployed agent, which anyone who can read it may do, as the server picks + // the identity; the editor previews the draft as the one editing it. if (view && workspace) { return await JobService.runAgent({ workspace, @@ -456,12 +456,21 @@ pathErrorValue = error ?? '' } + /** Who the next deploy makes the agent run as, as the "Permissioned as" line picked it. Unset + * while the line was never shown, which keeps the current identity as the line would have + * preselected it: an admin deploying without looking must not take the agent over. */ + let runAs = $state(undefined) + export function setRunAs(next: AgentRunAs) { + runAs = next + } + export function deploy(): Promise { if (pathErrorValue) { sendUserToast(`Cannot deploy the agent: ${pathErrorValue}`, true) return Promise.resolve(false) } - return draft.deploy().then(async (written) => { + const keep = draft.onBehalfOf ? { permissionedAs: draft.onBehalfOf, preserve: true } : undefined + return draft.deploy(runAs ?? keep).then(async (written) => { // The path the write landed on, which a rename moves off the one this editor opened. if (written) await onSaved?.(written) return written !== undefined diff --git a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte index 30aa98b65e..58c47bbb20 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte @@ -582,6 +582,7 @@ path={target?.path ?? ''} workspace={ws} bind:error={() => host?.pathError(), (error) => host?.setPathError(error)} + onRunAsChange={(runAs) => host?.setRunAs(runAs)} /> {/if} {/snippet} diff --git a/frontend/src/lib/components/flows/content/AgentSettings.svelte b/frontend/src/lib/components/flows/content/AgentSettings.svelte index 449edfccff..ec7d0edb7c 100644 --- a/frontend/src/lib/components/flows/content/AgentSettings.svelte +++ b/frontend/src/lib/components/flows/content/AgentSettings.svelte @@ -7,8 +7,9 @@ import ResourceDescriptionField from '$lib/components/ResourceDescriptionField.svelte' import ResourcePathHint from '$lib/components/ResourcePathHint.svelte' import Toggle from '$lib/components/Toggle.svelte' + import PermissionedAsLine from '$lib/components/triggers/PermissionedAsLine.svelte' import { WorkspaceService } from '$lib/gen' - import type { AgentDraftHandle } from '../agentDraft.svelte' + import type { AgentDraftHandle, AgentRunAs } from '../agentDraft.svelte' /** An agent's own settings, laid out as the top of the resource editor: what it is saved as * rather than what it does. */ @@ -19,9 +20,11 @@ workspace: string | undefined /** Why the path cannot be deployed to, if it cannot. */ error?: string + /** Who the next deploy makes the agent run as, as picked here. */ + onRunAsChange?: (runAs: AgentRunAs) => void } - let { draft, path, workspace, error = $bindable() }: Props = $props() + let { draft, path, workspace, error = $bindable(), onRunAsChange = undefined }: Props = $props() let readOnly = $derived(!draft.canWrite) // Only a workspace that deploys somewhere has anything to keep an agent out of. @@ -64,6 +67,33 @@ {:else} {/if} + +
+ + {#if draft.state.args.run_on_behalf_of} + + onRunAsChange?.({ permissionedAs, preserve })} + /> + {/if} +
{#if deployTo.current}