From b3ab8e22b37a666d4ffdbead4a80c406502254b2 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 26 Nov 2026 15:00:28 +0000 Subject: [PATCH] feat: overwrite or discard each path conflict when reassigning user items (#12683) * feat: overwrite or discard each path conflict when reassigning user items Co-Authored-By: Claude Opus 5.5 * fix: guard offboarding conflict resolution against stale rows and cascades Co-Authored-By: Claude Opus 5.5 * fix: match the departing user's rows literally in offboarding cleanup Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../tests/offboarding.rs | 118 ++++++++++++++++ backend/windmill-api/openapi.yaml | 25 ++++ backend/windmill-api/src/offboarding.rs | 110 ++++++++++++--- .../GlobalUserOffboardingModal.svelte | 27 ++-- .../components/OffboardConflictList.svelte | 133 ++++++++++++++++++ .../components/UserOffboardingModal.svelte | 26 ++-- .../src/lib/components/offboarding-utils.ts | 105 +++++++++++++- 7 files changed, 489 insertions(+), 55 deletions(-) create mode 100644 frontend/src/lib/components/OffboardConflictList.svelte diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index ce5d0578ca..fd9e7ad707 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -482,12 +482,130 @@ async fn test_offboard_conflicts(db: Pool) -> anyhow::Result<()> { .any(|c| c.as_str().unwrap().contains("conflict_script")), "conflict should mention conflict_script" ); + // The UI resolves each conflict by deleting one side, so both paths must be reported. + let items = body["conflict_items"] + .as_array() + .expect("conflict_items should be array"); + assert_eq!(items.len(), conflicts.len()); + let item = items + .iter() + .find(|c| c["source_path"] == "u/test-user-2/conflict_script") + .expect("conflict_items should include conflict_script"); + assert_eq!(item["kind"], "script"); + assert_eq!(item["target_path"], "u/test-user/conflict_script"); + assert_eq!(item["workspace_id"], "test-workspace"); // No summary when conflicts exist assert!(body["summary"].is_null()); Ok(()) } +/// Usernames may hold `_`, a LIKE wildcard: another user's item matched by it maps to itself, so +/// it must be neither reported as a conflict (which offers to delete it) nor cleaned up as stale. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_conflicts_underscore_username(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "INSERT INTO usr (workspace_id, email, username, is_admin, role) + VALUES ('test-workspace', 'underscore@windmill.dev', 'test_user', false, 'User')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description) + VALUES ('test-workspace', 'u/testxuser/var', 'v', false, '')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind) + VALUES ('test-workspace', 'main', 'datatable', 'u/testxuser/s', 'script')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path) + VALUES ('test-workspace', 'u/testxuser/s', 'script', 'f/shared/lib')", + ) + .execute(&db) + .await?; + + let resp = authed(client().post(ws_url(port, "offboard/test_user"))) + .json(&json!({ "reassign_to": "u/test-user", "delete_user": false })) + .send() + .await?; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await?; + assert!(body["conflict_items"].is_null(), "{body}"); + let untouched: i64 = sqlx::query_scalar( + "SELECT (SELECT COUNT(*) FROM asset WHERE usage_path = 'u/testxuser/s') + + (SELECT COUNT(*) FROM dependency_map WHERE importer_path = 'u/testxuser/s') + + (SELECT COUNT(*) FROM variable WHERE path = 'u/testxuser/var')", + ) + .fetch_one(&db) + .await?; + assert_eq!(untouched, 3, "another user's rows must survive the reassignment"); + + Ok(()) +} + +/// Resolving a conflict by deleting the target leaves that script's `dependency_map` and `asset` +/// rows behind, on the keys the departing user's rows are renamed onto. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_over_deleted_target(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path) + VALUES ('test-workspace', 'u/test-user/conflict_script', 'script', 'f/shared/lib'), + ('test-workspace', 'u/test-user-2/conflict_script', 'script', 'f/shared/lib')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind) + VALUES ('test-workspace', 'main', 'datatable', 'u/test-user/conflict_script', 'script'), + ('test-workspace', 'main', 'datatable', 'u/test-user-2/conflict_script', 'script')", + ) + .execute(&db) + .await?; + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/scripts/delete/p/u/test-user/conflict_script" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) + .json(&json!({ "reassign_to": "u/test-user", "delete_user": false })) + .send() + .await?; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await?; + assert!(body["summary"].is_object(), "{body}"); + + let importers: Vec = sqlx::query_scalar( + "SELECT importer_path FROM dependency_map + WHERE workspace_id = 'test-workspace' AND imported_path = 'f/shared/lib'", + ) + .fetch_all(&db) + .await?; + assert_eq!(importers, vec!["u/test-user/conflict_script".to_string()]); + let users: Vec = sqlx::query_scalar( + "SELECT usage_path FROM asset WHERE workspace_id = 'test-workspace' AND path = 'main'", + ) + .fetch_all(&db) + .await?; + assert_eq!(users, vec!["u/test-user/conflict_script".to_string()]); + + Ok(()) +} + #[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] async fn test_offboard_tokens_deleted(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 7e12f14dd0..4c7e907136 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -33947,9 +33947,34 @@ components: items: type: string description: "List of path conflicts that block the offboarding. Empty on success." + conflict_items: + type: array + items: + $ref: "#/components/schemas/OffboardPathConflict" + description: "The same conflicts as `conflicts`, structured. Empty on success." summary: $ref: "#/components/schemas/OffboardSummary" + OffboardPathConflict: + type: object + properties: + workspace_id: + type: string + kind: + type: string + description: "Item kind, as its table name (script, flow, app, resource, variable, schedule, eval_dataset, http_trigger, ...)" + source_path: + type: string + description: "The offboarded user's item, under u/{username}/" + target_path: + type: string + description: "The existing item at the reassignment target" + required: + - workspace_id + - kind + - source_path + - target_path + OffboardSummary: type: object properties: diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index 8dc53a7c72..a912351bbb 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -85,10 +85,44 @@ fn default_true() -> bool { pub(crate) struct OffboardResponse { #[serde(skip_serializing_if = "Vec::is_empty")] conflicts: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + conflict_items: Vec, #[serde(skip_serializing_if = "Option::is_none")] summary: Option, } +impl OffboardResponse { + fn conflicts(conflict_items: Vec, global: bool) -> Self { + let conflicts = conflict_items + .iter() + .map(|c| { + if global { + format!("[{}] {}: {}", c.workspace_id, c.kind, c.target_path) + } else { + format!("{}: {}", c.kind, c.target_path) + } + }) + .collect(); + Self { conflicts, conflict_items, summary: None } + } + + fn done(summary: OffboardSummary) -> Self { + Self { conflicts: vec![], conflict_items: vec![], summary: Some(summary) } + } +} + +/// An item of the departing user whose reassigned path is already taken. +#[derive(Serialize)] +struct PathConflict { + workspace_id: String, + /// The table the item lives in (`script`, `flow`, `http_trigger`, ...). + kind: String, + /// The departing user's item, under `u/{username}/`. + source_path: String, + /// The existing item the reassignment would collide with. + target_path: String, +} + #[derive(Serialize)] struct OffboardSummary { scripts_reassigned: i64, @@ -415,7 +449,7 @@ pub(crate) async fn offboard_workspace_user( let conflicts = check_path_conflicts(&db, &w_id, &username, &req.reassign_to).await?; if !conflicts.is_empty() { - return Ok(Json(OffboardResponse { conflicts, summary: None })); + return Ok(Json(OffboardResponse::conflicts(conflicts, false))); } let email = sqlx::query_scalar!( @@ -478,10 +512,7 @@ pub(crate) async fn offboard_workspace_user( .await?; } - Ok(Json(OffboardResponse { - conflicts: vec![], - summary: Some(summary), - })) + Ok(Json(OffboardResponse::done(summary))) } // ---- Instance-level endpoints ---- @@ -557,16 +588,11 @@ pub(crate) async fn offboard_global_user( &reassignment.reassign_to, ) .await?; - for c in conflicts { - all_conflicts.push(format!("[{}] {}", &ws.workspace_id, c)); - } + all_conflicts.extend(conflicts); } } if !all_conflicts.is_empty() { - return Ok(Json(OffboardResponse { - conflicts: all_conflicts, - summary: None, - })); + return Ok(Json(OffboardResponse::conflicts(all_conflicts, true))); } let mut tx = db.begin().await?; @@ -654,10 +680,7 @@ pub(crate) async fn offboard_global_user( tx.commit().await?; - Ok(Json(OffboardResponse { - conflicts: vec![], - summary: Some(total_summary), - })) + Ok(Json(OffboardResponse::done(total_summary))) } // ---- Validation helpers ---- @@ -769,7 +792,7 @@ async fn check_path_conflicts( w_id: &str, username: &str, reassign_to: &str, -) -> Result> { +) -> Result> { let new_prefix = format!("{}/", reassign_to); let mut conflicts = Vec::new(); @@ -800,11 +823,14 @@ async fn check_path_conflicts( "flow" => " AND NOT t1.archived", _ => "", }; + // A conflict is resolved by deleting one of its two paths, so the source must be the + // departing user's: `starts_with` rather than LIKE, where the `_` usernames may hold + // matches any character and would report another user's item as conflicting with itself. // SAFETY: `table_name` comes from a hardcoded allowlist `tables`, not user input. - let rows: Vec = sqlx::query_scalar(&format!( - "SELECT REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ + let rows: Vec<(String, String)> = sqlx::query_as(&format!( + "SELECT DISTINCT t1.path, REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ FROM {table} t1 \ - WHERE t1.path LIKE ('u/' || $1 || '/%') AND t1.workspace_id = $2{extra_filter} \ + WHERE starts_with(t1.path, 'u/' || $1 || '/') AND t1.workspace_id = $2{extra_filter} \ AND EXISTS ( \ SELECT 1 FROM {table} t2 \ WHERE t2.path = REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ @@ -818,8 +844,13 @@ async fn check_path_conflicts( .fetch_all(db) .await?; - for path in rows { - conflicts.push(format!("{}: {}", table_name, path)); + for (source_path, target_path) in rows { + conflicts.push(PathConflict { + workspace_id: w_id.to_string(), + kind: table_name.to_string(), + source_path, + target_path, + }); } } @@ -1216,12 +1247,47 @@ async fn offboard_user_from_workspace<'c>( &new_prefix, username, w_id ).execute(&mut **tx).await?; + // Deleting a script or flow by path leaves its asset usages behind, on the keys the moved + // usages take; such a row is an orphan or the same usage, so it is dropped, not renamed onto. + sqlx::query( + "DELETE FROM asset d WHERE d.workspace_id = $3 AND EXISTS ( \ + SELECT 1 FROM asset s \ + WHERE s.workspace_id = $3 AND starts_with(s.usage_path, 'u/' || $2 || '/') \ + AND s.ctid <> d.ctid AND s.path = d.path AND s.kind = d.kind AND s.usage_kind = d.usage_kind \ + AND REGEXP_REPLACE(s.usage_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.usage_path)", + ) + .bind(&new_prefix) + .bind(username) + .bind(w_id) + .execute(&mut **tx) + .await?; + sqlx::query!( r#"UPDATE asset SET usage_path = REGEXP_REPLACE(usage_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE usage_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, &new_prefix, username, w_id ).execute(&mut **tx).await?; // ---- dependency_map ---- + // Deleting an item by path leaves its rows here, so an item deleted to make room at the + // target still holds the keys the moved rows take. A row already holding a moved row's final + // key is such an orphan or the same edge, so it is dropped rather than renamed onto. + // SAFETY: `column` comes from the hardcoded list below, not user input. + for column in ["importer_path", "imported_path"] { + sqlx::query(&format!( + "DELETE FROM dependency_map d WHERE d.workspace_id = $3 AND EXISTS ( \ + SELECT 1 FROM dependency_map s \ + WHERE s.workspace_id = $3 AND starts_with(s.{column}, 'u/' || $2 || '/') \ + AND s.ctid <> d.ctid AND s.importer_node_id = d.importer_node_id AND s.importer_kind = d.importer_kind \ + AND REGEXP_REPLACE(s.importer_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.importer_path \ + AND REGEXP_REPLACE(s.imported_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.imported_path)" + )) + .bind(&new_prefix) + .bind(username) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + sqlx::query!( r#"UPDATE dependency_map SET importer_path = REGEXP_REPLACE(importer_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE importer_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, &new_prefix, username, w_id diff --git a/frontend/src/lib/components/GlobalUserOffboardingModal.svelte b/frontend/src/lib/components/GlobalUserOffboardingModal.svelte index 38bbf7b191..aa739a2b64 100644 --- a/frontend/src/lib/components/GlobalUserOffboardingModal.svelte +++ b/frontend/src/lib/components/GlobalUserOffboardingModal.svelte @@ -4,11 +4,12 @@ import { apiErrorMessage, classNames } from '$lib/utils' import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte' import { UserService, FolderService } from '$lib/gen' - import type { WorkspaceOffboardPreview } from '$lib/gen' + import type { OffboardPathConflict, WorkspaceOffboardPreview } from '$lib/gen' import { sendUserToast } from '$lib/toast' import Toggle from '$lib/components/Toggle.svelte' import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte' - import { countPaths } from './offboarding-utils' + import OffboardConflictList from './OffboardConflictList.svelte' + import { countPaths, withoutConflict } from './offboarding-utils' type Props = { open: boolean @@ -25,7 +26,7 @@ let submitting = $state(false) let doReassign = $state(true) let deleteUser = $state(true) - let conflicts: string[] = $state([]) + let conflicts: OffboardPathConflict[] = $state([]) $effect(() => { deleteUser = !reassignOnly @@ -169,8 +170,8 @@ delete_user: deleteUser } }) - if (result.conflicts && result.conflicts.length > 0) { - conflicts = result.conflicts + if (result.conflict_items && result.conflict_items.length > 0) { + conflicts = result.conflict_items } else { sendUserToast( deleteUser @@ -315,17 +316,11 @@ {/if} {#if conflicts.length > 0} - -

These items already exist at the target. Rename or delete them, or choose a - different user/folder.

-
    - {#each conflicts as conflict, i (i)} -
  • {conflict}
  • - {/each} -
-
+ (conflicts = withoutConflict(conflicts, c))} + /> {/if} {/if} diff --git a/frontend/src/lib/components/OffboardConflictList.svelte b/frontend/src/lib/components/OffboardConflictList.svelte new file mode 100644 index 0000000000..92d3dd7632 --- /dev/null +++ b/frontend/src/lib/components/OffboardConflictList.svelte @@ -0,0 +1,133 @@ + + + +

+ These items already exist at the target. For each one, overwrite the existing item with the + reassigned one, or discard the reassigned one and keep the existing item. You can also choose a + different user/folder. +

+
    + {#each conflicts as conflict (`${conflict.workspace_id}:${conflict.kind}:${conflict.source_path}`)} + {@const href = itemHref(conflict.kind, conflict.target_path)} +
  • + + {#if showWorkspace} + [{conflict.workspace_id}] + {/if} + {kindLabel(conflict.kind)}: + {#if href && !showWorkspace} + {conflict.target_path} + {:else} + {conflict.target_path} + {/if} + + {#if canDeleteKind(conflict.kind)} + + + {/if} +
  • + {/each} +
+
+ + (pending = undefined)} +> + {#if pending} +

+ {#if pending.action === 'overwrite'} + The existing {kindLabel(pending.conflict.kind)} + {pending.conflict.target_path} will be deleted, and + {pending.conflict.source_path} will be moved to that path on reassignment. + {:else} + The {kindLabel(pending.conflict.kind)} + {pending.conflict.source_path} will be deleted instead of + being reassigned. The existing + {pending.conflict.target_path} is kept. + {/if} +

+ {/if} +
diff --git a/frontend/src/lib/components/UserOffboardingModal.svelte b/frontend/src/lib/components/UserOffboardingModal.svelte index c4dbbc537c..8eeab997a4 100644 --- a/frontend/src/lib/components/UserOffboardingModal.svelte +++ b/frontend/src/lib/components/UserOffboardingModal.svelte @@ -4,12 +4,13 @@ import { apiErrorMessage, classNames } from '$lib/utils' import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte' import { UserService, FolderService } from '$lib/gen' - import type { OffboardPreview } from '$lib/gen/types.gen' + import type { OffboardPathConflict, OffboardPreview } from '$lib/gen/types.gen' import { workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' import Toggle from '$lib/components/Toggle.svelte' import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte' - import { countPaths } from './offboarding-utils' + import OffboardConflictList from './OffboardConflictList.svelte' + import { countPaths, withoutConflict } from './offboarding-utils' type Props = { open: boolean @@ -24,7 +25,7 @@ let preview = $state(undefined as OffboardPreview | undefined) let loading = $state(false) let submitting = $state(false) - let conflicts: string[] = $state([]) + let conflicts: OffboardPathConflict[] = $state([]) let doReassign = $state(true) let targetKind: 'user' | 'folder' = $state('user') @@ -117,8 +118,8 @@ delete_user: deleteUser } }) - if (result.conflicts && result.conflicts.length > 0) { - conflicts = result.conflicts + if (result.conflict_items && result.conflict_items.length > 0) { + conflicts = result.conflict_items } else { sendUserToast( deleteUser @@ -221,17 +222,10 @@ {/if} {#if conflicts.length > 0} - -

These items already exist at the target. Rename or delete them, or choose a - different user/folder.

-
    - {#each conflicts as conflict, i (i)} -
  • {conflict}
  • - {/each} -
-
+ (conflicts = withoutConflict(conflicts, c))} + /> {/if} {/if} diff --git a/frontend/src/lib/components/offboarding-utils.ts b/frontend/src/lib/components/offboarding-utils.ts index 11f266e101..b920979b7f 100644 --- a/frontend/src/lib/components/offboarding-utils.ts +++ b/frontend/src/lib/components/offboarding-utils.ts @@ -1,4 +1,25 @@ -import type { OffboardAffectedPaths } from '$lib/gen' +import { + AiEvalsService, + AmqpTriggerService, + AppService, + AzureTriggerService, + EmailTriggerService, + FlowService, + GcpTriggerService, + HttpTriggerService, + KafkaTriggerService, + MqttTriggerService, + NatsTriggerService, + PostgresTriggerService, + ResourceService, + ScheduleService, + ScriptService, + SqsTriggerService, + VariableService, + WebsocketTriggerService, + type OffboardAffectedPaths, + type OffboardPathConflict +} from '$lib/gen' export function pl(n: number, singular: string): string { return `${n} ${singular}${n === 1 ? '' : 's'}` @@ -115,3 +136,85 @@ export function downloadCsv(rows: string[][], filename: string) { a.click() URL.revokeObjectURL(url) } + +type DeleteFn = (p: { workspace: string; path: string }) => Promise + +// Keyed by the table names the offboarding conflict check reports. Scripts and flows are +// deleted rather than archived: an archived item still holds its path and keeps the conflict. +const DELETE_BY_KIND: Record = { + script: (p) => ScriptService.deleteScriptByPath(p), + flow: (p) => FlowService.deleteFlowByPath(p), + app: (p) => AppService.deleteApp(p), + resource: (p) => ResourceService.deleteResource(p), + variable: (p) => VariableService.deleteVariable(p), + schedule: (p) => ScheduleService.deleteSchedule(p), + eval_dataset: (p) => AiEvalsService.deleteEvalDataset(p), + http_trigger: (p) => HttpTriggerService.deleteHttpTrigger(p), + websocket_trigger: (p) => WebsocketTriggerService.deleteWebsocketTrigger(p), + kafka_trigger: (p) => KafkaTriggerService.deleteKafkaTrigger(p), + postgres_trigger: (p) => PostgresTriggerService.deletePostgresTrigger(p), + mqtt_trigger: (p) => MqttTriggerService.deleteMqttTrigger(p), + amqp_trigger: (p) => AmqpTriggerService.deleteAmqpTrigger(p), + nats_trigger: (p) => NatsTriggerService.deleteNatsTrigger(p), + sqs_trigger: (p) => SqsTriggerService.deleteSqsTrigger(p), + gcp_trigger: (p) => GcpTriggerService.deleteGcpTrigger(p), + azure_trigger: (p) => AzureTriggerService.deleteAzureTrigger(p), + email_trigger: (p) => EmailTriggerService.deleteEmailTrigger(p) +} + +const TRASHED_KINDS = new Set(['script', 'flow', 'app', 'resource', 'variable', 'schedule']) + +export function canDeleteKind(kind: string): boolean { + return kind in DELETE_BY_KIND +} + +export function isTrashedKind(kind: string): boolean { + return TRASHED_KINDS.has(kind) +} + +export async function deleteItemOfKind( + kind: string, + workspace: string, + path: string +): Promise { + const del = DELETE_BY_KIND[kind] + if (!del) throw new Error(`Cannot delete items of kind ${kind}`) + await del({ workspace, path }) +} + +export function withoutConflict( + conflicts: OffboardPathConflict[], + resolved: OffboardPathConflict +): OffboardPathConflict[] { + return conflicts.filter( + (c) => + !( + c.workspace_id === resolved.workspace_id && + c.kind === resolved.kind && + c.source_path === resolved.source_path + ) + ) +} + +/** + * Deleting a resource also deletes the variables linked to it, which can remove one side of a + * variable conflict. Returns the remaining conflicts that no longer have both sides, so the list + * does not offer to "keep" an item that is already gone. + */ +export async function conflictsGoneAfterDelete( + deletedKind: string, + remaining: OffboardPathConflict[] +): Promise { + if (deletedKind !== 'resource') return [] + const variables = remaining.filter((c) => c.kind === 'variable') + const gone = await Promise.all( + variables.map(async (c) => { + const [source, target] = await Promise.all([ + VariableService.existsVariable({ workspace: c.workspace_id, path: c.source_path }), + VariableService.existsVariable({ workspace: c.workspace_id, path: c.target_path }) + ]) + return !source || !target + }) + ) + return variables.filter((_, i) => gone[i]) +}