feat: restore working in a new fork from the Home session composer (#12559)

* feat: restore working in a new fork from the Home session composer

* feat: ask for a fork or, for a bypasser, direct work when building in a protected workspace from Home

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let direct work be left without forking, and check staged ids with the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: suggest a dev workspace's id, badge a staged dev workspace, and stage off a fork lock's dev workspace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem
2026-11-23 21:30:42 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent ff8f2e05fb
commit 1fb70c4fab
24 changed files with 911 additions and 83 deletions
+3 -1
View File
@@ -71,7 +71,9 @@ pub struct WindmillBackend {
/// `DisableDirectDeployment` holds a session to reading and running deployed items for
/// everyone, admins and bypassers included: that workspace takes changes from its dev workspace
/// or a fork, where drafts can go somewhere. Unreadable rules (`None`) hold it too. The in-app
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both.
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. The
/// chat alone lets a bypasser opt one session into working there directly, behind a confirmation
/// an MCP client has no equivalent of, so a token stays held.
fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess {
let locked = rules.map_or(true, |rules| {
rules
@@ -25,6 +25,9 @@
menuItems = undefined,
disableTitle = false,
forkableWorkspaces,
onClick = undefined,
compact = false,
stagedDev = undefined,
class: className = ''
}: {
workspaceId?: string
@@ -61,6 +64,12 @@
// resolves its name/family for a workspace absent from `$userWorkspaces`.
// Omitted consumers fall back to the member-only list.
forkableWorkspaces?: UserWorkspace[]
// For a chip that is not a dropdown's trigger, such as Home's staged fork.
onClick?: () => void
// Fork icon, fork name and chevron only: no parent segment, "(new)" or the base's dev badge.
compact?: boolean
// A staged fork that will be created as a dev workspace: the compact chip shows its badge.
stagedDev?: { label?: string }
class?: string
} = $props()
@@ -76,7 +85,7 @@
)
// The parent segment only appears for a fork of a fork — forking off the
// root is the default and doesn't need spelling out.
const shownParent = $derived(parentId !== root?.id ? parentName : undefined)
const shownParent = $derived(!compact && parentId !== root?.id ? parentName : undefined)
// A fork with a workspace color re-themes the whole chip: forkAccentStyle
// derives light/dark bg+text at that hue (matching the default blue's
@@ -115,6 +124,7 @@
<Button
variant="subtle"
unifiedSize="xs"
{onClick}
title={disableTitle ? undefined : showFork && shownParent ? `${shownParent} → ${name}` : name}
tabindex={interactive ? undefined : -1}
style={accentStyle ?? ''}
@@ -168,9 +178,16 @@
{showFork ? name : (rootLabel ?? name)}
</span>
{/if}
{#if pendingFork}
{#if compact && stagedDev}
<DevWorkspaceBadge
label={stagedDev.label}
{color}
fallbackClass="dark:bg-surface-accent-primary text-white dark:text-white"
class="text-3xs px-1 py-0"
/>
{:else if pendingFork && !compact}
<span class="shrink-0 opacity-70 font-normal">(new)</span>
{:else if currentWs?.is_dev_workspace}
{:else if currentWs?.is_dev_workspace && !compact}
<DevWorkspaceBadge
label={currentWs.dev_workspace_label}
color={color ?? (pendingFork ? undefined : currentWs.color)}
@@ -22,6 +22,7 @@
starter = undefined,
onSent = undefined,
inputPreface,
actingOn,
workModeLock = undefined,
initialInstructions = undefined,
onDraftChange = undefined,
@@ -46,6 +47,7 @@
starter?: import('./starter/starterPrompts.svelte').ChatStarter
onSent?: () => void
inputPreface?: import('svelte').Snippet
actingOn?: import('svelte').Snippet
workModeLock?: import('./workMode').WorkModeLock
// Seed / observe the composer's draft (forwarded to AIChatDisplay).
initialInstructions?: string
@@ -229,6 +231,7 @@
{starter}
{onSent}
{inputPreface}
{actingOn}
{workModeLock}
{initialInstructions}
{onDraftChange}
@@ -128,6 +128,7 @@
starter = undefined,
onSent = undefined,
inputPreface,
actingOn,
workModeLock = undefined,
footerSettings,
initialInstructions = undefined,
@@ -169,6 +170,8 @@
/** After the composer hands a new turn to the host. */
onSent?: () => void
inputPreface?: Snippet
/** Where the session acts: first among the controls after the attach button. */
actingOn?: Snippet
/** Holds a session chat in Use, and says why in the picker. */
workModeLock?: WorkModeLock
/** The settings control at the footer's right edge, where the copilot puts its
@@ -903,6 +906,7 @@
const showFooterLeftControls = $derived(
!footerMessageShown &&
(canAttachFiles ||
!!actingOn ||
attachmentsOffReason !== undefined ||
showContextPicker ||
showAutonomyModeSelector ||
@@ -1563,6 +1567,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
onchange={onFolderInputChange}
/>
{/if}
{@render actingOn?.()}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
@@ -849,6 +849,11 @@ export class AIChatManager implements ChatViewHost {
* Set before `moving`, which waits for the editors to hand over their pending edits. */
moveStarted = $state(false)
onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined
/** The protected workspace the session was opted into working in directly (`direct_in`). */
directInResolver: (() => string | undefined) | undefined = undefined
get directIn(): string | undefined {
return this.directInResolver?.()
}
workModesAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode))
/** Use is the only mode: the workspace is protected, or the user's role builds nothing in it. */
#useOnly = $derived(this.workModesAvailable && !canBuild(this.sessionAccess))
@@ -3234,7 +3239,9 @@ export class AIChatManager implements ChatViewHost {
return
}
const generation = ++this.sessionAccessGeneration
const access = await resolveSessionAccess(workspace)
const access = await resolveSessionAccess(workspace, {
direct: this.directIn === workspace
})
if (generation !== this.sessionAccessGeneration) return
this.sessionAccess = workspace === (this.operatingWorkspace ?? '') ? access : undefined
if (this.mode === AIMode.GLOBAL) {
@@ -60,7 +60,8 @@
}))
const w = work
if (!w) return postures
const lockedOut = (m: AIWorkMode) => !!w.lock && m !== AIWorkMode.USE
const lockedOut = (m: AIWorkMode) => !!w.lock && !w.lock.onPick && m !== AIWorkMode.USE
const onPick = w.lock?.onPick
const workItems: Item[] = workModeOptions
.filter((o) => o.mode !== AIWorkMode.PLAN || w.planAvailable || w.lock)
.map((o, i) => {
@@ -76,7 +77,7 @@
selected: workOption?.mode === o.mode,
disabled: locked,
tooltip: locked ? w.lock?.reason : undefined,
action: () => w.onChange(o.mode)
action: () => (onPick && o.mode !== AIWorkMode.USE ? onPick(o.mode) : w.onChange(o.mode))
}
})
const escape = w.lock?.escape
@@ -1,11 +1,12 @@
import { get } from 'svelte/store'
import { userWorkspaces } from '$lib/stores'
import type { ProtectionRuleset, RoleCapabilities } from '$lib/gen'
import { getWorkspaceRole } from '$lib/user'
import { getWorkspaceRole, type RoleLookup } from '$lib/user'
import { roleCanAuthor, roleCanDraft } from '$lib/editRights'
import { capabilitiesIn, FULL_CAPABILITIES } from '$lib/roleCapabilities'
import { checkDeployRules } from '$lib/utils_workspace_deploy'
import {
canUserBypassRuleKindInRulesets,
isRuleActiveInRulesets,
readProtectionRulesForWorkspace
} from '$lib/workspaceProtectionRules.svelte'
@@ -120,11 +121,31 @@ export function capabilitiesForRole(role: {
* `RestrictDeployToDeployers` alone leaves its users their drafts. Unreadable rules protect too:
* the server holds deploys to the rule but not drafts. The MCP server applies the same rule
* (`workspace_access` in `backend/windmill-api/src/mcp/core.rs`), and in `session_ctx_with` holds a
* role without `run` to reading only, as `capabilitiesForRole` does: change both. */
* role without `run` to reading only, as `capabilitiesForRole` does: change both. The one
* difference is `worksDirectly`, an opt-in only the in-app chat offers. */
function protects(rulesets: ProtectionRuleset[] | undefined): boolean {
return !rulesets || isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment')
}
/** Whether this user may opt a session out of `protects`: the rule's bypassers, admins included,
* whom the server lets deploy there anyway. A session is held unless they explicitly opt it in. */
function worksDirectly(rulesets: ProtectionRuleset[] | undefined, lookup: RoleLookup): boolean {
return (
!!rulesets &&
lookup.kind === 'resolved' &&
canUserBypassRuleKindInRulesets(rulesets, 'DisableDirectDeployment', lookup.user)
)
}
/** Whether this user may work directly in protected `workspace`, for the UI that offers it. */
export async function canWorkDirectly(workspace: string): Promise<boolean> {
const [rulesets, lookup] = await Promise.all([
readProtectionRulesForWorkspace(workspace),
getWorkspaceRole(workspace)
])
return worksDirectly(rulesets, lookup)
}
// The session UI asks this from every preview tab, the composer and the picker, and the rules
// fetch behind it is not cached, so they share one verdict per workspace for a minute.
const READ_ONLY_TTL_MS = 60_000
@@ -166,7 +187,12 @@ export function settledReadOnlyVerdict(workspace: string): boolean | undefined {
return settled && Date.now() - settled.at < READ_ONLY_TTL_MS ? settled.readOnly : undefined
}
export async function resolveSessionAccess(workspace: string): Promise<SessionAccess> {
/** `direct`: the session was opted into working directly in a protected workspace, which
* `worksDirectly` honours for its bypassers only. */
export async function resolveSessionAccess(
workspace: string,
{ direct = false }: { direct?: boolean } = {}
): Promise<SessionAccess> {
const [rulesets, lookup] = await Promise.all([
// Not the memoized verdict above: the chat's toolset follows a rule change on the next send.
readProtectionRulesForWorkspace(workspace),
@@ -176,15 +202,16 @@ export async function resolveSessionAccess(workspace: string): Promise<SessionAc
// `lookup_failed` covers a rejected request AND a body too malformed to map.
getWorkspaceRole(workspace)
])
const held = protects(rulesets) && !(direct && worksDirectly(rulesets, lookup))
if (lookup.kind !== 'resolved') {
return protects(rulesets) ? USE_MODE_ACCESS : fullSessionAccess()
return held ? USE_MODE_ACCESS : fullSessionAccess()
}
const me = lookup.user
const capabilities = capabilitiesIn(
me,
get(userWorkspaces).find((w) => w.id === workspace)
)
if (protects(rulesets)) return capabilities.run ? USE_MODE_ACCESS : NO_RUN_ACCESS
if (held) return capabilities.run ? USE_MODE_ACCESS : NO_RUN_ACCESS
return capabilitiesForRole({
isAdmin: !!me.is_admin || !!me.is_super_admin,
@@ -16,6 +16,9 @@ export type WorkModeLock = {
escape?: { label: string; action: () => void }
/** The session cannot run either: the user's role withholds `run`. */
readsOnly?: boolean
/** Picking a held mode asks how to leave the hold (Home's fork or direct-work choice) rather
* than being refused. */
onPick?: (mode: AIWorkMode) => void
}
/** The answer to a call approved after its session switched to Use: the card or form it
@@ -16,12 +16,18 @@
sessionPageHref,
sessionState,
setSessionDraftPrompt,
setSessionDirectIn,
takeHomeDraftFlash,
takeHomeDraftFocus
} from './sessionState.svelte'
import { useWorkModeLock } from './workModeLock.svelte'
import { AIWorkMode } from '$lib/components/copilot/chat/workMode'
import { homeComposerContext } from './homeComposerContext.svelte'
import WorkInForkToggle from './WorkInForkToggle.svelte'
import ProtectedBuildDialog from './ProtectedBuildDialog.svelte'
import { useForkStaging } from './forkStaging.svelte'
import { resource } from 'runed'
import { canWorkDirectly } from '$lib/components/copilot/chat/global/sessionAccess'
// Home's block is the unsent session's own chat, run by that session's manager: the
// composer, its controls and what a send does are the session's, not a copy of them.
@@ -51,7 +57,43 @@
)
// The draft acts on the workspace the page header names: holdHomeDraft keeps it there, so
// the lock's way out to a dev workspace switches the page.
const workModeLock = useWorkModeLock(() => session, true)
const forkStaging = useForkStaging(() => session)
// On a protected workspace, picking a mode that builds asks where to build.
let protectedPick: { mode: AIWorkMode; workspace: string } | undefined = $state(undefined)
let protectedDialogOpen = $state(false)
const directAllowed = resource(
() => forkStaging.workspace,
async (ws) => (ws ? canWorkDirectly(ws) : false)
)
const workModeLock = useWorkModeLock(
() => session,
true,
() =>
forkStaging.available || directAllowed.current
? (mode) => {
const ws = forkStaging.workspace
if (!ws) return
protectedPick = { mode, workspace: ws }
protectedDialogOpen = true
}
: undefined
)
async function workInFork() {
const pick = protectedPick
if (pick && (await forkStaging.stage())) runtime.manager.setWorkMode(pick.mode)
}
function workDirectly() {
const pick = protectedPick
if (!pick) return
setSessionDirectIn(sessionId, pick.workspace)
void runtime.manager.refreshSessionAccess(pick.workspace)
runtime.manager.setWorkMode(pick.mode)
}
function leaveDirect() {
const ws = session?.direct_in
setSessionDirectIn(sessionId, undefined)
if (ws) void runtime.manager.refreshSessionAccess(ws)
}
const starterPrompts = new StarterPrompts(
() => $workspaceStore ?? undefined,
() => !workModeLock.current && runtime.manager.workMode !== AIWorkMode.USE
@@ -111,6 +153,23 @@
})
</script>
{#snippet actingOn()}
{#if session}
<WorkInForkToggle {session} staging={forkStaging} onLeaveDirect={leaveDirect} />
{/if}
{/snippet}
{#if protectedPick}
<ProtectedBuildDialog
bind:isOpen={protectedDialogOpen}
workspace={protectedPick.workspace}
canFork={forkStaging.available}
canDirect={!!directAllowed.current}
onFork={() => void workInFork()}
onDirect={workDirectly}
/>
{/if}
<!-- Waits for the session's own config, without which the chat cannot say whether AI is on.
Latched, so a workspace switch or a save's reload does not unmount it while the next loads.
The item count decides whether the composer rests collapsed, so it waits for that too
@@ -131,6 +190,7 @@
restsOpen: starterPrompts.empty
}}
{onSent}
{actingOn}
workModeLock={workModeLock.current}
/>
</div>
@@ -0,0 +1,58 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
// Asked when a Home draft on a protected workspace leaves Use: the session builds in a new
// fork, or, for a user the rule lets through, in the workspace itself.
let {
isOpen = $bindable(),
workspace,
canFork,
canDirect,
onFork,
onDirect
}: {
isOpen: boolean
workspace: string
canFork: boolean
canDirect: boolean
onFork: () => void
onDirect: () => void
} = $props()
function pick(choice: () => void) {
isOpen = false
choice()
}
</script>
<Modal2
title="{workspace} is protected"
target="#content"
fixedWidth="xs"
fixedHeight="adaptive"
contentClasses="flex-col gap-4"
bind:isOpen
>
<p class="text-xs text-secondary">
Direct changes to {workspace} are turned off.
{#if canFork}
Build in a new fork instead: it is created when you send your first message, and you deploy
your changes back from it.
{/if}
{#if canDirect}
Its protection lets you through, so you can also work in {workspace} directly.
{/if}
</p>
<div class="flex justify-end gap-2">
<Button variant="subtle" unifiedSize="md" onClick={() => (isOpen = false)}>Cancel</Button>
{#if canDirect}
<Button variant="default" unifiedSize="md" onClick={() => pick(onDirect)}>
Work in {workspace} directly
</Button>
{/if}
{#if canFork}
<Button variant="accent" unifiedSize="md" onClick={() => pick(onFork)}>Work in a fork</Button>
{/if}
</div>
</Modal2>
@@ -0,0 +1,102 @@
<script lang="ts" module>
import { lazyModule } from '$lib/lazyModule.svelte'
const createWorkspaceModule = lazyModule(
() => import('$lib/components/workspaceSettings/CreateWorkspaceInner.svelte')
)
</script>
<script lang="ts">
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte'
import { Badge, Button } from '$lib/components/common'
import { X } from 'lucide-svelte'
import type { Session } from './sessionState.svelte'
import type { useForkStaging } from './forkStaging.svelte'
let {
session,
staging,
onLeaveDirect
}: {
session: Session
staging: ReturnType<typeof useForkStaging>
onLeaveDirect: () => void
} = $props()
const staged = $derived(session.pending_fork)
// Shown even where forking is unavailable: it is then the only way back out of direct work.
const direct = $derived(
!staged && !!session.direct_in && session.direct_in === staging.workspace
? session.direct_in
: undefined
)
function toggle() {
if (staged) staging.unstage()
else void staging.stage()
}
let settingsOpen = $state(false)
function openSettings() {
void createWorkspaceModule.load()
settingsOpen = true
}
</script>
{#if staging.available || direct}
<div class="flex items-center gap-1.5 min-w-0 text-2xs text-secondary">
{#if staging.available}
<label class="flex items-center gap-1.5 shrink-0 cursor-pointer">
<Checkbox checked={!!staged} onChange={toggle} />
<span>Work in fork</span>
</label>
{/if}
{#if direct}
<Badge color="orange" small title="You chose to work in {direct} itself.">
Changes go directly to {direct}
</Badge>
<Button
variant="subtle"
unifiedSize="2xs"
iconOnly
startIcon={{ icon: X }}
title="Stop working in {direct} directly"
onClick={onLeaveDirect}
/>
{/if}
{#if staged}
<WorkspaceScopeTrigger
workspaceId={staged.parent_workspace_id}
pendingFork={staged}
color={staged.settings?.color}
class="min-w-0"
compact
stagedDev={staged.settings?.is_dev_workspace
? { label: staged.settings.dev_workspace_label }
: undefined}
onClick={openSettings}
/>
{/if}
</div>
{/if}
<Modal2
title="Forking {staging.workspace}"
target="#content"
fixedHeight="adaptive"
fixedWidth="sm"
contentClasses="flex-col"
bind:isOpen={settingsOpen}
>
{#if settingsOpen && staged && createWorkspaceModule.current}
{@const CreateWorkspaceInner = createWorkspaceModule.current.default}
<CreateWorkspaceInner
isFork
inModal
stage={{ fork: staged, onStage: staging.save }}
onFinish={() => (settingsOpen = false)}
/>
{/if}
</Modal2>
@@ -0,0 +1,203 @@
import { fromStore } from 'svelte/store'
import {
enterpriseLicense,
maybePremium,
roleCapabilities,
userStore,
userWorkspaces
} from '$lib/stores'
import {
findCanonicalDevWorkspace,
findDefaultForkBase,
findWorkspaceDescendants,
findWorkspaceRoot
} from '$lib/utils/workspaceHierarchy'
import { canCreateFork } from '$lib/utils/editInFork'
import { canFork, capabilitiesIn } from '$lib/roleCapabilities'
import { isCloudHosted } from '$lib/cloud'
import { random_adj } from '$lib/components/random_positive_adjetive'
import { devBadgeText } from '$lib/utils/devWorkspaceLabel'
import { getUserExt } from '$lib/user'
import { WorkspaceService } from '$lib/gen'
import {
canUserBypassRuleKindInRulesets,
isRuleActiveInRulesets,
readProtectionRulesForWorkspace
} from '$lib/workspaceProtectionRules.svelte'
import { getEffectiveWorkspaceId, setSessionPendingFork, type Session } from './sessionState.svelte'
import {
loadForkDefaults,
saveForkDefaults,
type StagedFork,
type StagedForkSettings
} from './sessionForkDefaults'
const WM_FORK_PREFIX = 'wm-fork-'
// A fork is a new workspace, which community edition caps (backend _check_nb_of_workspaces).
const CE_MAX_NON_ADMIN_WORKSPACES = 2
/**
* Staging a new fork for a Home draft's first send: whether the user may, and the fork staged
* with the family's saved defaults under a fresh name. Reads stores: call during component
* initialisation.
*/
export function useForkStaging(session: () => Session | undefined) {
const workspaces = fromStore(userWorkspaces)
const user = fromStore(userStore)
const caps = fromStore(roleCapabilities)
const premium = fromStore(maybePremium)
const license = fromStore(enterpriseLicense)
// The header's workspace, which the draft acts on and a staged fork is staged from.
const workspace = $derived.by(() => {
const s = session()
return s ? getEffectiveWorkspaceId(s) : undefined
})
const root = $derived(findWorkspaceRoot(workspace, workspaces.current))
// The workspace picker's own gate (WorkspaceFamilyPicker): forking is premium on cloud, and a
// workspace that forbids forking can still be worked on through its dev workspace.
const available = $derived(
!!workspace &&
workspace !== 'admins' &&
!session()?.workspace_id &&
(!isCloudHosted() || !!premium.current) &&
(canCreateFork(user.current, caps.current) ||
!!findCanonicalDevWorkspace(workspace, workspaces.current)) &&
(!!license.current ||
workspaces.current.filter((w) => w.id !== 'admins').length < CE_MAX_NON_ADMIN_WORKSPACES)
)
// Workspace ids are unique across the instance, and the list holds only the user's own: the
// server has the last word on whether an id is free.
async function isTaken(id: string): Promise<boolean> {
if (workspaces.current.some((w) => w.id === id)) return true
return await WorkspaceService.existsWorkspace({ requestBody: { id } }).catch(() => false)
}
async function freeId(base: string): Promise<string> {
if (!(await isTaken(base))) return base
let n = 2
while (await isTaken(`${base}-${n}`)) n++
return `${base}-${n}`
}
async function freshForkName(prefix: string): Promise<string> {
for (let i = 0; i < 20; i++) {
const candidate = random_adj()
if (!(await isTaken(`${prefix}${candidate}`))) return candidate
}
const base = random_adj()
let n = 1
while (await isTaken(`${prefix}${base}-${n}`)) n++
return `${base}-${n}`
}
// A workspace has at most one dev workspace, so a saved dev choice applies only while the base
// has none yet, and never on a dev base, which the fork form offers no dev of from a session;
// otherwise the fork is a plain one. The server is asked, as the user may not see that dev.
async function applicableSettings(
parent: string,
settings: StagedForkSettings | undefined
): Promise<StagedForkSettings | undefined> {
if (!settings?.is_dev_workspace) return settings
const parentIsDev = workspaces.current.some((w) => w.id === parent && w.is_dev_workspace)
const hasDev =
parentIsDev ||
(await WorkspaceService.getDevWorkspace({ workspace: parent }).then(
(d) => !!d,
() => true
))
if (!hasDev) return settings
return {
...settings,
is_dev_workspace: false,
dev_workspace_label: undefined,
lock_prod_deploy: undefined,
lock_prod_forking: undefined,
copy_members: false
}
}
// How `ws`'s `DisableWorkspaceForking` rule treats this user: it refuses everyone it does not
// list as a bypass, and a bypass is an explicit choice in the fork form, never a default.
async function forkingRule(ws: string): Promise<'free' | 'bypass' | 'blocked'> {
const [rules, me] = await Promise.all([readProtectionRulesForWorkspace(ws), getUserExt(ws)])
if (!rules) return 'blocked'
if (!isRuleActiveInRulesets(rules, 'DisableWorkspaceForking')) return 'free'
return canUserBypassRuleKindInRulesets(rules, 'DisableWorkspaceForking', me)
? 'bypass'
: 'blocked'
}
// The family's saved base, while it is still a workspace of the family the user may fork, else
// the default one. A base locked against forking gives way to its dev workspace; a bypasser
// without one keeps the base, and the form asks them to confirm the bypass.
async function defaultBase(saved: string | undefined): Promise<string | undefined> {
const family = root ? [root, ...findWorkspaceDescendants(root.id, workspaces.current)] : []
const savedWs = family.find((w) => w.id === saved)
const base =
savedWs && canFork(capabilitiesIn(undefined, savedWs))
? savedWs
: findDefaultForkBase(workspace, workspaces.current)
if (!base) return undefined
const rule = await forkingRule(base.id)
if (rule === 'free') return base.id
const dev = findCanonicalDevWorkspace(base.id, workspaces.current)?.id
return dev ?? (rule === 'bypass' ? base.id : undefined)
}
let staging = false
/** Stage a fork with the saved defaults; whether one is staged once it returns. */
async function stage(): Promise<boolean> {
const s = session()
if (!s || staging) return !!s?.pending_fork
staging = true
const from = workspace
const defaults = loadForkDefaults(root?.id)
try {
const parent = await defaultBase(defaults?.base)
if (!parent) return !!session()?.pending_fork
const settings = await applicableSettings(parent, defaults?.settings)
// A dev workspace is named `<base>-<label>` with no `wm-fork-` prefix, as the fork form names it.
const prefix = settings?.is_dev_workspace ? '' : WM_FORK_PREFIX
const name = settings?.is_dev_workspace
? await freeId(`${parent}-${devBadgeText(settings.dev_workspace_label)}`)
: await freshForkName(prefix)
const now = session()
// The header moved, or the draft was sent or staged, while the server was asked.
if (!now || workspace !== from || now.workspace_id) return !!now?.pending_fork
if (now.pending_fork) return true
setSessionPendingFork(now.id, {
parent_workspace_id: parent,
id: `${prefix}${name}`,
name,
settings
})
return true
} finally {
staging = false
}
}
return {
get available() {
return available
},
get workspace() {
return workspace
},
stage,
unstage() {
const s = session()
if (s) setSessionPendingFork(s.id, undefined)
},
/** Keep `fork` for this draft, and all of it but its name as the family's defaults. */
save(fork: StagedFork) {
const s = session()
if (!s) return
setSessionPendingFork(s.id, fork)
saveForkDefaults(root?.id, { base: fork.parent_workspace_id, settings: fork.settings ?? {} })
}
}
}
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest'
import { stagedForkRequest } from './sessionForkDefaults'
const fork = {
id: 'wm-fork-brave',
name: 'brave',
settings: {
datatables: { main: 'schema_and_data' as const, gone: 'schema_only' as const },
shared_ducklakes: ['lake', 'old_lake'],
shared_storages: ['s3', 'old_s3'],
lock_prod_deploy: true
}
}
const base = {
datatables: [
{ name: 'main' },
{ name: 'extra' },
{ name: 'borrowed', database_workspace_id: 'other' }
],
ducklakes: ['lake'],
storages: ['s3'],
requireIsolation: false
}
describe('stagedForkRequest', () => {
it('drops saved names the base no longer has', () => {
const req = stagedForkRequest(fork, base)
expect(req.forked_datatables).toEqual([
{ name: 'main', new_dbname: 'wm_fork_brave__main', fork_behavior: 'schema_and_data' }
])
expect(req.shared_ducklakes).toEqual(['lake'])
expect(req.shared_storages).toEqual(['s3'])
})
it('keeps saved lake and storage names when the base lists could not be read', () => {
const req = stagedForkRequest(fork, { ...base, ducklakes: undefined, storages: undefined })
expect(req.shared_ducklakes).toEqual(['lake', 'old_lake'])
expect(req.shared_storages).toEqual(['s3', 'old_s3'])
})
it('copies every base-owned table and shares nothing under isolation', () => {
const req = stagedForkRequest(fork, { ...base, requireIsolation: true })
expect(req.forked_datatables.map((d) => [d.name, d.fork_behavior])).toEqual([
['main', 'schema_and_data'],
['extra', 'schema_only']
])
expect(req.shared_ducklakes).toEqual([])
expect(req.shared_storages).toEqual([])
})
it('sends the prod locks only for a dev workspace', () => {
expect(stagedForkRequest(fork, base).lock_prod_deploy).toBe(false)
const dev = { ...fork, settings: { ...fork.settings, is_dev_workspace: true } }
expect(stagedForkRequest(dev, base).lock_prod_deploy).toBe(true)
})
})
@@ -0,0 +1,105 @@
import type { CreateWorkspaceFork } from '$lib/gen'
import { forkDatatableDbName } from '$lib/utils/forkCreation'
export type DatatableCopy = 'schema_only' | 'schema_and_data'
/** What a staged fork is created with besides its id, name and base. */
export type StagedForkSettings = {
color?: string
/** The data tables the fork copies, by name; every other one is shared with the base. */
datatables?: Record<string, DatatableCopy>
shared_ducklakes?: string[]
shared_storages?: string[]
/** A persistent dev workspace of the base, whose id carries no `wm-fork-` prefix. */
is_dev_workspace?: boolean
dev_workspace_label?: CreateWorkspaceFork['dev_workspace_label']
lock_prod_deploy?: boolean
lock_prod_forking?: boolean
copy_members?: boolean
}
type ForkDefaults = { base?: string; settings: StagedForkSettings }
const KEY_PREFIX = 'wm-session-fork-defaults:'
/** The settings the last fork staged in this workspace family was saved with. Data table,
* lake and storage names are the family's own, so each family keeps its own. */
export function loadForkDefaults(rootId: string | undefined): ForkDefaults | undefined {
if (!rootId) return undefined
try {
const raw = localStorage.getItem(KEY_PREFIX + rootId)
return raw ? (JSON.parse(raw) as ForkDefaults) : undefined
} catch {
return undefined
}
}
export function saveForkDefaults(rootId: string | undefined, defaults: ForkDefaults): void {
if (!rootId) return
try {
localStorage.setItem(KEY_PREFIX + rootId, JSON.stringify(defaults))
} catch {}
}
/** What the base holds when the fork is created, which saved settings may no longer match. */
export type ForkBase = {
/** Each list is undefined when it could not be read: the saved names are sent as they are. */
datatables?: { name: string; database_workspace_id?: string }[]
ducklakes?: string[]
storages?: string[]
/** The base's `RequireIsolatedForks` rule binds this user: nothing may stay shared with it. */
requireIsolation: boolean
}
/** The create-fork request for a staged fork. Saved names the base no longer has are dropped (the
* server refuses to share an unknown lake or storage), and under isolation every base-owned table
* is copied and nothing is shared, as the fork form does. */
export function stagedForkRequest(
fork: { id: string; name: string; settings?: StagedForkSettings },
base: ForkBase
): CreateWorkspaceFork {
const s = fork.settings ?? {}
const tables = base.datatables ?? Object.keys(s.datatables ?? {}).map((name) => ({ name }))
const copies = tables.flatMap((dt: { name: string; database_workspace_id?: string }) => {
const chosen = s.datatables?.[dt.name]
// A table whose database another workspace owns is not the base's data; the rule leaves it.
const behavior =
chosen ?? (base.requireIsolation && !dt.database_workspace_id ? 'schema_only' : undefined)
return behavior
? [
{
name: dt.name,
new_dbname: forkDatatableDbName(fork.id, dt.name),
fork_behavior: behavior
}
]
: []
})
return {
id: fork.id,
name: fork.name,
color: s.color,
forked_datatables: copies,
shared_ducklakes: base.requireIsolation
? []
: (s.shared_ducklakes ?? []).filter((n) => base.ducklakes?.includes(n) ?? true),
shared_storages: base.requireIsolation
? []
: (s.shared_storages ?? []).filter((n) => base.storages?.includes(n) ?? true),
is_dev_workspace: !!s.is_dev_workspace,
dev_workspace_label: s.is_dev_workspace ? s.dev_workspace_label : undefined,
lock_prod_deploy: !!s.is_dev_workspace && !!s.lock_prod_deploy,
lock_prod_forking: !!s.is_dev_workspace && !!s.lock_prod_forking,
copy_members: !!s.copy_members
}
}
/** A fork a session creates at its first send. */
export type StagedFork = {
// Existing workspace to fork from.
parent_workspace_id: string
// Prefixed id the fork will take, e.g. `wm-fork-foo`.
id: string
name: string
settings?: StagedForkSettings
}
@@ -6,6 +6,7 @@ import { useActingUser } from '$lib/actingUser.svelte'
import { useEditRights } from '$lib/operatorWriteRights'
import { buildsAnything } from '$lib/editRights'
import {
canWorkDirectly,
forgetReadOnlyVerdicts,
isReadOnlySessionWorkspace,
settledReadOnlyVerdict
@@ -24,20 +25,35 @@ export function rereadReadOnlyVerdicts(): void {
}
/** Whether a session in `workspace` is read-only because the workspace is protected: the verdict
* `resolveSessionAccess` gives the chat, so the UI and the toolset agree. */
export function useSessionReadOnly(workspace: () => string | undefined) {
const verdict = resource([workspace, () => verdictEpoch], async ([ws], _prev, { signal }) => {
if (!ws) return undefined
const readOnly = await isReadOnlySessionWorkspace(ws)
// A superseded read answers for older rules: runed would still land it over the newer one.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
// Only a successful read settles a verdict; a failed one is read-only to fail closed.
return { workspace: ws, readOnly, rulesRead: settledReadOnlyVerdict(ws) !== undefined }
})
// `resource` keeps the previous workspace's verdict while it asks about the next one.
* `resolveSessionAccess` gives the chat, so the UI and the toolset agree. `direct`: the session
* was opted into working there directly, which lifts it for the rule's bypassers. */
export function useSessionReadOnly(
workspace: () => string | undefined,
direct: () => boolean = () => false
) {
const verdict = resource(
[workspace, direct, () => verdictEpoch],
async ([ws, isDirect], _prev, { signal }) => {
if (!ws) return undefined
const readOnly =
(await isReadOnlySessionWorkspace(ws)) && !(isDirect && (await canWorkDirectly(ws)))
// A superseded read answers for older rules: runed would still land it over the newer one.
if (signal.aborted) throw new DOMException('superseded', 'AbortError')
// Only a successful read settles a verdict; a failed one is read-only to fail closed.
return {
workspace: ws,
direct: isDirect,
readOnly,
rulesRead: settledReadOnlyVerdict(ws) !== undefined
}
}
)
// `resource` keeps the previous workspace's verdict while it asks about the next one. A direct
// session waits for its own verdict rather than take the workspace's.
const verdictFor = (ws: string): boolean | undefined => {
const landed = verdict.current
return landed?.workspace === ws ? landed.readOnly : settledReadOnlyVerdict(ws)
if (landed?.workspace === ws && landed.direct === direct()) return landed.readOnly
return direct() ? undefined : settledReadOnlyVerdict(ws)
}
return {
/** Read-only, and also while the rules have not been read yet: the preview's writes wait
@@ -59,9 +75,9 @@ export function useSessionReadOnly(workspace: () => string | undefined) {
const ws = workspace()
if (!ws) return false
const landed = verdict.current
return landed?.workspace === ws
return landed?.workspace === ws && landed.direct === direct()
? landed.readOnly && landed.rulesRead
: (settledReadOnlyVerdict(ws) ?? false)
: !direct() && (settledReadOnlyVerdict(ws) ?? false)
},
/** Whether the rules were read, a failed read included, which settles as read-only. */
get settled() {
@@ -74,6 +90,7 @@ export function useSessionReadOnly(workspace: () => string | undefined) {
/** The session chat whose work mode the session UI follows. */
type WorkModeHost = {
readonly workMode: AIWorkMode
readonly directIn?: string
readonly moving?: boolean
readonly moveStarted?: boolean
}
@@ -96,8 +113,11 @@ export function useSessionPermissions(
const contextChat = getContext<WorkModeHost | undefined>('aiChatManager')
const rights = useEditRights(workspace)
const user = useActingUser(workspace)
const protectedWorkspace = useSessionReadOnly(workspace)
const host = $derived(chat?.() ?? contextChat)
const protectedWorkspace = useSessionReadOnly(
workspace,
() => !!host?.directIn && host.directIn === workspace()
)
const readOnly = $derived(
protectedWorkspace.current ||
!buildsAnything(rights.capabilities) ||
@@ -394,6 +394,7 @@ function createRuntime(session: Session): SessionRuntime {
manager.sessionId = session.id
manager.workMode = session.workMode ?? AIWorkMode.BUILD
manager.onWorkModeChanged = (mode) => setSessionWorkMode(session.id, mode)
manager.directInResolver = () => sessionState.sessions.find((x) => x.id === session.id)?.direct_in
manager.workingInResolver = () => {
const s = sessionState.sessions.find((x) => x.id === session.id)
// Read from the browser's store, so only a list counts.
@@ -45,8 +45,15 @@ export function syncWorkspaceTo(workspaceId: string | undefined): void {
if (workspaceId === get(workspaceStore)) return
switchWorkspace(workspaceId)
}
import { WorkspaceService } from '$lib/gen'
import { SettingService, WorkspaceService } from '$lib/gen'
import { createWorkspaceForkAndWait, waitForForkCreation } from '$lib/utils/forkCreation'
import { stagedForkRequest, type StagedFork } from './sessionForkDefaults'
import {
canUserBypassRuleKindInRulesets,
isRuleActiveInRulesets,
readProtectionRulesForWorkspace
} from '$lib/workspaceProtectionRules.svelte'
import { getUserExt } from '$lib/user'
import { sendUserToast } from '$lib/toast'
import { onUserChange } from '$lib/userScopedStorage'
@@ -77,13 +84,7 @@ export function isForkSession(
return !!ws.parent_workspace_id
}
export type PendingFork = {
// Existing workspace to fork from (drives routing/scope pre-send).
parent_workspace_id: string
// Slug the new fork will use, e.g. `wm-fork-foo`.
id: string
// Display name shown in the workspace bar.
name: string
export type PendingFork = StagedFork & {
// The background creation this fork started, so a reload mid-copy waits for it rather than
// requesting the fork again, which the server refuses while that creation runs.
creation_id?: string
@@ -106,9 +107,13 @@ export type Session = {
// into workspace_id at first send and then becomes irrelevant.
pending_workspace_id?: string
// Intent to create a new fork at first send (via commitSessionWorkspace), so
// cancelling the draft doesn't leave an orphan fork behind. Found only on records
// older clients wrote: no control stages one.
// cancelling the draft doesn't leave an orphan fork behind. Staged by Home's "Work in
// fork"; `pending_workspace_id` stays the header's workspace it was staged from.
pending_fork?: PendingFork
// The protected workspace its user chose to work in directly rather than in a fork, which
// `resolveSessionAccess` honours for the rule's bypassers only. Keyed by workspace, so it
// lapses when the session acts on another one.
direct_in?: string
// Stable root workspace id used only for sidebar grouping. Lifecycle follows
// workspace_id, not this field. Root sessions store the same id in both fields.
workspace_root_id?: string
@@ -1156,7 +1161,8 @@ function followHomeDraft(): void {
const s = homeDraft.id ? sessionState.sessions.find((x) => x.id === homeDraft.id) : undefined
const ws = get(workspaceStore)
if (!s || !ws || s.workspace_id || sendUnderWay(s.id)) return
if (s.pending_workspace_id === ws && !s.pending_fork) return
// A fork staged from the header's workspace stays; picking another workspace drops it.
if (s.pending_workspace_id === ws) return
if (s.pending_workspace_id && workspaceRootId(ws, get(userWorkspaces)) !== sessionRootId(s)) {
return
}
@@ -1324,6 +1330,24 @@ export function setSessionPendingWorkspace(id: string, workspace_id: string) {
if (changed) persistTouched(s)
}
/** Stage `fork` for a session's first send, or drop the staged one (`undefined`). */
export function setSessionPendingFork(id: string, fork: StagedFork | undefined) {
const s = sessionState.sessions.find((x) => x.id === id)
if (!s || s.workspace_id) return
s.pending_fork = fork && { ...fork }
if (fork) s.direct_in = undefined
persistTouched(s)
}
/** Opt a session into working directly in protected `workspace`, or out (`undefined`). */
export function setSessionDirectIn(id: string, workspace: string | undefined) {
const s = sessionState.sessions.find((x) => x.id === id)
if (!s) return
s.direct_in = workspace
if (workspace) s.pending_fork = undefined
persistTouched(s)
}
// Keep a just-created session in memory until the user starts it (see `untilStarted`).
export function holdSessionUntilStarted(id: string) {
const s = sessionState.sessions.find((x) => x.id === id)
@@ -1563,9 +1587,23 @@ export async function materializeForkOutcome(
)
}
if (!resumed) {
const base = fork.parent_workspace_id
const [datatables, ducklakes, storages, readRules, user] = await Promise.all([
WorkspaceService.listDataTables({ workspace: base }).catch(() => undefined),
WorkspaceService.listDucklakes({ workspace: base }).catch(() => undefined),
SettingService.getSecondaryStorageNames({ workspace: base, includeDefault: true }).catch(
() => undefined
),
readProtectionRulesForWorkspace(base),
getUserExt(base)
])
const rules = readRules ?? []
const requireIsolation =
isRuleActiveInRulesets(rules, 'RequireIsolatedForks') &&
!canUserBypassRuleKindInRulesets(rules, 'RequireIsolatedForks', user)
await createWorkspaceForkAndWait(
fork.parent_workspace_id,
{ id: fork.id, name: fork.name },
base,
stagedForkRequest(fork, { datatables, ducklakes, storages, requireIsolation }),
{ onCreationStarted }
)
}
@@ -50,7 +50,11 @@ vi.mock('$lib/gen', async (orig) => {
...actual.WorkspaceService,
createWorkspaceFork: vi.fn().mockRejectedValue(new Error('fork creation failed')),
getForkCreationStatus: vi.fn().mockResolvedValue({ status: 'completed' }),
listUserWorkspaces: vi.fn().mockResolvedValue([])
listUserWorkspaces: vi.fn().mockResolvedValue([]),
// What a staged fork's request is checked against before it is sent.
listDataTables: vi.fn().mockResolvedValue([]),
listDucklakes: vi.fn().mockResolvedValue([]),
listProtectionRules: vi.fn().mockResolvedValue([])
}
}
})
@@ -6,7 +6,7 @@ import { buildsAnything } from '$lib/editRights'
import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy'
import { setAiClientWorkspace } from '$lib/components/copilot/aiClientWorkspace'
import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl'
import type { WorkModeLock } from '../copilot/chat/workMode'
import type { AIWorkMode, WorkModeLock } from '../copilot/chat/workMode'
import { useSessionReadOnly } from './sessionPermissions.svelte'
import {
getEffectiveWorkspaceId,
@@ -31,12 +31,21 @@ function moveUnsentSession(sessionId: string, id: string, switchesWorkspace: boo
* Home: moving its draft to the dev workspace moves the page too. Reads context and registers
* an effect: call during component initialisation.
*/
export function useWorkModeLock(session: () => Session | undefined, switchesWorkspace = false) {
export function useWorkModeLock(
session: () => Session | undefined,
switchesWorkspace = false,
/** On an unsent draft in a protected workspace, picking a held mode calls this rather than
* being refused: Home asks whether to work in a fork or, for a bypasser, directly. */
onProtectedPick?: () => ((mode: AIWorkMode) => void) | undefined
) {
const workspace = () => {
const s = session()
return s ? getEffectiveWorkspaceId(s) : undefined
}
const protectedWorkspace = useSessionReadOnly(workspace)
const protectedWorkspace = useSessionReadOnly(workspace, () => {
const s = session()
return !!s?.direct_in && s.direct_in === workspace()
})
const rights = useEditRights(workspace)
const workspaces = fromStore(userWorkspaces)
const lock = $derived.by((): WorkModeLock | undefined => {
@@ -48,16 +57,19 @@ export function useWorkModeLock(session: () => Session | undefined, switchesWork
// A role that cannot run is held to reading, as its chat access is (`capabilitiesForRole`).
const readsOnly = !rights.capabilities.run
if (protectedWorkspace.known) {
const onPick = !s.workspace_id && !readsOnly ? onProtectedPick?.() : undefined
const dev = findCanonicalDevWorkspace(ws, workspaces.current)
if (!dev)
return {
reason: 'This workspace is protected against direct changes. Build in a fork.',
readsOnly
readsOnly,
onPick
}
const label = `${dev.name} (dev)`
return {
reason: `This workspace is protected against direct changes. Build in ${label}.`,
readsOnly,
onPick,
// Until its first message a session can still change workspace; after it, only a new
// one can act elsewhere: Home's composer, on the dev workspace.
escape: s.workspace_id
@@ -83,6 +83,8 @@
import ForkDucklakeSection from './ForkDucklakeSection.svelte'
import ForkStorageSection from './ForkStorageSection.svelte'
import { createWorkspaceForkAndWait } from '$lib/utils/forkCreation'
import type { StagedFork } from '$lib/components/sessions/sessionForkDefaults'
import { untrack } from 'svelte'
interface Props {
isFork?: boolean
@@ -91,19 +93,32 @@
// "Back to workspaces" navigation.
inModal?: boolean
onFinish?: () => void
/** A fork a session creates at its first send: the form opens on `fork` and its button
* hands the choices to `onStage` instead of creating the fork. */
stage?: { fork: StagedFork; onStage: (fork: StagedFork) => void }
}
let { isFork = false, inModal = false, onFinish }: Props = $props()
let { isFork = false, inModal = false, onFinish, stage }: Props = $props()
const stagedAtOpen = untrack(() => stage?.fork)
const staged = stagedAtOpen?.settings
// Dev-workspace mode: create the fork as a persistent, prefix-less dev workspace and (optionally)
// lock the parent ("prod") against direct edits.
let createAsDevWorkspace = $state(false)
let lockProdDeploy = $state(true)
let lockProdForking = $state(true)
let lockProdDeploy = $state(staged?.lock_prod_deploy ?? true)
let lockProdForking = $state(staged?.lock_prod_forking ?? true)
// Bring the parent's members into the fork (a shared env). Defaults on for a
// dev workspace, off for a throwaway fork; flipping the dev toggle resets it.
// dev workspace, off for a throwaway fork; flipping the dev toggle resets it, except for
// the flip that restores a staged dev workspace, which keeps what was staged.
let copyMembers = $state(false)
let restoringStagedDev = !!staged?.is_dev_workspace
$effect(() => {
if (createAsDevWorkspace && restoringStagedDev) {
restoringStagedDev = false
copyMembers = staged?.copy_members ?? true
devWorkspaceLabel = (staged?.dev_workspace_label as DevWorkspaceLabelKey) ?? 'dev'
return
}
copyMembers = createAsDevWorkspace
})
@@ -117,8 +132,11 @@
})
// "Create a new dev workspace" links here with ?dev=true, so the button creates what it names.
// Applied once eligibility is confirmed rather than at init, since the effect above would clear a
// toggle set while the server check is still in flight.
let devRequestedFromUrl = $state(page.url.searchParams.get('dev') === 'true')
// toggle set while the server check is still in flight. A staged dev workspace is restored the
// same way.
let devRequestedFromUrl = $state(
page.url.searchParams.get('dev') === 'true' || !!staged?.is_dev_workspace
)
$effect(() => {
if (devRequestedFromUrl && canDesignateDevWorkspace) {
devRequestedFromUrl = false
@@ -128,7 +146,7 @@
// The base workspace to fork from. A fork's git branch is based on its parent's branch, so picking
// a fork here (rather than the root) yields a fork of a fork.
let baseWorkspaceId = $state<string | undefined>(undefined)
let baseWorkspaceId = $state<string | undefined>(stagedAtOpen?.parent_workspace_id)
// Base list for forking, folding in a superadmin-visited workspace (see useForkableWorkspaces).
const forkable = useForkableWorkspaces({
@@ -216,8 +234,12 @@
// Offer dev designation only once the server confirms there's no dev yet (returns null); stay
// conservative (no offer) while the check is loading (current is undefined). With every label
// taken the chain is full and there is nothing left to designate.
// A session's staged fork never adds a level to a dev chain: from Home, a dev base gets a fork.
let canDesignateDevWorkspace = $derived(
baseCanHostDev && availableDevLabels.length > 0 && devWorkspaceResource.current === null
baseCanHostDev &&
!(stage && baseWorkspaceEntry?.is_dev_workspace) &&
availableDevLabels.length > 0 &&
devWorkspaceResource.current === null
)
let devWorkspaceLabel = $state<DevWorkspaceLabelKey>('dev')
@@ -270,7 +292,7 @@
let effectiveLockProdDeploy = $derived(deployLocked || lockProdDeploy)
let effectiveLockProdForking = $derived(forkingLocked || lockProdForking)
let id = $state('')
let id = $state(stagedAtOpen?.id.replace(/^wm-fork-/, '') ?? '')
let name = $state('')
let username = $state('')
@@ -346,8 +368,8 @@
(forkingRulesets.length > 0 && !(canBypassForkingRule && forkingBypassConfirmed)))
)
let workspaceColor: string | undefined = $state(undefined)
let colorEnabled = $state(false)
let workspaceColor: string | undefined = $state(stagedAtOpen?.settings?.color)
let colorEnabled = $state(!!stagedAtOpen?.settings?.color)
let errorHandlerFallbackToInstanceAlerts = $state(false)
function generateRandomColor() {
@@ -463,7 +485,7 @@
async function forkWorkspace(prefixed_id: string): Promise<void> {
if (baseWorkspaceId) {
forkCreationLoading = true
forkCreationStep = 'Creating branch'
forkCreationStep = stage ? 'Saving' : 'Creating branch'
errorMsgs = []
failedSyncJobs = []
forkCreationError = ''
@@ -477,12 +499,40 @@
}
}
await completeFork(prefixed_id)
await afterCloneConfirmations(prefixed_id)
} else {
sendUserToast('No workspace selected, cannot fork non-existent workspace', true)
}
}
async function afterCloneConfirmations(prefixed_id: string): Promise<void> {
if (stage && baseWorkspaceId) {
forkCreationLoading = false
stage.onStage({
parent_workspace_id: baseWorkspaceId,
id: prefixed_id,
name,
settings: {
color: colorEnabled && workspaceColor ? workspaceColor : undefined,
datatables: Object.fromEntries(
(forkDatatableSection?.getConfirmedCloneJobs() ?? []).map((j) => [j.name, j.behavior])
),
shared_ducklakes: forkDucklakeSection?.getSharedDucklakes() ?? [],
shared_storages: forkStorageSection?.getSharedStorages() ?? [],
is_dev_workspace: createAsDevWorkspace,
dev_workspace_label: createAsDevWorkspace ? devWorkspaceLabel : undefined,
// Left unset on a plain fork, so a later dev workspace starts with prod locked.
lock_prod_deploy: createAsDevWorkspace ? effectiveLockProdDeploy : undefined,
lock_prod_forking: createAsDevWorkspace ? effectiveLockProdForking : undefined,
copy_members: copyMembers
}
})
onFinish?.()
} else {
await completeFork(prefixed_id)
}
}
async function completeFork(prefixed_id: string): Promise<void> {
// The fork request makes these copies, and drops them if the fork is not created
const forkedDatatables = forkDatatableSection
@@ -732,19 +782,30 @@
id = name.toLowerCase().replace(/\s/gi, '-')
}
})
// When creating a dev workspace, prefill the fork name with `<root>-<badge>` (the effect above
// slugifies it into the id). Only fill an empty field or one still holding a prior suggestion, so a
// user-typed name is never overwritten; changing the label updates the suffix, and turning the dev
// toggle back off clears the suggestion.
let lastAutoDevName = $state<string | undefined>(undefined)
// When creating a dev workspace, prefill the id with `<base>-<badge>` (a fork's name is its id).
// Only replace an empty id, a prior suggestion, or the name Home generated for a staged fork, so a
// user-typed id is never overwritten; changing the label updates the suffix, and turning the dev
// toggle back off restores what was there.
const generatedId = untrack(() => (stagedAtOpen && !staged?.is_dev_workspace ? id : ''))
// A staged dev workspace Home named `<base>-<badge>` is still that suggestion.
let lastAutoId = $state(
untrack(() =>
stagedAtOpen &&
staged?.is_dev_workspace &&
id === `${stagedAtOpen.parent_workspace_id}-${devBadgeText(staged.dev_workspace_label)}`
? id
: generatedId
)
)
$effect(() => {
// A requested dev toggle is not on yet: the id would be cleared before it is restored.
if (devRequestedFromUrl) return
const base = baseWorkspaceId ?? $workspaceStore
const target =
createAsDevWorkspace && $workspaceStore
? `${$workspaceStore}-${devBadgeText(devWorkspaceLabel)}`
: ''
if (name === '' || name === lastAutoDevName) {
name = target
lastAutoDevName = target === '' ? undefined : target
createAsDevWorkspace && base ? `${base}-${devBadgeText(devWorkspaceLabel)}` : generatedId
if (id === lastAutoId || (id === '' && createAsDevWorkspace)) {
id = target
lastAutoId = target
}
})
run(() => {
@@ -1131,8 +1192,9 @@
bind:itemCount={datatableCount}
sourceWorkspace={baseWorkspaceId}
{requireIsolation}
initialBehaviors={stagedAtOpen?.settings?.datatables}
onAllDone={() => {
completeFork(effectiveForkId)
void afterCloneConfirmations(effectiveForkId)
}}
onCanceled={() => {
forkCreationLoading = false
@@ -1143,12 +1205,14 @@
bind:itemCount={ducklakeCount}
sourceWorkspace={baseWorkspaceId}
{requireIsolation}
initialShared={stagedAtOpen?.settings?.shared_ducklakes}
/>
<ForkStorageSection
bind:this={forkStorageSection}
bind:itemCount={storageCount}
sourceWorkspace={baseWorkspaceId}
{requireIsolation}
initialShared={stagedAtOpen?.settings?.shared_storages}
/>
</div>
{/if}
@@ -1275,8 +1339,14 @@
{/if}
</div>
</div>
<div class="flex flex-wrap flex-row {inModal ? 'justify-end' : 'justify-between'} gap-4 pt-4">
{#if !inModal}
<div
class="flex flex-wrap flex-row items-center {inModal && !stage
? 'justify-end'
: 'justify-between'} gap-4 pt-4"
>
{#if stage}
<span class="text-xs text-hint">Fork is created when the first message is sent</span>
{:else if !inModal}
<Button disabled={forkCreationLoading} variant="default" size="sm" href="/user/workspaces"
>&leftarrow; Back to workspaces</Button
>
@@ -1292,7 +1362,9 @@
!id}
on:click={createOrForkWorkspace}
>
{#if isFork}
{#if stage}
Save
{:else if isFork}
Fork workspace
{:else}
Create workspace
@@ -16,6 +16,8 @@
import { TriangleAlert } from 'lucide-svelte'
import Alert from '../common/alert/Alert.svelte'
import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte'
import { forkDatatableDbName } from '$lib/utils/forkCreation'
import { untrack } from 'svelte'
interface Props {
// Workspace whose datatables are cloned into the fork (the fork's base). Falls back to the
@@ -24,6 +26,8 @@
// A protection rule on the base forbids `keep_original` for the base's own datatables.
requireIsolation?: boolean
itemCount?: number
// The copies a staged fork was saved with, read once.
initialBehaviors?: Record<string, 'schema_only' | 'schema_and_data'>
onAllDone?: () => void
onCanceled?: () => void
}
@@ -32,6 +36,7 @@
sourceWorkspace,
requireIsolation = false,
itemCount = $bindable(),
initialBehaviors,
onAllDone,
onCanceled
}: Props = $props()
@@ -48,7 +53,9 @@
})
type Behavior = 'schema_only' | 'schema_and_data' | 'keep_original'
let datatableBehaviors: Record<string, Behavior> = $state({})
let datatableBehaviors: Record<string, Behavior> = $state(
untrack(() => ({ ...initialBehaviors }))
)
// An entry whose database another workspace owns is not the base's data: the rule leaves it
// alone, as the server does.
@@ -82,8 +89,7 @@
name: dt.name,
resourceType: dt.resource_type,
behavior: behaviorOf(dt) as 'schema_only' | 'schema_and_data',
// A dev workspace's id has no `wm-fork-` prefix; its copies are named like a fork's
_newDbName: `wm_fork_${targetWorkspaceId.replace(/^wm-fork-/, '').replace(/-/g, '_')}__${dt.name}`
_newDbName: forkDatatableDbName(targetWorkspaceId, dt.name)
}))
}
@@ -2,6 +2,7 @@
import { WorkspaceService } from '$lib/gen'
import { workspaceStore } from '$lib/stores'
import { resource } from 'runed'
import { untrack } from 'svelte'
import Select from '../select/Select.svelte'
import { TriangleAlert } from 'lucide-svelte'
@@ -11,8 +12,15 @@
let {
sourceWorkspace,
requireIsolation = false,
itemCount = $bindable()
}: { sourceWorkspace?: string; requireIsolation?: boolean; itemCount?: number } = $props()
itemCount = $bindable(),
initialShared
}: {
sourceWorkspace?: string
requireIsolation?: boolean
itemCount?: number
// The names a staged fork was saved sharing, read once.
initialShared?: string[]
} = $props()
let effectiveSource = $derived(sourceWorkspace ?? $workspaceStore ?? undefined)
// Keyed on the source so a direct page load (store hydrates after mount) still fetches.
@@ -25,7 +33,9 @@
itemCount = allDucklakes.current?.length ?? 0
})
let lakeBehaviors: Record<string, 'isolated' | 'shared'> = $state({})
let lakeBehaviors: Record<string, 'isolated' | 'shared'> = $state(
untrack(() => Object.fromEntries((initialShared ?? []).map((n) => [n, 'shared' as const])))
)
// Lakes the user explicitly opted out of isolation for — sent as
// `shared_ducklakes` on the create-fork request. Unlisted lakes default to the
@@ -2,6 +2,7 @@
import { SettingService } from '$lib/gen'
import { workspaceStore } from '$lib/stores'
import { resource } from 'runed'
import { untrack } from 'svelte'
import Select from '../select/Select.svelte'
import { TriangleAlert } from 'lucide-svelte'
@@ -10,8 +11,15 @@
let {
sourceWorkspace,
requireIsolation = false,
itemCount = $bindable()
}: { sourceWorkspace?: string; requireIsolation?: boolean; itemCount?: number } = $props()
itemCount = $bindable(),
initialShared
}: {
sourceWorkspace?: string
requireIsolation?: boolean
itemCount?: number
// The names a staged fork was saved sharing, read once.
initialShared?: string[]
} = $props()
let effectiveSource = $derived(sourceWorkspace ?? $workspaceStore ?? undefined)
let storages = resource(
@@ -26,7 +34,9 @@
itemCount = storages.current?.length ?? 0
})
let behaviors: Record<string, 'isolated' | 'shared'> = $state({})
let behaviors: Record<string, 'isolated' | 'shared'> = $state(
untrack(() => Object.fromEntries((initialShared ?? []).map((n) => [n, 'shared' as const])))
)
// Sent as `shared_storages` on the create-fork request; unlisted storages are isolated.
export function getSharedStorages(): string[] {
+6
View File
@@ -4,6 +4,12 @@ const POLL_INTERVAL_MS = 1500
// How long polls may keep failing, which a rolling deploy's replicas without the status route cause.
const MAX_FAILING_POLLS_MS = 3 * 60 * 1000
/** The database a fork's copy of data table `name` is created as. A dev workspace's id has no
* `wm-fork-` prefix; its copies are named like a fork's. */
export function forkDatatableDbName(forkId: string, name: string): string {
return `wm_fork_${forkId.replace(/^wm-fork-/, '').replace(/-/g, '_')}__${name}`
}
/**
* Create a fork and resolve once it exists, rejecting with the reason it could not be created.
*