diff --git a/backend/windmill-api/src/mcp/session/deploy.rs b/backend/windmill-api/src/mcp/session/deploy.rs index 1dc8b1453e..a5be2c0ecc 100644 --- a/backend/windmill-api/src/mcp/session/deploy.rs +++ b/backend/windmill-api/src/mcp/session/deploy.rs @@ -426,6 +426,9 @@ async fn deploy_app( app.insert("preserve_on_behalf_of".into(), json!(true)); } app.insert("policy".into(), Value::Object(policy)); + if let Some(labels) = non_null(draft.get("labels")) { + app.insert("labels".into(), labels.clone()); + } if let Some(message) = message { app.insert("deployment_message".into(), json!(message)); } diff --git a/backend/windmill-api/src/mcp/session/workspace.rs b/backend/windmill-api/src/mcp/session/workspace.rs index 720dbbac76..ac8403c7c8 100644 --- a/backend/windmill-api/src/mcp/session/workspace.rs +++ b/backend/windmill-api/src/mcp/session/workspace.rs @@ -58,7 +58,7 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult // is_template, language, kind`, + `parent_hash` once forked from a deploy) // flow the `Flow` object (`path, summary, description, value, schema`, + // `version_id` when forked from a deploy) -// raw_app `{summary, files, runnables, data, policy?, custom_path?, +// raw_app `{summary, files, runnables, data, policy?, custom_path?, labels?, // parent_version?, draft_path?}` (`normalize_app_draft`) // trigger_schedule the schedule request body; `trigger_` that trigger's body // resource `{path, description, args, labels, wsSpecific, resource_type}` @@ -384,7 +384,13 @@ pub(super) fn normalize_app_draft(value: &Value) -> Value { .cloned() .unwrap_or_else(|| json!({ "tables": [] })), ); - for key in ["policy", "custom_path", "parent_version", "draft_path"] { + for key in [ + "policy", + "custom_path", + "labels", + "parent_version", + "draft_path", + ] { put(&mut out, key, value.get(key).cloned()); } Value::Object(out) @@ -695,6 +701,7 @@ pub(super) fn app_source_to_draft_value(app: &Value, fallback: Option<&Value>) - out.insert("data".into(), data); put(&mut out, "policy", or_fallback("policy")); put(&mut out, "custom_path", or_fallback("custom_path")); + put(&mut out, "labels", or_fallback("labels")); // The fork base: the head of a deployed app's versions, or what a draft already pinned. let head = app .get("versions") @@ -2027,6 +2034,17 @@ mod tests { assert!(draft_item("app", "u/a/s", &draft).is_none()); } + #[test] + fn normalize_app_draft_keeps_labels() { + // Every session save goes through this whitelist: a field missing here is + // stripped from a draft the editor wrote. + let draft = json!({ "files": {}, "labels": ["a"] }); + assert_eq!( + normalize_app_draft(&draft).get("labels"), + Some(&json!(["a"])) + ); + } + #[test] fn draft_item_carries_the_variable_expiry() { let draft = json!({ "path": "u/a/v", "variable": { "value": "", "is_secret": true, "description": "" }, "value_valid_until": "2027-01-15T00:00:00Z" }); diff --git a/frontend/src/lib/appDiffSides.ts b/frontend/src/lib/appDiffSides.ts index 68ff75c11b..1443bcae36 100644 --- a/frontend/src/lib/appDiffSides.ts +++ b/frontend/src/lib/appDiffSides.ts @@ -1,11 +1,17 @@ /** Split a CLASSIC app draft into comparable parts. The editor mirrors - * summary/draft_path INTO the bare grid it autosaves, while a deployed row - * keeps them outside `value` — compared raw, metadata diffs as grid noise. - * Also unwraps legacy wrapped drafts ({summary/policy/custom_path, value}). */ + * summary/draft_path and the app settings (policy, labels) INTO the bare grid + * it autosaves, while a deployed row keeps them outside `value` — compared + * raw, metadata diffs as grid noise. Also unwraps legacy wrapped drafts + * ({summary/policy/custom_path, value}). + * + * `policy` and `labels` are undefined when the draft predates mirroring them, + * so the caller falls back to the deployed row. */ export function classicAppDraftParts(json: unknown): { value: unknown summary?: string draftPath?: string + policy?: Record + labels?: string[] } { if (json === null || typeof json !== 'object' || Array.isArray(json)) { return { value: json } @@ -27,10 +33,12 @@ export function classicAppDraftParts(json: unknown): { draftPath: (obj.draft_path as string | undefined) ?? inner.draftPath } } - const { parent_version: _pv, draft_path, summary, ...value } = obj + const { parent_version: _pv, draft_path, summary, policy, labels, ...value } = obj return { value, summary: summary as string | undefined, - draftPath: draft_path as string | undefined + draftPath: draft_path as string | undefined, + policy: policy as Record | undefined, + labels: labels as string[] | undefined } } diff --git a/frontend/src/lib/components/apps/editor/AppDeploymentHistory.svelte b/frontend/src/lib/components/apps/editor/AppDeploymentHistory.svelte index 7a508aac71..8f1c9e6ac4 100644 --- a/frontend/src/lib/components/apps/editor/AppDeploymentHistory.svelte +++ b/frontend/src/lib/components/apps/editor/AppDeploymentHistory.svelte @@ -4,6 +4,7 @@ import { workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { deployRawAppValue } from '$lib/rawAppDeploy' + import { policyForUpdate } from './publishAccessMode' import DeploymentHistory from './DeploymentHistory.svelte' interface Props { @@ -37,7 +38,8 @@ workspace: $workspaceStore!, path: app.path, requestBody: { - ...app + ...app, + policy: app.policy && policyForUpdate(app.policy) } }) } diff --git a/frontend/src/lib/components/apps/editor/AppEditor.svelte b/frontend/src/lib/components/apps/editor/AppEditor.svelte index 643cd074d3..813894a11f 100644 --- a/frontend/src/lib/components/apps/editor/AppEditor.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditor.svelte @@ -67,7 +67,7 @@ let { app, path, - policy, + policy = $bindable(), summary, labels, deployedBaseline = undefined, @@ -897,7 +897,7 @@ {onOpenOthersDrafts} {onRestore} {onDeploy} - {policy} + bind:policy {fromHub} bind:this={appEditorHeader} {diffDrawer} diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte index 1760b104cc..0e191078e5 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte @@ -1,4 +1,13 @@ + + - - closeSaveDrawer()}> - {#snippet actions()} -
- - -
- {/snippet} - -
-
+ (inputsDrawerOpen = false)}> @@ -1318,14 +1320,31 @@ seeing the app is most of what an app editor is good for on one. --> - + + {/if} + deploy(detail)} dropdownItems={$appPath != '' ? () => [ { @@ -1346,8 +1365,6 @@ : []) ] : undefined} - > - Deploy - + /> {/snippet} diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte deleted file mode 100644 index 9037aec2d4..0000000000 --- a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte +++ /dev/null @@ -1,695 +0,0 @@ - - -
- {#if !onLatest} - - {headUnknown - ? "Deploying may overwrite changes made by other users. Press 'Deploy' to see diff." - : "By deploying, you may overwrite changes made by other users. Press 'Deploy' to see diff."} - - {/if} - -
-
- - - { - e.stopPropagation() - }, - onkeyup: () => { - if (appPath == '' && summary?.length > 0 && !dirtyPath) { - path?.setName( - summary - .toLowerCase() - .replace(/[^a-z0-9_]/g, '_') - .replace(/-+/g, '_') - .replace(/^-|-$/g, '') - ) - } - } - }} - bind:value={summary} - /> - -
-
- - -
-
- - -
-
- -
-
-
- { - onBehalfOfChoice = choice - if (choice === 'me') { - policy.on_behalf_of_email = $userStore?.email - policy.on_behalf_of = `u/${$userStore?.username}` - customOnBehalfOfEmail = '' - preserveOnBehalfOf = false - } else if (choice === 'target') { - policy.on_behalf_of_email = savedOnBehalfOfEmail - policy.on_behalf_of = savedOnBehalfOf - customOnBehalfOfEmail = '' - preserveOnBehalfOf = true - } else if (choice === 'custom' && details) { - policy.on_behalf_of_email = details.email - policy.on_behalf_of = details.permissionedAs - customOnBehalfOfEmail = details.email - preserveOnBehalfOf = true - } - }} - kind="app" - {canPreserve} - customValue={customOnBehalfOfEmail} - isDeployment={false} - myPermissionedAs={myOnBehalfOf} - readOnlyWithoutPreserve - /> - {#if onBehalfOfWillChange} - - will change from {savedOnBehalfOf} on deploy - {/if} -
-
- {#if canPreserve} - Viewers run the app's runnables as this user. - {:else} - Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user. - {/if} -
-
-
- -
- { - policy.sandbox = e.detail || undefined - // Counted where the toggle is flipped rather than where the policy is - // persisted: a not-yet-deployed app only mutates it locally, and skipping - // those would read as unused in the case where it is picked up front. - logFeatureUsage('app_sandbox', 'toggled', { - key: `${rawApp ? 'raw' : 'low_code'}:${e.detail ? 'on' : 'off'}` - }) - // Frontend API access exists only for a sandboxed app, so turning - // isolation off drops the declared scopes with it rather than leaving - // them set but inert. - if (!e.detail) { - policy.frontend_sdk_scopes = undefined - } - // A not-yet-deployed app has no row to PATCH — `setPublishState` (POST - // /apps/update) would 404. The flag rides along in the `policy` the first - // deploy sends (createApp), so here we only mutate it locally. Persist - // incrementally once the app exists. - if (savedApp && !newApp) { - setPublishState(e.detail ? 'Sandbox isolation enabled' : 'Sandbox isolation disabled') - } - }} - disabled={!savedApp || composeOnlyApps} - /> - {#if composeOnlyApps || newApp} -
- {#if composeOnlyApps} - Required for apps composed by your role, and cannot be turned off. - {/if} - {#if newApp} - Takes effect when you first deploy this app. - {/if} -
- {/if} - {#if !composeOnlyApps && policy.sandbox != true} -
- - The app's frontend code runs with each viewer's full Windmill permissions. A future - version will ask viewers to approve this. Keep isolation off only if the app needs it. - -
- {/if} - - {#if rawApp && policy.sandbox == true} -
-
- {#snippet badge()} - {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length} -
- {#each FRONTEND_SDK_SCOPES.filter( (s) => policy.frontend_sdk_scopes.includes(s.value) ) as scope (scope.value)} - {scope.label} - {/each} -
- {/if} - {/snippet} -
- Let the app's frontend call the Windmill API as the viewer through the - windmill-client SDK, which it lists as a dependency. Grant only what the app - needs. -
-
- {#each FRONTEND_SDK_SCOPES as scope (scope.value)} -
- { - const current: string[] = policy.frontend_sdk_scopes ?? [] - const next = e.detail - ? [...current, scope.value] - : current.filter((s) => s !== scope.value) - // Keep the curated order so the consent banner and the stored - // 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) - ) - policy.frontend_sdk_scopes = ordered.length > 0 ? ordered : undefined - // Same as sandbox: a not-yet-deployed app has no row to PATCH, so the - // scopes ride along in the first deploy's policy instead. - if (savedApp && !newApp) { - setPublishState('Frontend API access updated') - } - }} - disabled={!savedApp} - /> -
{scope.description}
-
- {/each} -
- {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length} -
- - A sandboxed app calls the API cross-origin, which older windmill-client - versions cannot do. An app bundled before this Windmill version fails with a CORS error - until you deploy it again, which re-bundles it against a current client. - -
- {/if} -
-
- {/if} -
- - {#if !hideSecretUrl} -
-
- {#if rulesetsLoaded && !canSetAnonymous && policy.execution_mode != 'anonymous'} - - Opening this app to anyone with the link is restricted to workspace admins and bypass - users by a workspace protection rule - - {/if} - {#if rulesetsLoaded && !canSetGuest && policy.execution_mode != 'guest' && guestsAvailable} - - Opening this app to guests is restricted to workspace admins and bypass users by a - workspace protection rule - - {/if} -
- onAccessModeChange(e.detail)} - disabled={!savedApp} - > - {#snippet children({ item })} - - - - {/snippet} - -
-
- {#if policy.execution_mode == 'anonymous'} - Anyone holding the secret URL below can open this app without signing in. - {:else if policy.execution_mode == 'guest'} - {#if !guestsAvailable} - Guests are not available on Windmill Cloud, so this app still admits members only. - They require a self-hosted instance or a dedicated Windmill Cloud deployment. - {:else} - Anyone your identity provider authenticates can open this app without a Windmill - account. They join no workspace. Members of this workspace can open it too. - {#if guestUsage} - {guestUsage.guest_count} of {guestUsage.free_allowance} free guests used across this - instance in the last {guestUsage.window_days} days; beyond that, {guestUsage.metered - ? 'every four guests count as one seat' - : 'new guests are refused until the count drops'}. - {/if} - {/if} - {:else} - Only workspace members with read access on this app can open it. - {/if} -
-
- -
- {#if !savedApp || newApp} - - {:else if secretUrlHref} -
- (embedMode = e.detail)} - options={{ left: 'URL', right: 'Embed' }} - /> -
- - {:else} - {/if} -
- {#if embedMode} - Paste this iframe snippet into another app. - {#if rawApp} - To embed it in a cross-origin isolated page, add wm_coep=on - Sets the cross-origin isolation headers (COEP) on the app, which such a page - requires of its iframes. The app then only loads cross-origin resources that send - CORS or a Cross-Origin-Resource-Policy header. to the URL. - {/if} - (if requiring login, top-level domain of embedding app must be the same as the one of Windmill) - {:else} - Share this URL directly, or switch to Embed to get an iframe snippet. Only the latest - deployed version is served. - {/if} -
-
- - {#if embedMode && policy.execution_mode == 'guest' && guestJwtBase && guestsAvailable} -
-
- Embed for your own authenticated users (guest JWT) -
-
- To open this app for a user your own product already authenticates, mint a short-lived - JWT in your backend and append it to the app URL as guest.<jwt>. Each - token is its own seatless guest, confined to this app. Unlike the plain secret URL - above, there is no shared secret and no Windmill account. -
-
- Windmill verifies the token against the workspace's guest JWT key (Workspace settings → - Guests): a PEM public key or a JWKS URL{#if !isCloudHosted()}, or the instance's - configured issuer (JWT_EXT_JWKS_URL) when no workspace key is set{/if}. - Set the public half there; in your backend, sign each token with the matching - private key using RS256/384/512, PS256/384/512 or ES256/384 (symmetric HS* is - refused), carrying email, workspace_id = {opWs}, - app_path = {appPath} and exp (at most 24h ahead). -
- -
- Replace YOUR_GUEST_JWT with the token your backend signs per user. Past the - instance's free guest allowance a new guest email is refused (see the count above); guests - already seen in the window keep working. -
-
- {/if} - -
- {#if !(actingUser?.is_admin || actingUser?.is_super_admin)} - - Custom path can only be set by workspace admins - - {/if} -
- { - customPath = detail ? '' : undefined - if (customPath === undefined) { - customPathError = '' - } - }} - checked={customPath !== undefined} - options={{ - right: 'Use a custom URL' - }} - disabled={!$enterpriseLicense || !(actingUser?.is_admin || actingUser?.is_super_admin)} - /> - {#if !$enterpriseLicense} - - {/if} -
- - {#if customPath !== undefined} -
- - { - dirtyCustomPath = true - } - }} - bind:value={customPath} - error={dirtyCustomPath ? customPathError : undefined} - /> - {#if dirtyCustomPath && customPathError} -
{customPathError}
- {/if} -
-
-
Custom public URL
- -
- {/if} -
- - Embed this app in your own product to be used by your own users -
- {/if} -
diff --git a/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte b/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte new file mode 100644 index 0000000000..79d74204b9 --- /dev/null +++ b/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte @@ -0,0 +1,687 @@ + + +{#snippet sandboxHint()} + {#if composeOnlyApps} + Required for apps composed by your role, and cannot be turned off. + {:else} + + The app's frontend code runs with each viewer's full Windmill permissions. A future version + will ask viewers to approve this. Keep isolation off only if the app needs it. + + {/if} +{/snippet} + +{#snippet adminOnlyHint()} + Only workspace admins can set a custom URL. +{/snippet} + + + (open = false)}> +
+
+
+ {#snippet labelExtra()} + + {/snippet} +
+ +
+ +
+
+ +
+ {#snippet labelExtra()} + + {/snippet} +
+ + + { + policy.sandbox = on || undefined + // Counted where the toggle is flipped rather than where the policy is + // persisted, so a choice made before the first deploy counts too. + logFeatureUsage('app_sandbox', 'toggled', { + key: `${rawApp ? 'raw' : 'low_code'}:${on ? 'on' : 'off'}` + }) + // Frontend API access exists only for a sandboxed app, so turning + // isolation off drops the declared scopes with it rather than leaving + // them set but inert. + if (!on) { + policy.frontend_sdk_scopes = undefined + } + }} + > + {#if rawApp} + + {/if} + +
+
+ +
+ {#snippet labelExtra()} + + {/snippet} +
+ {#if sharingChanged} + + {/if} +
+ +
+ + + + {#if embedMode && policy.execution_mode == 'guest' && guestJwtBase && guestsAvailable} + + {/if} + + { + customPath = on ? '' : undefined + if (!on) { + customPathError = '' + } + }} + > + + + + + Embed this app in your own product to be used by your own users +
+
+
+
+
+
diff --git a/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts b/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts index 5c22e3f475..efda2dabb8 100644 --- a/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts +++ b/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts @@ -1,6 +1,54 @@ -import { workspaceStore } from '$lib/stores' -import { get } from 'svelte/store' +import { AppService, type Policy } from '$lib/gen' +import { deployedPermissionedAs } from '$lib/components/itemSettings/onBehalfOf' -export function computeSecretUrl(secretUrl: string) { - return `${window.location.origin}/public/${get(workspaceStore)}/${secretUrl}` +type RunAs = { on_behalf_of?: string; on_behalf_of_email?: string } +type DeployingUser = Parameters[0] + +export function computeSecretUrl(secretUrl: string, workspace: string | undefined) { + return `${window.location.origin}/public/${workspace}/${secretUrl}` +} + +/** The user the app at `path` runs on behalf of right now, read from its row: the editor's copy + * is the one it loaded, which another deploy may have replaced since. Undefined when the read + * fails. */ +export async function fetchDeployedRunAs( + workspace: string, + path: string +): Promise { + try { + const { on_behalf_of, on_behalf_of_email } = ( + await AppService.getAppLiteByPath({ workspace, path }) + ).policy + return { on_behalf_of, on_behalf_of_email } + } catch { + return undefined + } +} + +/** Who can open the app at `path` right now. An update deploy states no mode, so the server keeps + * the deployed one, which someone may have changed since the editor loaded the app. Undefined + * when the read fails. */ +export async function fetchDeployedAccessMode( + workspace: string, + path: string +): Promise { + try { + return (await AppService.getAppLiteByPath({ workspace, path })).policy.execution_mode + } catch { + return undefined + } +} + +/** Writes into an app's policy the user its deploy will run on behalf of, so the request names + * it. The editor keeps the policy it sent as the deployed one, so it has to say what the backend + * stores, or the next deploy would see a change that already happened. */ +export function setDeployedOnBehalfOf( + policy: RunAs, + user: DeployingUser, + folderDefault?: string +): void { + const runsAs = deployedPermissionedAs(user, policy.on_behalf_of, folderDefault) + if (!runsAs || runsAs === policy.on_behalf_of) return + policy.on_behalf_of = runsAs + policy.on_behalf_of_email = runsAs === `u/${user?.username}` ? user?.email : undefined } diff --git a/frontend/src/lib/components/apps/editor/appDeploy.test.ts b/frontend/src/lib/components/apps/editor/appDeploy.test.ts new file mode 100644 index 0000000000..d820e4b7de --- /dev/null +++ b/frontend/src/lib/components/apps/editor/appDeploy.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest' +import { setDeployedOnBehalfOf } from './appDeploy.svelte' + +// The app editors keep the policy they sent as the deployed one. +describe('setDeployedOnBehalfOf', () => { + const admin = { username: 'admin', email: 'admin@x.dev', is_admin: true } + const member = { username: 'alice', email: 'alice@x.dev' } + + it('writes the stored user into the policy, with the email only for the deployer', () => { + const forMember = { on_behalf_of: 'u/bot', on_behalf_of_email: 'bot@x.dev' } + setDeployedOnBehalfOf(forMember, member) + expect(forMember).toEqual({ on_behalf_of: 'u/alice', on_behalf_of_email: 'alice@x.dev' }) + + const newInFolder: { on_behalf_of?: string; on_behalf_of_email?: string } = {} + setDeployedOnBehalfOf(newInFolder, admin, 'u/folder') + expect(newInFolder).toEqual({ on_behalf_of: 'u/folder', on_behalf_of_email: undefined }) + }) +}) diff --git a/frontend/src/lib/components/apps/editor/appDraftSettings.test.ts b/frontend/src/lib/components/apps/editor/appDraftSettings.test.ts new file mode 100644 index 0000000000..c84930493a --- /dev/null +++ b/frontend/src/lib/components/apps/editor/appDraftSettings.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import type { Policy } from '$lib/gen' +import { withDraftPolicySettings } from './appDraftSettings' + +describe('withDraftPolicySettings', () => { + it('keeps a setting the draft turned off, and the undrafted fields from the deployed policy', () => { + const deployed = { + execution_mode: 'anonymous', + sandbox: true, + frontend_sdk_scopes: ['resources:read'], + triggerables_v2: { 'a:rawscript/x': {} } + } as unknown as Policy + // Sandbox off drops the key, and the scopes with it; a stale drafted access mode is ignored. + const draft = { execution_mode: 'publisher' } as Partial + expect(withDraftPolicySettings(deployed, draft)).toEqual({ + execution_mode: 'anonymous', + triggerables_v2: { 'a:rawscript/x': {} } + }) + }) +}) diff --git a/frontend/src/lib/components/apps/editor/appDraftSettings.ts b/frontend/src/lib/components/apps/editor/appDraftSettings.ts new file mode 100644 index 0000000000..9b1d216902 --- /dev/null +++ b/frontend/src/lib/components/apps/editor/appDraftSettings.ts @@ -0,0 +1,67 @@ +import type { Policy } from '$lib/gen' + +/** Policy fields a draft leaves to the deployed row: the ones `updatePolicy` rebuilds from the + * app value on every deploy, and who can open the app, which the editor holds until Deploy. */ +const UNDRAFTED_POLICY_KEYS = [ + 'triggerables', + 'triggerables_v2', + 's3_inputs', + 'allowed_s3_keys', + 'execution_mode' +] + +/** The part of a policy an app draft carries (sandbox, on-behalf-of, SDK scopes). The derived + * part describes the deployed value, and a draft holding it would differ from the deployed row + * after every runnable edit. */ +export function policySettings(policy: Policy | Partial | undefined): Partial { + const settings: Record = { ...(policy ?? {}) } + for (const k of UNDRAFTED_POLICY_KEYS) delete settings[k] + return settings as Partial +} + +export type AppDraftSettings = { + policy: Partial + labels: string[] +} + +/** The settings an app draft mirrors onto the App value, normalized so the editor's mirror and + * the deployed baseline it is compared against agree on "unchanged". */ +export function appDraftSettings(s: { + policy?: Policy | Partial + labels?: string[] | null +}): AppDraftSettings { + return { + policy: policySettings(s.policy), + labels: s.labels ?? [] + } +} + +/** A drafted policy's settings over the deployed policy's undrafted fields. Every setting comes + * from the draft, absent ones included: a setting turned off is absent from the draft's JSON, + * and spreading the draft over the deployed policy would turn it back on. */ +export function withDraftPolicySettings( + deployed: Policy | undefined, + draftSettings: Partial +): Policy { + const d = (deployed ?? {}) as Record + const undrafted = Object.fromEntries( + UNDRAFTED_POLICY_KEYS.filter((k) => d[k] !== undefined).map((k) => [k, d[k]]) + ) + return { ...policySettings(draftSettings), ...undrafted } as Policy +} + +/** A classic app's settings as the draft states them, falling back field by field to the + * deployed row for a draft that predates mirroring them. */ +export function draftOrDeployedSettings( + parts: { + policy?: Record + labels?: string[] + }, + row: { policy?: Policy; labels?: string[] | null } +): AppDraftSettings { + const deployed = appDraftSettings(row) + return { + policy: parts.policy ? policySettings(parts.policy as Partial) : deployed.policy, + labels: parts.labels ?? deployed.labels + } +} diff --git a/frontend/src/lib/components/apps/editor/appSettingsBadges.ts b/frontend/src/lib/components/apps/editor/appSettingsBadges.ts new file mode 100644 index 0000000000..1d1bd4442c --- /dev/null +++ b/frontend/src/lib/components/apps/editor/appSettingsBadges.ts @@ -0,0 +1,97 @@ +import { Globe, Link, PlugZap, ShieldCheck, Tag, UserCog, Users } from 'lucide-svelte' +import type { Policy } from '$lib/gen' +import type { ScriptSettingsBadge } from '$lib/components/scriptSettings' + +/** The badges of an app's Metadata section. */ +export function getAppMetadataBadges(labels: string[] | undefined): ScriptSettingsBadge[] { + return labels?.length + ? [ + { + key: 'labels', + short: 'Labels', + setting: 'labels', + label: 'Labels', + icon: Tag, + detail: labels.join(', ') + } + ] + : [] +} + +/** The badges of an app's Permissions section. `sandboxed` also holds when the role forces it. */ +export function getAppPermissionBadges( + policy: Pick, + sandboxed: boolean +): ScriptSettingsBadge[] { + const badges: ScriptSettingsBadge[] = [] + const runsAs = policy.on_behalf_of ?? policy.on_behalf_of_email + if (runsAs) { + badges.push({ + key: 'on_behalf_of', + short: 'On behalf', + setting: 'on-behalf-of', + label: 'Run on behalf of', + icon: UserCog, + detail: runsAs + }) + } + if (sandboxed) { + badges.push({ + key: 'sandbox', + short: 'Sandbox', + setting: 'sandbox', + label: 'Sandbox isolation', + icon: ShieldCheck, + detail: "The app's browser-side code gets a narrowly scoped token" + }) + if (policy.frontend_sdk_scopes?.length) { + badges.push({ + key: 'frontend_sdk_scopes', + short: 'API access', + setting: 'sandbox', + label: 'Frontend API access', + icon: PlugZap, + detail: policy.frontend_sdk_scopes.join(', ') + }) + } + } + return badges +} + +/** The badges of an app's Sharing section: who beyond members can open it, and its custom URL. */ +export function getAppSharingBadges( + executionMode: Policy['execution_mode'], + customPath: string | undefined +): ScriptSettingsBadge[] { + const badges: ScriptSettingsBadge[] = [] + if (executionMode === 'anonymous') { + badges.push({ + key: 'access', + short: 'Public', + setting: 'access', + label: 'Public', + icon: Globe, + detail: 'Anyone with the secret URL, no login' + }) + } else if (executionMode === 'guest') { + badges.push({ + key: 'access', + short: 'Guests', + setting: 'access', + label: 'Guests', + icon: Users, + detail: 'Guests your identity provider authenticates, plus members' + }) + } + if (customPath) { + badges.push({ + key: 'custom_path', + short: 'Custom URL', + setting: 'custom-url', + label: 'Custom URL', + icon: Link, + detail: customPath + }) + } + return badges +} diff --git a/frontend/src/lib/components/apps/editor/publishAccessMode.ts b/frontend/src/lib/components/apps/editor/publishAccessMode.ts new file mode 100644 index 0000000000..2e3a015c3c --- /dev/null +++ b/frontend/src/lib/components/apps/editor/publishAccessMode.ts @@ -0,0 +1,29 @@ +import { AppService, type Policy } from '$lib/gen' + +/** Writes who can open the app to the deployed app at once. The server applies the mode alone to + * the deployed policy under the deploy's row lock: sandbox, SDK scopes and the run-as user wait + * for a deploy, and a concurrent deploy neither reverts the mode nor is reverted by it. */ +export async function publishAccessMode( + workspace: string, + path: string, + mode: NonNullable +): Promise { + await AppService.updateApp({ + workspace, + path, + requestBody: { + execution_mode: mode, + // The clicker's draft holds edits this write does not deploy. + skip_draft_deletion: true + } + }) +} + +/** The policy an update deploy sends. The mode changes only through `publishAccessMode`, so an + * update states none and the server keeps the deployed one, read under the row lock: a policy read + * earlier would otherwise put back a mode changed since. */ +export function policyForUpdate

>(policy: P): P { + const sent = { ...policy } + delete sent.execution_mode + return sent +} diff --git a/frontend/src/lib/components/apps/types.ts b/frontend/src/lib/components/apps/types.ts index a72d54507e..abef47ef50 100644 --- a/frontend/src/lib/components/apps/types.ts +++ b/frontend/src/lib/components/apps/types.ts @@ -237,6 +237,14 @@ export type App = { * sends it as the summary on deploy. */ summary?: string + /** + * The app settings, persisted on the autosaved App like `summary` so an undeployed settings + * change survives a reload and Review & Deploy deploys it. Draft-only: stripped from the + * deployed value (`classicAppDraftParts`). `policy` holds only `policySettings`; deploy + * recomputes the runnable whitelist and keeps the deployed access mode. + */ + policy?: Partial + labels?: string[] } export type ConnectingInput = { 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 66d105a216..24a81b5298 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -233,6 +233,9 @@ vi.mock('$lib/gen', async () => { getAppByVersion: vi.fn(async () => { throw new Error('getAppByVersion mock not configured') }), + getAppLiteByPath: vi.fn(async () => { + throw new Error('getAppLiteByPath mock not configured') + }), listApps: vi.fn(async () => []) }), ResourceService: wrapService(actual.ResourceService, { @@ -4676,7 +4679,8 @@ describe('global AI tools', () => { data: { tables: ['orders'] } }, summary: 'Updated report', - policy: expect.objectContaining({ execution_mode: 'anonymous' }), + // An update leaves the mode to the deployed row, so a stale draft can't revert it. + policy: expect.not.objectContaining({ execution_mode: expect.anything() }), deployment_message: undefined }, js: 'bundled js', @@ -4690,9 +4694,16 @@ describe('global AI tools', () => { // Deploying is what makes an app's runnables reachable, so it is the one moment the // exposure is both true and known. it('discloses who can open an app after a deploy', async () => { - const deployApp = async (path: string, policy: Record) => { + const deployApp = async ( + path: string, + policy: Record, + storedMode = policy.execution_mode + ) => { vi.mocked(AppService.existsApp).mockResolvedValueOnce(true) vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({} as any) + vi.mocked(AppService.getAppLiteByPath).mockResolvedValueOnce({ + policy: { execution_mode: storedMode } + } as any) seedBackendDraft( 'raw_app', path, @@ -4718,6 +4729,10 @@ describe('global AI tools', () => { // anyone outside the deployers group — so the note must not name an identity. expect(open.message).not.toContain('u/alice') + // An update keeps the deployed mode, so the note follows the stored row, not a stale draft. + const keptPublic = await deployApp('f/apps/kept', { execution_mode: 'publisher' }, 'anonymous') + expect(keptPublic.message).toContain('anyone with the URL, without logging in') + // Guest is a real widening only where the deployment admits guests; stored on one // that does not, it is inert and the note would announce an exposure that does not // exist. diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index ea5c6a3e7d..6f1ba399b7 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -90,6 +90,7 @@ import { formatDataTableRef } from '$lib/components/raw_apps/dataTableRefUtils' import { appSourceToDraftValue } from '$lib/components/raw_apps/rawAppDraftValue' +import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode' import { conformBuilderAppPolicy } from '$lib/components/raw_apps/builderAppPolicy' import { capabilitiesInWorkspace } from '$lib/operatorWriteRights' import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities' @@ -9623,27 +9624,6 @@ async function deployDraft( `not working until they are.` } - // `policy` is the mode being written, so the exposure is stated from the value in - // hand. What a runnable runs as is the server's to decide, so the note names who - // can reach the app and never an identity. - if (policy.execution_mode === 'anonymous') { - deployNote = - `${deployNote ? `${deployNote} ` : ''}This app is deployed as anonymous: its ` + - `backend runnables are now reachable by anyone with the URL, without logging in. ` + - `Tell the user plainly what is now reachable and by whom.` - } else if (policy.execution_mode === 'guest') { - // Only where the guest door actually opens: below that, silence — a false note - // is worse than none. The standing cap is a live count no read settles, so the - // note says the door is open, not that every newcomer gets in. - if (await guestAccessIsLive(workspace)) { - deployNote = - `${deployNote ? `${deployNote} ` : ''}This app is deployed as guest: anyone ` + - `the instance's identity provider authenticates can now open it and run its ` + - `backend runnables, member of this workspace or not. Tell the user plainly ` + - `what is now reachable and by whom.` - } - } - toolCallbacks.setToolStatus(toolId, { content: `Bundling app "${path}"...` }) @@ -9707,7 +9687,8 @@ async function deployDraft( } } deployedPath = targetPath - if (await AppService.existsApp({ workspace, path: targetPath })) { + const isUpdate = await AppService.existsApp({ workspace, path: targetPath }) + if (isUpdate) { // Omit custom_path on update for now. The backend preserves it when absent, while // sending it requires admin privileges; this chat deploy path does not yet mirror // the raw app editor's user/admin-specific custom_path handling. @@ -9719,7 +9700,8 @@ async function deployDraft( path: targetPath, value: rawAppValue, summary, - policy, + policy: policyForUpdate(policy), + labels: appValue.labels, deployment_message: deploymentMessage, // Preserve the policy's on_behalf_of: this chat deploy path has no // on-behalf-of selector, so without the flag the backend resets it to @@ -9741,6 +9723,7 @@ async function deployDraft( policy, deployment_message: deploymentMessage, custom_path: appValue.custom_path, + labels: appValue.labels, // Preserve the policy's on_behalf_of (see update branch above). preserve_on_behalf_of: policy.on_behalf_of ? true : undefined }, @@ -9749,6 +9732,38 @@ async function deployDraft( } }) } + + // An update keeps the deployed mode, so the exposure is stated from the stored row, + // never from the draft. What a runnable runs as is the server's to decide, so the + // note names who can reach the app and never an identity. + const storedMode = isUpdate + ? ( + await AppService.getAppLiteByPath({ workspace, path: targetPath }).catch( + () => undefined + ) + )?.policy?.execution_mode + : policy.execution_mode + if (storedMode === 'anonymous') { + deployNote = + `${deployNote ? `${deployNote} ` : ''}This app is deployed as anonymous: its ` + + `backend runnables are now reachable by anyone with the URL, without logging in. ` + + `Tell the user plainly what is now reachable and by whom.` + } else if (storedMode === 'guest') { + // Only where the guest door actually opens: below that, silence — a false note + // is worse than none. The standing cap is a live count no read settles, so the + // note says the door is open, not that every newcomer gets in. + if (await guestAccessIsLive(workspace)) { + deployNote = + `${deployNote ? `${deployNote} ` : ''}This app is deployed as guest: anyone ` + + `the instance's identity provider authenticates can now open it and run its ` + + `backend runnables, member of this workspace or not. Tell the user plainly ` + + `what is now reachable and by whom.` + } + } else if (storedMode === undefined) { + deployNote = + `${deployNote ? `${deployNote} ` : ''}Its access mode could not be read back ` + + `after the deploy, so tell the user to check who can open the app.` + } break } } diff --git a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts index 6368a27e24..1a214312f4 100644 --- a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts +++ b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts @@ -68,6 +68,7 @@ function normalizeAppDraftValue(value: AppDraftValue): AppDraftValue { data: value.data ?? { ...DEFAULT_RAW_APP_DATA }, policy: value.policy === undefined ? undefined : clone(value.policy), custom_path: value.custom_path, + labels: value.labels, // Carry the fork-base version through the whitelist — it is dropped on every // save otherwise, which would defeat the stale-draft check. parent_version: value.parent_version, diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts index 949a016b65..c01044c85f 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts @@ -78,6 +78,7 @@ export type AppDraftValue = { data?: any policy?: Policy custom_path?: string + labels?: string[] // Fork base: the deployed app version this draft was started from, pinned at // fork. The app analog of a script's parent_hash / a flow's version_id. parent_version?: number diff --git a/frontend/src/lib/components/itemSettings/RunOnBehalfOfSetting.svelte b/frontend/src/lib/components/itemSettings/RunOnBehalfOfSetting.svelte index d699f6cc7f..2ed15d6d02 100644 --- a/frontend/src/lib/components/itemSettings/RunOnBehalfOfSetting.svelte +++ b/frontend/src/lib/components/itemSettings/RunOnBehalfOfSetting.svelte @@ -5,6 +5,7 @@ type OnBehalfOfChoice } from '$lib/components/OnBehalfOfSelector.svelte' import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { AlertTriangle } from 'lucide-svelte' import SettingToggle from './SettingToggle.svelte' import { canPreserveOnBehalfOf, deployedPermissionedAs, WM_DEPLOYERS_GROUP } from './onBehalfOf' @@ -60,7 +61,11 @@ const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) - let canPreserve = $derived(canPreserveOnBehalfOf(actingUser)) + const roleCaps = useRoleCapabilities() + // A builder's app draft may name no other user (docs/operator-builder-rights.md), so their editor + // drops the deployed one and the deploy stores them, `wm_deployers` or not. + let composesApp = $derived(kind === 'app' && $roleCaps.apps === 'compose') + let canPreserve = $derived(canPreserveOnBehalfOf(actingUser) && !composesApp) // "Me" is the acting user in the target workspace, its username and its email alike: usernames // are per-workspace, and the backend rejects a pair that names two accounts. let myPermissionedAs = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined) @@ -69,9 +74,9 @@ // opens, and a choice that restarts empty lets the selector reselect the deployed user over // the one picked. let choice: OnBehalfOfChoice = $derived.by(() => { - // No user picked deploys the folder default, even over a deployed user: a script renamed - // into the folder is created at its new path. - if (!permissionedAs && !email && folderDefault) return 'custom' + // No user held deploys the folder default, even over a deployed user: a script renamed + // into the folder is created at its new path. Outside one, it deploys the deployer. + if (!permissionedAs && !email) return folderDefault ? 'custom' : 'me' const keepsSaved = savedPermissionedAs ? (permissionedAs ?? savedPermissionedAs) === savedPermissionedAs : !!savedEmail && (email ?? savedEmail) === savedEmail @@ -140,7 +145,11 @@ > {/if} - {#if !canPreserve} + {#if composesApp} +

+ Apps you build run on behalf of you once you deploy them. +
+ {:else if !canPreserve}
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
diff --git a/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts b/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts index e62af85cca..488f1fb6a4 100644 --- a/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts +++ b/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts @@ -15,7 +15,7 @@ describe('onBehalfOf', () => { expect(deployedPermissionedAs(member, 'u/bot', 'u/folder')).toBe('u/alice') }) - it('asks on every app deploy, and on flow or script deploys that change the run-as user', () => { + it('asks on a first deploy, and on deploys that change the run-as user', () => { const none = { email: undefined, permissionedAs: undefined, @@ -25,8 +25,11 @@ describe('onBehalfOf', () => { const bot = { email: 'bot@x.dev', permissionedAs: 'u/bot' } const deployedAsBot = { savedEmail: 'bot@x.dev', savedPermissionedAs: 'u/bot' } - expect(deployAsksOnBehalfOf('app', { user: admin, ...none })).toBe(true) expect(deployAsksOnBehalfOf('flow', { user: admin, ...none })).toBe(false) + // An app runs on behalf of someone from its first deploy. + expect(deployAsksOnBehalfOf('app', { user: admin, ...none })).toBe(true) + expect(deployAsksOnBehalfOf('app', { user: admin, ...bot, ...deployedAsBot })).toBe(false) + expect(deployAsksOnBehalfOf('app', { user: member, ...bot, ...deployedAsBot })).toBe(true) // A first deploy, or one that turns it on. expect(deployAsksOnBehalfOf('script', { user: admin, ...none, ...bot })).toBe(true) expect(deployAsksOnBehalfOf('flow', { user: admin, ...none, folderDefault: 'u/f' })).toBe(true) diff --git a/frontend/src/lib/components/itemSettings/onBehalfOf.ts b/frontend/src/lib/components/itemSettings/onBehalfOf.ts index 3576340498..d1c7cad268 100644 --- a/frontend/src/lib/components/itemSettings/onBehalfOf.ts +++ b/frontend/src/lib/components/itemSettings/onBehalfOf.ts @@ -34,10 +34,10 @@ export function deployedPermissionedAs( return user?.username ? `u/${user.username}` : undefined } -/** Whether a deploy asks first whose access the item will run with. Every app deploy asks, since - * all its viewers use that access. A flow or script deploy asks when it starts running on behalf - * of someone, changes who, or stops: a deploy that keeps the deployed user has nothing new to - * confirm. `saved*` are the deployed version's, unset before the first deploy. */ +/** Whether a deploy asks first whose access the item will run with. A deploy asks when the item + * starts running on behalf of someone, changes who, or stops: a deploy that keeps the deployed + * user has nothing new to confirm. An app always runs on behalf of someone, so its first deploy + * always asks. `saved*` are the deployed version's, unset before the first deploy. */ export function deployAsksOnBehalfOf( kind: 'flow' | 'script' | 'app', deploy: { @@ -49,9 +49,8 @@ export function deployAsksOnBehalfOf( folderDefault?: string } ): boolean { - if (kind === 'app') return true const deployedHoldsUser = !!(deploy.savedPermissionedAs ?? deploy.savedEmail) - if (!deploy.email && !deploy.folderDefault) return deployedHoldsUser + if (kind !== 'app' && !deploy.email && !deploy.folderDefault) return deployedHoldsUser if (!deployedHoldsUser) return true return ( deployedPermissionedAs(deploy.user, deploy.permissionedAs, deploy.folderDefault) !== diff --git a/frontend/src/lib/components/otherUserDraftDiff.ts b/frontend/src/lib/components/otherUserDraftDiff.ts index f462a3bc83..6b79294880 100644 --- a/frontend/src/lib/components/otherUserDraftDiff.ts +++ b/frontend/src/lib/components/otherUserDraftDiff.ts @@ -1,11 +1,12 @@ import { AppService, FlowService, ScriptService, type UserDraftItemKind } from '$lib/gen' import type { Value } from '$lib/utils' import { DEFAULT_DATA, extractDataConfig } from '$lib/components/raw_apps/dataTableRefUtils' +import { appDraftSettings } from '$lib/components/apps/editor/appDraftSettings' /** * Fetch the currently-deployed value for an item, in the same shape its draft * is stored — so it can be the "original" side of a draft-vs-deployed diff. - * App drafts hold the bare `App` value (unwrap `.value`); raw-app drafts hold a + * App drafts hold the bare `App` value with the row's metadata mirrored on; raw-app drafts hold a * flat bundle (`files`/`runnables`/`data`/`summary`/`policy`/`custom_path`), * with `summary`/`policy`/`custom_path` living OUTSIDE `.value` on the deployed * row — so we project the deployed app into that bundle (via the same @@ -26,9 +27,15 @@ export async function fetchDeployedValueForDiff( })) as unknown as Value case 'flow': return (await FlowService.getFlowByPath({ workspace, path })) as unknown as Value - case 'app': - return (await AppService.getAppByPath({ workspace, path, getDraft: false })) - .value as unknown as Value + case 'app': { + // The editor mirrors the summary and settings onto the bare App it drafts. + const app = await AppService.getAppByPath({ workspace, path, getDraft: false }) + return { + ...(app.value as object), + summary: app.summary, + ...appDraftSettings(app) + } as unknown as Value + } case 'raw_app': { const app = await AppService.getAppByPath({ workspace, path, getDraft: false }) const v = (app.value ?? {}) as any diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 29c5b3147c..8a689b0b62 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -170,6 +170,8 @@ /** User-typed path when it differs from `savedApp.path`. The route injects * it as `draft_path` so the home row shows the friendly name, not `draft_{uuid}`. */ pendingDraftPath?: string | undefined + /** The labels being edited, for the route's autosaved draft. */ + pendingDraftSettings?: { labels: string[] } | undefined // Threaded to the AutosaveIndicator's "Reset to deployed" button. /** `Exit & see details`: see RawAppEditorHeader. */ onDetails?: (e: { path: string }) => void @@ -228,7 +230,7 @@ runnables = $bindable({}), data = $bindable(DEFAULT_DATA), newApp, - policy, + policy = $bindable(), summary = $bindable(''), path, newPath = undefined, @@ -245,6 +247,7 @@ defaultSplitWithPreview = true, compact = false, pendingDraftPath = $bindable(undefined), + pendingDraftSettings = $bindable(), onDetails, onOpenFork, onResetToDeployed, @@ -2696,6 +2699,7 @@ addEventListener('message', function (e) { bind:savedApp bind:summary bind:pendingDraftPath + bind:pendingDraftSettings {version} {onTakeLatest} {draftBaseVersion} @@ -2706,7 +2710,7 @@ addEventListener('message', function (e) { } onSavedNewAppPath?.(newAppPath) }} - {policy} + bind:policy {diffDrawer} {newApp} {newPath} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index e006e25265..b94f5ed62d 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -1,4 +1,12 @@ + deploymentMsg ?? '', (v) => (deploymentMsg = v)} + bind:email={policy.on_behalf_of_email} + bind:permissionedAs={policy.on_behalf_of} + savedEmail={isNewApp ? undefined : deployedRunAs?.on_behalf_of_email} + savedPermissionedAs={isNewApp ? undefined : deployedRunAs?.on_behalf_of} + isNew={isNewApp} + folderDefault={folderDefault.value} + folderDefaultLoading={folderDefault.loading} + executionMode={policy.execution_mode} + targetWorkspace={opWorkspace ?? ''} + rawApp + onConfirmed={deployNow} +/> + - - closeSaveDrawer()}> - {#snippet actions()} -
- - -
- {/snippet} - - -
-
+ (historyBrowserDrawerOpen = false)}> @@ -1183,6 +1195,25 @@ + {#if !phoneTopbar} +
+ {#if settingsHaveErrors} + + {/if} + +
+ {/if} +
+ /> {/snippet} diff --git a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte index e5e25a5ff1..9ee5ddd98c 100644 --- a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte @@ -293,11 +293,8 @@ ) function appPolicy(): Policy { + // No run-as user: the deploy dialog resolves it, the folder's default first. const policy: Policy = { - on_behalf_of: $userStore?.username.includes('@') - ? $userStore?.username - : `u/${$userStore?.username}`, - on_behalf_of_email: $userStore?.email, execution_mode: 'publisher', sandbox: true } diff --git a/frontend/src/lib/components/raw_apps/rawAppDraftValue.ts b/frontend/src/lib/components/raw_apps/rawAppDraftValue.ts index 35ff0805d3..ced0919644 100644 --- a/frontend/src/lib/components/raw_apps/rawAppDraftValue.ts +++ b/frontend/src/lib/components/raw_apps/rawAppDraftValue.ts @@ -48,6 +48,7 @@ export function appSourceToDraftValue(app: any, fallback?: any): AppDraftValue { data: normalizeRawAppData(value), policy: app.policy ?? fallback?.policy, custom_path: app.custom_path ?? fallback?.custom_path, + labels: app.labels ?? fallback?.labels, // Pin the fork base: a deployed app exposes `versions` (head = last); an // existing draft already carries `parent_version` — preserve it. parent_version: diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index 50ea1e054a..103f5f7f3f 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -375,11 +375,21 @@ bind:data={cell.store.val.data} bind:summary={cell.store.val.summary} bind:pendingDraftPath + bind:pendingDraftSettings={ + () => undefined, + (s: { labels: string[] } | undefined) => { + // The header reports its labels on mount too: only a change reaches the draft. + const v = cell.store.val + if (!s || !v) return + if ((v.labels ?? []).join('\n') !== s.labels.join('\n')) v.labels = s.labels + } + } + labels={cell.store.val.labels} newPath={cell.store.val.draft_path ?? cell.store.val.path} {path} autosaveWorkspace={workspaceId} autosavePath={path} - policy={cell.store.val.policy} + bind:policy={cell.store.val.policy} bind:savedApp={cell.saved.val} version={cell.store.val?.parent_version ?? cell.saved.val?.deployed_version} draftBaseVersion={cell.store.val?.parent_version != null diff --git a/frontend/src/lib/components/sessions/appDraftCodec.ts b/frontend/src/lib/components/sessions/appDraftCodec.ts index 7d9f4b048f..0878d39cd0 100644 --- a/frontend/src/lib/components/sessions/appDraftCodec.ts +++ b/frontend/src/lib/components/sessions/appDraftCodec.ts @@ -11,6 +11,7 @@ export type RawAppDraft = { summary: string policy?: any custom_path?: string + labels?: string[] // User-typed path while the app is parked at a `…/draft_` storage path. // Must round-trip through the draft so the home/review/Drafts lists render the // friendly name (they read `value->>'draft_path'`) — and so editing the path @@ -32,6 +33,7 @@ export type RuntimeRawApp = { data: RawAppData policy: any custom_path?: string + labels?: string[] draft_path?: string parent_version?: number } @@ -47,6 +49,7 @@ export function runtimeRawAppToDraft(raw: RuntimeRawApp): RawAppDraft { data: raw.data, policy: raw.policy, custom_path: raw.custom_path, + labels: raw.labels, draft_path: raw.draft_path, parent_version: raw.parent_version } @@ -63,6 +66,7 @@ export function applyDraftToRuntimeRawApp(raw: RuntimeRawApp, dv: RawAppDraft): data: dv.data, policy: dv.policy ?? raw.policy, custom_path: dv.custom_path ?? raw.custom_path, + labels: dv.labels ?? raw.labels, draft_path: dv.draft_path ?? raw.draft_path, // The incoming draft's own fork base, absence included: this round-trips into the // next save, so falling back to the runtime's version would give that content a diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index 2e58f3f5b1..1a4cfb310e 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -166,6 +166,7 @@ export interface RawAppRuntimeValue { summary: string path: string custom_path?: string + labels?: string[] draft_path?: string /** The app_version this cell's content forked from, carried so the editor's deploy * guard and diff drawer compare the same pair the full-page editor does. */ @@ -1157,6 +1158,7 @@ function createRuntime(session: Session): SessionRuntime { summary: draftValue?.summary ?? result.summary ?? '', path: result.path, custom_path: draftValue?.custom_path ?? result.custom_path, + labels: draftValue?.labels ?? result.labels, draft_path: draftValue?.draft_path, // Only a fresh checkout forks from the head; a draft keeps its own base, // unknown included, or it would read as up to date. See loadScript. @@ -1189,9 +1191,8 @@ function createRuntime(session: Session): SessionRuntime { files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) }, runnables: builder ? {} : structuredClone(STARTER_RUNNABLES), data: { ...DEFAULT_DATA }, + // No run-as user: the deploy dialog resolves it, the folder's default first. policy: { - on_behalf_of: user?.username.includes('@') ? user.username : `u/${user?.username}`, - on_behalf_of_email: user?.email, execution_mode: 'publisher', sandbox: true }, diff --git a/frontend/src/lib/rawAppDeploy.ts b/frontend/src/lib/rawAppDeploy.ts index d146f74bc1..ce68c1091e 100644 --- a/frontend/src/lib/rawAppDeploy.ts +++ b/frontend/src/lib/rawAppDeploy.ts @@ -16,6 +16,7 @@ import { isAdminIn } from '$lib/user' import { bundleRawAppDraft } from '$lib/components/copilot/chat/global/rawAppBundlerBridge' import type { AppDraftValue } from '$lib/components/copilot/chat/global/workspaceItems' import { updateRawAppPolicy } from '$lib/components/raw_apps/rawAppPolicy' +import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode' import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA } from '$lib/components/raw_apps/dataTableRefUtils' import { appSourceToDraftValue, @@ -56,9 +57,6 @@ export async function deployRawAppValue({ // The value carries the runnables, so the policy's triggerables have to be // recomputed from it or the deployed app can't call what it now contains. const policy = (await updateRawAppPolicy(runnables, currentPolicy)) as Policy - if (!policy.execution_mode) { - policy.execution_mode = 'publisher' - } const bundle = await bundleRawAppDraft({ workspace, files }) @@ -72,7 +70,7 @@ export async function deployRawAppValue({ // version can still carry the pre-`data` datatable shapes. value: { files, runnables, data: normalizeRawAppData(plainValue) }, summary: summary ?? '', - policy, + policy: policyForUpdate(policy), deployment_message: deploymentMessage, // custom_path changes require admin (see deployRawAppDraft). custom_path: isAdmin ? (customPath ?? '') : undefined, @@ -139,9 +137,10 @@ export async function deployRawAppDraft( path: targetPath, value: rawAppValue, summary, - policy, + policy: policyForUpdate(policy), deployment_message: deploymentMessage, custom_path: isAdmin ? (value.custom_path ?? '') : undefined, + labels: value.labels, // Preserve the policy's on_behalf_of: this draft-deploy path has no // on-behalf-of selector, so without the flag the backend resets it to // the deploying user (gated server-side by can_preserve_on_behalf_of). @@ -162,6 +161,7 @@ export async function deployRawAppDraft( policy, deployment_message: deploymentMessage, custom_path: value.custom_path, + labels: value.labels, // Preserve the policy's on_behalf_of (see update branch above). preserve_on_behalf_of: policy.on_behalf_of ? true : undefined }, diff --git a/frontend/src/lib/utils_draft_deploy.test.ts b/frontend/src/lib/utils_draft_deploy.test.ts index e7c9a66153..0962cc693f 100644 --- a/frontend/src/lib/utils_draft_deploy.test.ts +++ b/frontend/src/lib/utils_draft_deploy.test.ts @@ -1,11 +1,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { draftBaseIsStale, deployDraft } from './utils_draft_deploy' +import { draftBaseIsStale, deployDraft, getDraftDiffValues } from './utils_draft_deploy' vi.mock('$lib/gen', () => ({ ScriptService: { getScriptByPath: vi.fn(), createScript: vi.fn() }, FlowService: { getFlowByPath: vi.fn(), createFlow: vi.fn(), updateFlow: vi.fn() }, DraftService: { deleteDraft: vi.fn() }, - AppService: {}, + AppService: { getAppByPath: vi.fn(), createApp: vi.fn() }, VariableService: { getVariable: vi.fn(), createVariable: vi.fn(), updateVariable: vi.fn() }, ResourceService: { getResource: vi.fn(), updateResource: vi.fn(), createResource: vi.fn() }, ScheduleService: {}, @@ -31,9 +31,13 @@ vi.mock('$lib/rawAppDeploy', () => ({ deployRawAppDraft: vi.fn() })) vi.mock('$lib/components/raw_apps/utils', () => ({ canonicalRawAppDiffValue: vi.fn() })) vi.mock('$lib/appDiffSides', () => ({ classicAppDraftParts: vi.fn() })) vi.mock('$lib/utils_deployable', () => ({ TRIGGER_RUNTIME_IGNORE: [] })) +vi.mock('$lib/components/apps/editor/appPolicy', () => ({ + updatePolicy: vi.fn(async (_app: unknown, policy: unknown) => policy) +})) -import { ScriptService, FlowService, VariableService, ResourceService } from '$lib/gen' +import { ScriptService, FlowService, VariableService, ResourceService, AppService } from '$lib/gen' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' +import { classicAppDraftParts } from '$lib/appDiffSides' // draftBaseIsStale compares a draft's base pointer against the deployed head // of the item it was fetched with (`get_draft=true`). Shared by CompareDrafts @@ -143,6 +147,38 @@ describe('deployDraft preserves on_behalf_of', () => { }) }) +// The backend runs an app without `sandbox` same-origin with each viewer's session, and a draft +// saved before drafts carried the policy has none to give. +describe('deployDraft: draft-only classic app', () => { + beforeEach(() => vi.clearAllMocks()) + + it('creates the app sandboxed when its draft carries no policy', async () => { + vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({ draft: { grid: [] } } as any) + vi.mocked(classicAppDraftParts).mockReturnValueOnce({ value: { grid: [] } } as any) + + expect(await deployDraft('app', 'u/alice/dash', 'ws', { draftOnly: true })).toEqual({ + success: true + }) + expect(AppService.createApp).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ + policy: expect.objectContaining({ execution_mode: 'publisher', sandbox: true }) + }) + }) + ) + }) + + it('shows the sandboxed policy it deploys in the diff', async () => { + vi.mocked(AppService.getAppByPath).mockResolvedValueOnce({ draft: { grid: [] } } as any) + vi.mocked(classicAppDraftParts) + .mockReturnValueOnce({ value: {} } as any) + .mockReturnValueOnce({ value: { grid: [] } } as any) + + const { draft } = await getDraftDiffValues('app', 'u/alice/dash', 'ws', true) + expect(draft.policy).toEqual({ sandbox: true }) + }) +}) + // Muting writes to the deployed row at once, so a draft saved before it holds a stale copy, and // the backend unmutes on a deploy that sends `false`. describe('deployDraft keeps the deployed mute flag', () => { diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index 4ffbfc2508..7a5bf66553 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -32,14 +32,23 @@ import { GcpTriggerService, AzureTriggerService, EmailTriggerService, + type Policy, type UserDraftItemKind } from '$lib/gen' +import type { App } from '$lib/components/apps/types' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import type { DeployResult } from '$lib/utils_workspace_deploy' import { TRIGGER_RUNTIME_IGNORE } from '$lib/utils_deployable' import { deployRawAppDraft } from '$lib/rawAppDeploy' import { canonicalRawAppDiffValue } from '$lib/components/raw_apps/utils' import { classicAppDraftParts } from '$lib/appDiffSides' +import { + appDraftSettings, + draftOrDeployedSettings, + policySettings, + withDraftPolicySettings +} from '$lib/components/apps/editor/appDraftSettings' +import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' import { invalidateWorkspaceComparison } from '$lib/workspaceComparison' import { setLocalDraftHint } from '$lib/localDraftHints.svelte' @@ -188,7 +197,12 @@ export function canonicalDraftSideValue(kind: DraftKind, value: unknown): unknow if (kind === 'raw_app') return canonicalRawAppDiffValue((value ?? {}) as Record) if (kind === 'app') { const parts = classicAppDraftParts(value) - return { summary: parts.summary ?? '', value: parts.value } + return { + summary: parts.summary ?? '', + value: parts.value, + ...(parts.policy ? { policy: policySettings(parts.policy) } : {}), + ...(parts.labels ? { labels: parts.labels } : {}) + } } if (kind === 'flow' && value !== null && typeof value === 'object') { const { version_id: _v, ...rest } = value as Record @@ -254,6 +268,11 @@ function canonicalizeDraftDiffValue(kind: DraftKind, raw: any, isDraft: boolean) return stripScheduleTriggerRuntime(raw) } +/** What a draft-only app deploys with when its draft carries no policy, as a draft saved before + * drafts carried one does: a new app's sandboxed policy, since an empty one deploys it + * unsandboxed. The diff shows the same, or it would show a policy the deploy does not store. */ +const DRAFT_ONLY_APP_POLICY: Policy = { execution_mode: 'publisher', sandbox: true } + /** * Fetch the deployed value and the draft value for an item, for the DiffDrawer * (`mode: 'simple'`, original = deployed, current = draft). For a `draft_only` @@ -345,15 +364,23 @@ export async function getDraftDiffValues( // `value`. Both sides reduce to `{ summary, value }` with the metadata // extracted from the grid, so a summary edit diffs as a summary edit and // the grid never diffs against draft-only markers. + // The settings are compared too, or a settings-only draft reads as equal to the deployed + // app and the auto-prune drops it. const deployedParts = classicAppDraftParts(r.value) const draftParts = r.draft != null ? classicAppDraftParts(r.draft) : deployedParts - const deployed = { summary: r.summary ?? '', value: deployedParts.value, path: r.path } + const deployed = { + summary: r.summary ?? '', + value: deployedParts.value, + path: r.path, + ...appDraftSettings(r) + } return { deployed: draftOnly ? EMPTY_DEPLOYED.app!(undefined) : deployed, draft: { summary: draftParts.summary ?? r.summary ?? '', value: draftParts.value, - path: draftParts.draftPath ?? r.path + path: draftParts.draftPath ?? r.path, + ...draftOrDeployedSettings(draftParts, draftOnly ? { policy: DRAFT_ONLY_APP_POLICY } : r) }, hasDraft: r.draft != null, noDeployed: r.no_deployed === true @@ -571,35 +598,37 @@ export async function deployDraft( // plus a `draft_path` when the path was renamed) — NOT wrapped in // { value, summary, policy } like script/flow drafts. So the deploy value // is the draft object itself; fall back to the deployed value when there's - // no draft. `draft_path` and `summary` are draft-only fields mirrored onto - // the App value (the editor drops them on deploy), so strip them from the - // value and apply them as the deploy path / summary column. - // `parent_version` is the draft's stale-check base, never deployed. - const draft = r.draft as Record | undefined - const { - draft_path: draftPath, - summary: draftSummary, - parent_version: _pv, - ...appValue - } = draft ?? r.value ?? {} - // Policy isn't carried in the app draft, so it comes from the deployed app - // (or a default). custom_path requires admin on update; non-admins send - // undefined so the backend preserves the existing route. The draft has no - // custom_path, so admins fall back to the deployed route (`''` when none). + // no draft. The draft-only fields mirrored onto the App value (staged path, + // summary, settings, fork base) are stripped from it and applied as the + // app row's columns. + const parts = classicAppDraftParts(r.draft ?? r.value ?? {}) + const appValue = parts.value as App + const deployedPolicy = draftOnly ? DRAFT_ONLY_APP_POLICY : (r.policy as Policy) + const settings = draftOrDeployedSettings(parts, draftOnly ? { policy: deployedPolicy } : r) + // The runnable whitelist is rebuilt from the value being deployed: the deployed + // policy's whitelist describes the previous value. Loaded lazily, as it pulls in the + // app component tree. + const { updatePolicy } = await import('$lib/components/apps/editor/appPolicy') + const policy = await updatePolicy( + appValue, + withDraftPolicySettings(deployedPolicy, settings.policy) + ) + // custom_path requires admin on update; non-admins send undefined so the + // backend preserves the existing route. The draft has no custom_path, so + // admins fall back to the deployed route (`''` when none). const isAdmin = await isAdminIn(workspace) - const policy = r.policy ?? { execution_mode: 'publisher', sandbox: true } const requestBody = { value: appValue, - summary: draftSummary ?? r.summary ?? '', - policy, + summary: parts.summary ?? r.summary ?? '', + policy: draftOnly ? policy : policyForUpdate(policy), // Honor the draft's intended path; `draft_path` holds the user-typed path // for a never-deployed app parked at a `u/{user}/draft_{uuid}` storage key. - path: draftPath ?? r.path ?? path, + path: parts.draftPath ?? r.path ?? path, custom_path: isAdmin ? (r.custom_path ?? '') : undefined, + labels: settings.labels, deployment_message: deploymentMessage, - // The draft carries no on-behalf-of selector — the policy comes straight - // from the deployed app. Preserve its on_behalf_of (the backend resets it - // to the deploying user without this flag, gated by can_preserve_on_behalf_of). + // Preserve the drafted on_behalf_of (the backend resets it to the deploying + // user without this flag, gated by can_preserve_on_behalf_of). preserve_on_behalf_of: policy?.on_behalf_of ? true : undefined } // Same as flows: draft-only apps have no app row → create; diff --git a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte index d32c279802..0bac041bb3 100644 --- a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte @@ -22,6 +22,11 @@ import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' import { runResetToDeployed } from '$lib/userDraftToast' + import { classicAppDraftParts } from '$lib/appDiffSides' + import { + appDraftSettings, + withDraftPolicySettings + } from '$lib/components/apps/editor/appDraftSettings' let app = $state(undefined as (AppWithLastVersion & { value: any }) | undefined) /** Seeded from a hub app this load; AppEditor relaxes a few authoring affordances. */ @@ -227,7 +232,8 @@ // never compares equal (and a summary-only edit still counts as a change). ({ ...(structuredClone(stateSnapshot(backendApp.value)) as App), - summary: backendApp.summary + summary: backendApp.summary, + ...appDraftSettings(structuredClone(stateSnapshot(backendApp))) } as App) // `other_drafts_users` only computed when `getDraft`; don't clobber the // known list on a `getDraft:false` reload. See /scripts/edit's loader. @@ -359,6 +365,16 @@ // `app = undefined` first, unmounting AppEditor and releasing the UserDraft // entry, so the remount starts fresh — no local discard is needed here // (and `UserDraft.discard` would POST `value: null`, a spurious autosave). + // The draft's settings win over the deployed ones here; `savedApp` keeps the deployed ones, + // which the settings drawer compares against. + const draftParts = classicAppDraftParts(backendApp.value) + backendApp = { + ...backendApp, + policy: draftParts.policy + ? withDraftPolicySettings(backendApp.policy, draftParts.policy) + : backendApp.policy, + labels: draftParts.labels ?? backendApp.labels + } as typeof backendApp app = backendApp } @@ -495,7 +511,7 @@ {deployedBaseline} newPath={app.value?.draft_path ?? app.path} path={page.params.path ?? ''} - policy={app.policy} + bind:policy={app.policy} bind:savedApp {diffDrawer} version={app.versions ? app.versions[app.versions.length - 1] : undefined} diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index a90a5ae587..09a1e6ec01 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -3,7 +3,7 @@ import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { AppService } from '$lib/gen' - import { userStore, workspaceStore } from '$lib/stores' + import { workspaceStore } from '$lib/stores' import { useRoleCapabilities, workspaceListLoaded } from '$lib/operatorWriteRights' import { readFieldsRecursively } from '$lib/utils' import { goto } from '$lib/navigation' @@ -51,6 +51,7 @@ summary: string policy?: any custom_path?: string + labels?: string[] /** User-typed path the home list renders, set only when it differs * from the deployed/seeded `savedApp.path`. */ draft_path?: string @@ -72,6 +73,8 @@ * `savedApp.path`; mirrored into the draft below as `draft_path` for the * home list's friendly name. */ let pendingDraftPath = $state(undefined) + /** The labels the header is editing, mirrored into the draft. */ + let pendingDraftSettings = $state<{ labels: string[] } | undefined>(undefined) let savedApp: | { @@ -128,6 +131,7 @@ readFieldsRecursively(policy) void summary void pendingDraftPath + void pendingDraftSettings draftSync.draft = { files: currentFiles, runnables, @@ -135,6 +139,7 @@ summary, policy, custom_path: savedApp?.custom_path, + labels: pendingDraftSettings ? pendingDraftSettings.labels : (labels ?? []), parent_version: parentVersion, // Persist the typed path as `draft_path` only when it actually differs // from the current path — a `draft_path` equal to the baseline is a @@ -235,11 +240,8 @@ path }) } + // No run-as user: the deploy dialog resolves it, the folder's default first. const defaultPolicy = { - on_behalf_of: $userStore?.username.includes('@') - ? $userStore?.username - : `u/${$userStore?.username}`, - on_behalf_of_email: $userStore?.email, execution_mode: 'publisher', sandbox: true } as any @@ -373,6 +375,7 @@ summary: backendApp.summary ?? '', policy: backendApp.policy, custom_path: backendApp.custom_path, + labels: backendApp.labels ?? [], parent_version: parentVersion }) ) as RawAppDraft) @@ -389,6 +392,7 @@ summary?: string policy?: any custom_path?: string + labels?: string[] draft_path?: string } | undefined @@ -406,6 +410,7 @@ backendApp.summary = savedRawAppDraft?.summary ?? '' backendApp.policy = savedRawAppDraft?.policy ?? { execution_mode: 'publisher', sandbox: true } backendApp.custom_path = savedRawAppDraft?.custom_path + backendApp.labels = savedRawAppDraft?.labels backendApp.path = page.params.path ?? '' } else if (savedRawAppDraft) { backendApp.value = { @@ -418,13 +423,18 @@ if (savedRawAppDraft.policy !== undefined) backendApp.policy = savedRawAppDraft.policy if (savedRawAppDraft.custom_path !== undefined) backendApp.custom_path = savedRawAppDraft.custom_path + if (savedRawAppDraft.labels !== undefined) backendApp.labels = savedRawAppDraft.labels } const backendApp_ = structuredClone(stateSnapshot(backendApp)) savedApp = { summary: backendApp_.summary, value: backendApp_.value as any, path: backendApp_.path, - policy: backendApp_.policy, + // The deployed policy, not the draft's swapped in above: the header and the settings + // measure what a deploy changes against it. + policy: deployedBaseline + ? structuredClone(stateSnapshot(deployedBaseline.policy)) + : backendApp_.policy, custom_path: backendApp_.custom_path, labels: backendApp_.labels, no_deployed: backendApp_.no_deployed @@ -452,6 +462,7 @@ data = v.data ?? { ...DEFAULT_DATA } summary = v.summary ?? '' policy = v.policy ?? {} + labels = v.labels ?? labels // Their draft's own fork base: the bundle is rebuilt from these pieces, so // leaving `parentVersion` on ours would deploy their content claiming a base // it never had. @@ -473,6 +484,7 @@ summary, policy, custom_path: savedApp?.custom_path, + labels: labels ?? [], parent_version: parentVersion, ...(pendingDraftPath ? { draft_path: pendingDraftPath } : {}) } as RawAppDraft, @@ -692,11 +704,12 @@ bind:data bind:summary bind:pendingDraftPath + bind:pendingDraftSettings {newPath} {labels} path={page.params.path ?? ''} liveEditorDraftStoragePath={path} - {policy} + bind:policy bind:savedApp {diffDrawer} newApp={isNewApp}