Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): hold the docked-or-floating invariant across reload, presets, and routing

Lincoln Steinb0348d311afd
diff --git a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
index e3cdf64e09..0379fc3693 100644
--- a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
@@ -10,6 +10,8 @@ import {
FLOATING_MIN_WIDTH_PX,
nextStackOrder,
} from './floatingWindows';
+import { doesProjectMatchLayoutPreset, resolveSavedLayoutPreset } from './layoutPresetSnapshots';
+import { normalizeWorkbenchProject } from './workbenchState';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
const getActiveProject = (state: WorkbenchState): Project => {
@@ -25,6 +27,11 @@ const getActiveProject = (state: WorkbenchState): Project => {
const floatGallery = (state = createInitialWorkbenchState()): WorkbenchState =>
workbenchReducer(state, { instanceId: 'gallery', type: 'floatWidget' });
+const getRegionsHolding = (project: Project, instanceId: string): string[] =>
+ Object.entries(project.widgetRegions)
+ .filter(([, region]) => region.instanceIds.includes(instanceId))
+ .map(([regionId]) => regionId);
+
describe('floatWidget', () => {
it('detaches the instance from its region and repairs the active instance', () => {
const initial = createInitialWorkbenchState();
@@ -56,6 +63,35 @@ describe('floatWidget', () => {
expect(floating?.queue.stackOrder).toBe(2);
expect(floating?.queue.x).toBeGreaterThan(floating?.gallery.x ?? 0);
});
+
+ it('refuses to float the last center view, which would blank the work surface', () => {
+ let state = createInitialWorkbenchState();
+ const centerInstanceIds = getActiveProject(state).widgetRegions.center.instanceIds;
+
+ for (const instanceId of centerInstanceIds.slice(1)) {
+ state = workbenchReducer(state, { region: 'center', type: 'toggleRegionWidget', widgetId: instanceId });
+ }
+
+ const lastCenterInstanceId = centerInstanceIds[0];
+ expect(getActiveProject(state).widgetRegions.center.instanceIds).toEqual([lastCenterInstanceId]);
+ expect(workbenchReducer(state, { instanceId: lastCenterInstanceId, type: 'floatWidget' })).toBe(state);
+ });
+
+ it('collapses a rail it empties instead of leaving it open and blank', () => {
+ let state = createInitialWorkbenchState();
+ const rightInstanceIds = getActiveProject(state).widgetRegions.right.instanceIds;
+
+ for (const instanceId of rightInstanceIds.slice(1)) {
+ state = workbenchReducer(state, { region: 'right', type: 'toggleRegionWidget', widgetId: instanceId });
+ }
+
+ state = workbenchReducer(state, { region: 'right', type: 'setRegionWidgetCollapsed', isCollapsed: false });
+ state = workbenchReducer(state, { instanceId: rightInstanceIds[0], type: 'floatWidget' });
+ const right = getActiveProject(state).widgetRegions.right;
+
+ expect(right.instanceIds).toEqual([]);
+ expect(right.isCollapsed).toBe(true);
+ });
});
describe('dockFloatingWidget', () => {
@@ -101,6 +137,23 @@ describe('geometry, mode, and stacking actions', () => {
expect(floating).toMatchObject({ heightPx: FLOATING_MIN_HEIGHT_PX, widthPx: FLOATING_MIN_WIDTH_PX, x: 5, y: 7 });
});
+ it('ignores a commit that lands on the geometry already stored', () => {
+ const state = floatGallery();
+ const floating = getActiveProject(state).floatingWidgets?.gallery;
+
+ // What a pointer-down/up with no movement sends: the starting geometry.
+ expect(
+ workbenchReducer(state, {
+ heightPx: floating?.heightPx ?? 0,
+ instanceId: 'gallery',
+ type: 'setFloatingWidgetGeometry',
+ widthPx: floating?.widthPx ?? 0,
+ x: floating?.x ?? 0,
+ y: floating?.y ?? 0,
+ })
+ ).toBe(state);
+ });
+
it('switches modes and ignores repeats', () => {
const state = workbenchReducer(floatGallery(), {
instanceId: 'gallery',
@@ -176,6 +229,87 @@ describe('pure helpers', () => {
});
});
+describe('normalization of persisted floating windows', () => {
+ it('keeps a floated widget floating across a reload instead of re-docking it', () => {
+ // The right rail migration re-adds `image-map` to any rail that reads as a
+ // pre-image-map default — which is exactly the shape floating it leaves.
+ const state = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'image-map', type: 'floatWidget' });
+ const project = normalizeWorkbenchProject(getActiveProject(state));
+
+ expect(project.floatingWidgets?.['image-map']).toBeDefined();
+ expect(getRegionsHolding(project, 'image-map')).toEqual([]);
+ });
+
+ it('survives a second normalization pass unchanged', () => {
+ const state = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'image-map', type: 'floatWidget' });
+ const once = normalizeWorkbenchProject(getActiveProject(state));
+ const twice = normalizeWorkbenchProject(once);
+
+ expect(twice.floatingWidgets).toEqual(once.floatingWidgets);
+ expect(twice.widgetRegions).toEqual(once.widgetRegions);
+ });
+
+ it('drops entries a hand-edited or foreign project file could carry', () => {
+ const project = getActiveProject(floatGallery());
+ const normalized = normalizeWorkbenchProject({
+ ...project,
+ floatingWidgets: {
+ // Would crash `dockFloatingWidget` on `widgetRegions[returnRegion]`.
+ 'image-map': { ...project.floatingWidgets!.gallery, returnRegion: 'nowhere' },
+ // Would reach the window's fixed-position CSS as `NaNpx`.
+ preview: { ...project.floatingWidgets!.gallery, x: Number.NaN },
+ // No such instance to render.
+ 'no-such-widget': { ...project.floatingWidgets!.gallery },
+ queue: { ...project.floatingWidgets!.gallery, mode: 'iconified' },
+ } as unknown as Project['floatingWidgets'],
+ });
+
+ expect(normalized.floatingWidgets).toBeUndefined();
+ for (const instanceId of ['image-map', 'preview', 'queue']) {
+ expect(getRegionsHolding(normalized, instanceId)).toContain('right');
+ }
+ });
+
+ it('clamps persisted geometry below the minimum size', () => {
+ const project = getActiveProject(floatGallery());
+ const normalized = normalizeWorkbenchProject({
+ ...project,
+ floatingWidgets: { gallery: { ...project.floatingWidgets!.gallery, heightPx: 1, widthPx: 1 } },
+ });
+
+ expect(normalized.floatingWidgets?.gallery).toMatchObject({
+ heightPx: FLOATING_MIN_HEIGHT_PX,
+ widthPx: FLOATING_MIN_WIDTH_PX,
+ });
+ });
+
+ it('docks rather than empties the center region', () => {
+ const project = getActiveProject(createInitialWorkbenchState());
+ const [onlyCenterInstanceId] = project.widgetRegions.center.instanceIds;
+ const normalized = normalizeWorkbenchProject({
+ ...project,
+ floatingWidgets: {
+ [onlyCenterInstanceId]: {
+ heightPx: 300,
+ mode: 'windowed',
+ returnRegion: 'center',
+ stackOrder: 1,
+ widthPx: 400,
+ x: 10,
+ y: 10,
+ },
+ },
+ widgetRegions: {
+ ...project.widgetRegions,
+ center: { ...project.widgetRegions.center, instanceIds: [onlyCenterInstanceId] },
+ },
+ });
+
+ expect(normalized.floatingWidgets).toBeUndefined();
+ expect(normalized.widgetRegions.center.instanceIds).toEqual([onlyCenterInstanceId]);
+ });
+});
+
describe('interaction with presets and undo', () => {
it('applying a preset docks all floating widgets (no double render)', () => {
const floated = floatGallery();
@@ -186,6 +320,39 @@ describe('interaction with presets and undo', () => {
expect(project.widgetRegions.right.instanceIds).toContain('gallery');
});
+ it('a preset saved while a widget floats restores the window, not nothing', () => {
+ // The rail is customized first so the reload migration is not what keeps
+ // the widget alive here — only the preset can.
+ let state = workbenchReducer(createInitialWorkbenchState(), {
+ region: 'right',
+ type: 'toggleRegionWidget',
+ widgetId: 'project',
+ });
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'floatWidget' });
+ state = workbenchReducer(state, { presetId: 'compose', type: 'saveLayoutPreset' });
+ // Dock it, then revert to the preset that was saved with it floating.
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'dockFloatingWidget' });
+ state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });
+ const project = getActiveProject(state);
+
+ expect(project.floatingWidgets?.gallery).toBeDefined();
+ expect(getRegionsHolding(project, 'gallery')).toEqual([]);
+ });
+
+ it('reads a floated window as unsaved layout drift until it is saved', () => {
+ const floated = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'gallery', type: 'floatWidget' });
+
+ expect(
+ doesProjectMatchLayoutPreset(getActiveProject(floated), resolveSavedLayoutPreset(floated.account, 'compose'))
+ ).toBe(false);
+
+ const saved = workbenchReducer(floated, { presetId: 'compose', type: 'saveLayoutPreset' });
+
+ expect(
+ doesProjectMatchLayoutPreset(getActiveProject(saved), resolveSavedLayoutPreset(saved.account, 'compose'))
+ ).toBe(true);
+ });
+
it('undo restores floating state together with the regions', () => {
// Snapshot A: gallery docked. The undoable action (apply preset) captures it.
let state = createInitialWorkbenchState();
diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts
index 88df00e023..0a51e71c2d 100644
--- a/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.test.ts
@@ -52,6 +52,18 @@ describe('graph widget sources', () => {
);
});
+ it('counts a floated widget as both visible and placed', () => {
+ // A widget in a window is on screen; reading only the rails would drop the
+ // first graph-bearing widget that floats out of the invoke-source list.
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ state = workbenchReducer(state, { instanceId: 'upscale', type: 'floatWidget' });
+ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;
+
+ expect(project.floatingWidgets?.upscale).toBeDefined();
+ expect(getVisibleWidgetTypeIds(project).has('upscale')).toBe(true);
+ expect(getPlacedWidgetTypeIds(project).has('upscale')).toBe(true);
+ });
+
it('maps each source to its natural output target', () => {
expect(getNaturalDestination('canvas')).toBe('canvas');
expect(getNaturalDestination('generate')).toBe('gallery');
diff --git a/invokeai/frontend/webv2/src/workbench/graphWidgets.ts b/invokeai/frontend/webv2/src/workbench/graphWidgets.ts
index 50e1b52ea2..417110668c 100644
--- a/invokeai/frontend/webv2/src/workbench/graphWidgets.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphWidgets.ts
@@ -49,6 +49,22 @@ export const graphWidgetSources: GraphWidgetSource[] = graphWidgetTypeIds
}))
.filter((source) => isInvocationSourceAvailable(source.sourceId));
+/**
+ * Floated instances belong in both sets below: a widget in a window is on
+ * screen and placed, just not in a rail. Reading only `widgetRegions` would
+ * drop the first graph-bearing widget that opts into floating out of the
+ * invoke-source list while it sits in plain view.
+ */
+const addFloatingWidgetTypeIds = (project: Project, typeIds: Set<WidgetTypeId>): void => {
+ for (const instanceId of Object.keys(project.floatingWidgets ?? {})) {
+ const typeId = project.widgetInstances[instanceId]?.typeId;
+
+ if (typeId) {
+ typeIds.add(typeId);
+ }
+ }
+};
+
// Collapsed regions still count as visible because disclosure does not change routing.
export const getVisibleWidgetTypeIds = (project: Project): Set<WidgetTypeId> => {
const typeIds = new Set<WidgetTypeId>();
@@ -61,6 +77,9 @@ export const getVisibleWidgetTypeIds = (project: Project): Set<WidgetTypeId> =>
}
}
+ // Shaded and maximized windows count too, for the same reason.
+ addFloatingWidgetTypeIds(project, typeIds);
+
return typeIds;
};
@@ -77,6 +96,8 @@ export const getPlacedWidgetTypeIds = (project: Project): Set<WidgetTypeId> => {
}
}
+ addFloatingWidgetTypeIds(project, typeIds);
+
return typeIds;
};
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index dd3d77f6a9..48550bb45e 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -184,6 +184,17 @@ describe('resolveInvocationRoute — upscale source', () => {
return getInvocationRouteInput(project);
};
+ it('still counts the widget as mounted once it is floated out of its rail', () => {
+ let state = createInitialWorkbenchState();
+
+ state = workbenchReducer(state, { instanceId: 'upscale', type: 'floatWidget' });
+
+ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;
+
+ expect(project.floatingWidgets?.upscale).toBeDefined();
+ expect(getInvocationRouteInput(project).mountedWidgetIds).toContain('upscale');
+ });
+
it('is ready only with a mounted widget and installed compatible required models', () => {
expect(resolveInvocationRouteInput(createInput(), 'global', route, upscaleModels)).toMatchObject({
sourceValid: true,
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index c5d4c8ae64..a3804eed0d 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -112,6 +112,15 @@ const getMountedWidgetIds = (project: Project): WidgetId[] => {
}
}
+ // A floated instance is mounted in its window, not in a region.
+ for (const instanceId of Object.keys(project.floatingWidgets ?? {})) {
+ const widgetId = project.widgetInstances[instanceId]?.typeId;
+
+ if (widgetId) {
+ mountedWidgetIds.add(widgetId);
+ }
+ }
+
return Array.from(mountedWidgetIds).sort();
};
diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
index ca468d56ae..0c72b466fc 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
@@ -59,6 +59,12 @@ export interface LayoutPresetSnapshot {
layout: ProjectLayoutState;
widgetInstances: Record<WidgetInstanceId, LayoutPresetWidgetInstanceSnapshot>;
widgetRegions: Record<WidgetRegion, WidgetRegionState>;
+ /**
+ * Captured with widgetRegions: a floated instance is in no region, so a
+ * preset that recorded only the regions would drop it on the floor. Absent
+ * on presets saved before floating existed, which have no floating windows.
+ */
+ floatingWidgets?: Record<WidgetInstanceId, FloatingWidgetState>;
}
/**
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
index 8334ffa8d6..763ed24f11 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
@@ -1,4 +1,5 @@
import type {
+ FloatingWidgetState,
LayoutPreset,
LayoutPresetId,
LayoutPresetSnapshot,
@@ -58,6 +59,11 @@ export const resolveSavedLayoutPreset = (account: AccountState, presetId: Layout
: builtInPreset;
};
+export const cloneFloatingWidgets = (
+ floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState>
+): Record<WidgetInstanceId, FloatingWidgetState> =>
+ Object.fromEntries(Object.entries(floatingWidgets).map(([instanceId, state]) => [instanceId, { ...state }]));
+
export const cloneLayoutPresetWidgetRegions = (
widgetRegionState: Record<WidgetRegion, WidgetRegionState>
): Record<WidgetRegion, WidgetRegionState> => ({
@@ -78,6 +84,12 @@ export const createLayoutPresetSnapshot = (project: Project): LayoutPresetSnapsh
}
}
+ // A floated instance sits in no region, so it has to be named here too or
+ // applying the preset would recreate neither the window nor a docked copy.
+ for (const instanceId of Object.keys(project.floatingWidgets ?? {})) {
+ referencedInstanceIds.add(instanceId);
+ }
+
const widgetInstances: Record<WidgetInstanceId, LayoutPresetWidgetInstanceSnapshot> = {};
for (const instanceId of referencedInstanceIds) {
@@ -89,6 +101,7 @@ export const createLayoutPresetSnapshot = (project: Project): LayoutPresetSnapsh
}
return {
+ ...(project.floatingWidgets ? { floatingWidgets: cloneFloatingWidgets(project.floatingWidgets) } : {}),
layout: { ...project.layout, panels: { ...project.layout.panels } },
widgetInstances,
widgetRegions: cloneLayoutPresetWidgetRegions(project.widgetRegions),
@@ -117,12 +130,45 @@ const areWidgetInstanceSnapshotsEqual = (
);
};
+/**
+ * Window geometry counts as drift for the same reason panel `sizePx` does: it
+ * is part of what `Save changes` would store, so the strip's dot has to offer
+ * to store it. `stackOrder` is excluded — it is a monotonically rising counter
+ * bumped by every click on a window, so comparing it would leave the dot lit
+ * for good the first time someone focuses one.
+ */
+const areFloatingWidgetsEqual = (
+ left: LayoutPresetSnapshot['floatingWidgets'],
+ right: LayoutPresetSnapshot['floatingWidgets']
+): boolean => {
+ const leftKeys = Object.keys(left ?? {}).sort();
+ const rightKeys = Object.keys(right ?? {}).sort();
+
+ return (
+ areArraysEqual(leftKeys, rightKeys) &&
+ leftKeys.every((key) => {
+ const leftState = left?.[key];
+ const rightState = right?.[key];
+
+ return (
+ leftState?.x === rightState?.x &&
+ leftState?.y === rightState?.y &&
+ leftState?.widthPx === rightState?.widthPx &&
+ leftState?.heightPx === rightState?.heightPx &&
+ leftState?.mode === rightState?.mode &&
+ leftState?.returnRegion === rightState?.returnRegion
+ );
+ })
+ );
+};
+
export const areLayoutPresetSnapshotsEqual = (left: LayoutPresetSnapshot, right: LayoutPresetSnapshot): boolean =>
left.layout.centerViewId === right.layout.centerViewId &&
left.layout.panels.isBottomOpen === right.layout.panels.isBottomOpen &&
left.layout.panels.isLeftOpen === right.layout.panels.isLeftOpen &&
left.layout.panels.isRightOpen === right.layout.panels.isRightOpen &&
widgetRegions.every((region) => areWidgetRegionsEqual(left.widgetRegions[region], right.widgetRegions[region])) &&
+ areFloatingWidgetsEqual(left.floatingWidgets, right.floatingWidgets) &&
areWidgetInstanceSnapshotsEqual(left.widgetInstances, right.widgetInstances);
export const doesProjectMatchLayoutPreset = (project: Project, preset: LayoutPreset): boolean =>
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
index 6e78028135..9b082d1b7b 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
@@ -118,6 +118,7 @@ export const WidgetActionsMenu = ({
(project) => ({ projectGraph: project.projectGraph, widgetGraphs: project.widgetGraphs }),
shallowEqual
) as Project;
+ const centerInstanceCount = useActiveProjectSelector((project) => project.widgetRegions.center.instanceIds.length);
const { widgets } = useWorkbenchCommands();
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const [previewGraph, setPreviewGraph] = useState<GraphContract | null>(null);
@@ -128,8 +129,11 @@ export const WidgetActionsMenu = ({
[label, manifest, region]
);
// Floating is offered only from dockable regions; the floating window's own
- // chrome carries the dock control.
- const canFloat = Boolean(manifest.allowFloating) && region !== 'floating';
+ // chrome carries the dock control. The last center view is not offered it
+ // either — the reducer refuses to empty the work surface, so the item would
+ // do nothing.
+ const canFloat =
+ Boolean(manifest.allowFloating) && region !== 'floating' && !(region === 'center' && centerInstanceCount === 1);
const handleFloat = useCallback(() => widgets.float(instance.id), [instance.id, widgets]);
const surfaceSourceId = surface?.sourceId;
const handlePreview = useCallback(async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 7933b456fa..1eb1a3cadb 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -147,6 +147,7 @@ import {
resolveLayoutPresetId,
} from './layoutPresets';
import {
+ cloneFloatingWidgets,
cloneLayoutPresetWidgetRegions,
createLayoutPresetSnapshot,
resolveSavedLayoutPreset,
@@ -1306,6 +1307,120 @@ const ensureCenterRegion = (
};
};
+const WIDGET_REGION_IDS: WidgetRegion[] = ['left', 'right', 'bottom', 'center'];
+const FLOATING_WIDGET_MODES: FloatingWidgetMode[] = ['windowed', 'maximized', 'shaded'];
+
+const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
+
+const isFloatingWidgetMode = (value: unknown): value is FloatingWidgetMode =>
+ FLOATING_WIDGET_MODES.includes(value as FloatingWidgetMode);
+
+const isWidgetRegionId = (value: unknown): value is WidgetRegion => WIDGET_REGION_IDS.includes(value as WidgetRegion);
+
+/**
+ * Persisted floating windows are an unsafe-cast boundary like every other
+ * sub-shape here. An entry naming a region that does not exist crashes the
+ * reducer the moment it is docked, and a non-numeric geometry reaches the
+ * window's fixed-position CSS, so anything malformed is dropped rather than
+ * carried: the widget then reappears docked instead of not at all.
+ */
+const normalizeFloatingWidgets = (
+ value: unknown,
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
+): Record<WidgetInstanceId, FloatingWidgetState> | undefined => {
+ if (!value || typeof value !== 'object') {
+ return undefined;
+ }
+
+ const floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> = {};
+
+ for (const [instanceId, entry] of Object.entries(value as Record<string, unknown>)) {
+ if (!entry || typeof entry !== 'object' || !widgetInstances[instanceId]) {
+ continue;
+ }
+
+ const state = entry as Partial<FloatingWidgetState>;
+
+ if (
+ !isFiniteNumber(state.x) ||
+ !isFiniteNumber(state.y) ||
+ !isFiniteNumber(state.widthPx) ||
+ !isFiniteNumber(state.heightPx) ||
+ !isFiniteNumber(state.stackOrder) ||
+ !isFloatingWidgetMode(state.mode) ||
+ !isWidgetRegionId(state.returnRegion)
+ ) {
+ continue;
+ }
+
+ floatingWidgets[instanceId] = {
+ ...clampSizeToMinimum({ heightPx: state.heightPx, widthPx: state.widthPx, x: state.x, y: state.y }),
+ mode: state.mode,
+ returnRegion: state.returnRegion,
+ stackOrder: state.stackOrder,
+ };
+ }
+
+ return Object.keys(floatingWidgets).length > 0 ? floatingWidgets : undefined;
+};
+
+/**
+ * An instance renders either in a region or in a floating window, never both.
+ *
+ * The region migrations above rebuild a rail that reads as an untouched default
+ * — and a rail missing a floated widget is exactly that shape — so on every
+ * reload they hand back a widget the person had floated. Floating wins: it is
+ * the deliberate act, while the region entry is the migration's guess.
+ *
+ * The center region is the exception, because it must always hold a view. If
+ * honouring the floating entries would empty it, they lose and the widget
+ * stays docked.
+ */
+const reconcileFloatingWidgets = (
+ widgetRegions: Record<WidgetRegion, WidgetRegionState>,
+ floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined
+): {
+ widgetRegions: Record<WidgetRegion, WidgetRegionState>;
+ floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined;
+} => {
+ if (!floatingWidgets) {
+ return { floatingWidgets, widgetRegions };
+ }
+
+ let remainingFloating = floatingWidgets;
+ const reconciledRegions = { ...widgetRegions };
+
+ for (const regionId of WIDGET_REGION_IDS) {
+ const region = reconciledRegions[regionId];
+ const instanceIds = region.instanceIds.filter((instanceId) => !remainingFloating[instanceId]);
+
+ if (instanceIds.length === region.instanceIds.length) {
+ continue;
+ }
+
+ if (regionId === 'center' && instanceIds.length === 0) {
+ remainingFloating = Object.fromEntries(
+ Object.entries(remainingFloating).filter(([instanceId]) => !region.instanceIds.includes(instanceId))
+ );
+ continue;
+ }
+
+ reconciledRegions[regionId] = {
+ ...region,
+ activeInstanceId: instanceIds.includes(region.activeInstanceId)
+ ? region.activeInstanceId
+ : (instanceIds[0] ?? region.activeInstanceId),
+ instanceIds,
+ isCollapsed: instanceIds.length === 0 ? regionId !== 'center' : region.isCollapsed,
+ };
+ }
+
+ return {
+ floatingWidgets: Object.keys(remainingFloating).length > 0 ? remainingFloating : undefined,
+ widgetRegions: reconciledRegions,
+ };
+};
+
const normalizePromptHistory = (value: unknown): PromptHistoryItem[] => {
if (!Array.isArray(value)) {
return [];
@@ -1385,12 +1500,22 @@ export const normalizeWorkbenchProject = (project: Project): Project => {
}
const canvas = cloneCanvas(migrateCanvasStateToV2(project.canvas));
+ const placement = reconcileFloatingWidgets(
+ {
+ left: leftRegion,
+ right: ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']),
+ bottom: legacyWidgetRegions?.bottom ?? legacyWidgetRegions?.['status-bar'] ?? defaultWidgetRegions.bottom,
+ center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),
+ },
+ normalizeFloatingWidgets((project as Partial<Project>).floatingWidgets, widgetInstances)
+ );
return {
...project,
// `project` may come straight from persisted storage (an unsafe cast boundary), so its
// canvas can still be v1-shaped, malformed, or missing — migrate before cloning.
canvas,
+ floatingWidgets: placement.floatingWidgets,
graphHistory: normalizeGraphHistory((project as Partial<Project>).graphHistory),
// Built-in preset ids were renamed for the three-preset model; a project
// saved under an old id must still resolve to the arrangement it names,
@@ -1400,12 +1525,7 @@ export const normalizeWorkbenchProject = (project: Project): Project => {
promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),
queue: normalizeWorkbenchQueueHistory(project.queue, { canvas, widgetInstances }),
settings: normalizeProjectSettings(project.settings),
- widgetRegions: {
- left: leftRegion,
- right: ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']),
- bottom: legacyWidgetRegions?.bottom ?? legacyWidgetRegions?.['status-bar'] ?? defaultWidgetRegions.bottom,
- center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),
- },
+ widgetRegions: placement.widgetRegions,
widgetInstances,
};
};
@@ -1885,9 +2005,12 @@ const applyLayoutPresetToProject = (project: Project, preset: LayoutPreset): Pro
return {
...project,
- // A preset is a full placement reset: floating windows dock implicitly,
- // otherwise an instance the preset places in a region would render twice.
- floatingWidgets: undefined,
+ // A preset is a full placement reset, so the project's own floating
+ // windows go: keeping one would double-render whatever the preset docks.
+ // The preset's are restored in their place — a preset saved while a widget
+ // floated has it in no region, and dropping them both would leave the
+ // instance nowhere at all.
+ floatingWidgets: snapshot.floatingWidgets ? cloneFloatingWidgets(snapshot.floatingWidgets) : undefined,
layout: {
...snapshot.layout,
panels: { ...snapshot.layout.panels },
@@ -3162,6 +3285,14 @@ export const __workbenchReducerInternal = (
}
const [hostRegionId, hostRegion] = hostEntry;
+
+ // The work surface must keep a view. `toggleRegionWidget` and
+ // `closeWidgetPlacement` refuse the same removal; floating it out is
+ // the same removal with a window attached.
+ if (hostRegionId === 'center' && hostRegion.instanceIds.length === 1) {
+ return project;
+ }
+
const instanceIds = hostRegion.instanceIds.filter((instanceId) => instanceId !== action.instanceId);
const fallbackInstanceId = getNextInstanceId(hostRegion, action.instanceId);
const floating: FloatingWidgetState = {
@@ -3183,6 +3314,10 @@ export const __workbenchReducerInternal = (
? fallbackInstanceId
: hostRegion.activeInstanceId,
instanceIds,
+ // Floating the last widget out of a rail leaves nothing to show,
+ // so the rail collapses rather than standing open and empty —
+ // the same repair `toggleRegionWidget` makes.
+ isCollapsed: instanceIds.length === 0 ? true : hostRegion.isCollapsed,
},
},
};
@@ -3233,6 +3368,18 @@ export const __workbenchReducerInternal = (
y: action.y,
});
+ // A pointer-down/up on the title bar with no movement still commits the
+ // starting geometry. Without this the project is marked dirty — and
+ // autosaved — every time someone clicks the window chrome.
+ if (
+ floating.heightPx === geometry.heightPx &&
+ floating.widthPx === geometry.widthPx &&
+ floating.x === geometry.x &&
+ floating.y === geometry.y
+ ) {
+ return project;
+ }
+
return {
...project,
floatingWidgets: { ...project.floatingWidgets, [action.instanceId]: { ...floating, ...geometry } },