Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(ui): preserve workspace state and share dynamic shell layout

Abdurrahman Fakhrulca69736dc4bf
diff --git a/components/external-app-frame.tsx b/components/external-app-frame.tsx
index 1993aa56..60afa47a 100644
--- a/components/external-app-frame.tsx
+++ b/components/external-app-frame.tsx
@@ -6,13 +6,17 @@ import type { WorkflowEmbed } from "@/lib/contracts/surface-app";
import { Button } from "@/components/ui/button";
export function ExternalAppFrame({ app, frameTitle }: { app: WorkflowEmbed; frameTitle?: string }) {
+ return <ExternalAppFrameContent key={app.url} app={app} frameTitle={frameTitle} />;
+}
+
+function ExternalAppFrameContent({ app, frameTitle }: { app: WorkflowEmbed; frameTitle?: string }) {
const [revision, setRevision] = useState(0);
const [loading, setLoading] = useState(true);
const [slow, setSlow] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setSlow(true), 15000);
return () => clearTimeout(timer);
- }, [revision]);
+ }, [revision, app.url]);
if (app.blocked || !app.url) return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm" data-slot="external-app-frame" role="alert">
<p>{app.reason || "This editor destination is unavailable."}</p>
<p className="text-xs text-muted-foreground">No editor or login link is opened. Configure a separate cookie-isolated origin before connecting.</p>
@@ -23,6 +27,7 @@ export function ExternalAppFrame({ app, frameTitle }: { app: WorkflowEmbed; fram
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>
{app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}
<Button asChild variant="outline" size="sm"><a href={app.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="size-4"/><span>Open {app.title}</span></a></Button>
+ {app.origin && app.url !== app.origin && app.url !== app.origin + "/" ? <Button asChild variant="ghost" size="sm"><a href={app.origin} target="_blank" rel="noopener noreferrer">Open home</a></Button> : null}
{app.renderer === "iframe" ? <Button variant="ghost" size="icon" onClick={reload} aria-label={`Reload ${app.title}`} title={`Reload ${app.title}`}><RefreshCw className="size-4"/></Button> : null}
</div>
{app.renderer === "iframe" ? <div className="relative min-h-0 min-w-0 flex-1">
diff --git a/components/ui/button.tsx b/components/ui/button.tsx
index a73bb2c3..3a321a2f 100644
--- a/components/ui/button.tsx
+++ b/components/ui/button.tsx
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0",
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:min-w-11 [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
@@ -19,10 +19,10 @@ const buttonVariants = cva(
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
},
size: {
- default: "h-9 px-4 py-2",
+ default: "h-[var(--ui-control-height,2.25rem)] px-[var(--ui-control-padding,1rem)] py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
- icon: "h-9 w-9",
+ icon: "h-[var(--ui-control-height,2.25rem)] w-[var(--ui-control-height,2.25rem)]",
},
},
defaultVariants: { variant: "default", size: "default" },
@@ -40,6 +40,7 @@ function Button({
const Comp = asChild ? Slot : "button";
return (
<Comp
+ data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx
index 7f774903..34dabb9d 100644
--- a/components/ui/dialog.tsx
+++ b/components/ui/dialog.tsx
@@ -61,7 +61,7 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
- "fixed top-[50%] left-[50%] z-50 grid grid-cols-[minmax(0,1fr)] w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
+ "fixed top-[50%] left-[50%] z-50 grid grid-cols-[minmax(0,1fr)] w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-[var(--surface,var(--background))] p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
diff --git a/components/ui/drawer.tsx b/components/ui/drawer.tsx
index ad086714..51ef2b8d 100644
--- a/components/ui/drawer.tsx
+++ b/components/ui/drawer.tsx
@@ -56,7 +56,7 @@ function DrawerContent({
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
- "group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
+ "group/drawer-content fixed z-50 flex h-auto flex-col bg-[var(--surface,var(--background))]",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
diff --git a/components/ui/input.tsx b/components/ui/input.tsx
index 46289d21..2ab900d0 100644
--- a/components/ui/input.tsx
+++ b/components/ui/input.tsx
@@ -4,9 +4,10 @@ import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
+ data-slot="input"
type={type}
className={cn(
- "flex h-8 w-full rounded-md border border-input bg-secondary px-2.5 py-1 text-sm shadow-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring disabled:opacity-50",
+ "flex h-[var(--ui-control-height,2rem)] w-full rounded-md border border-input bg-secondary px-2.5 py-1 text-sm shadow-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring disabled:opacity-50 [@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:text-base",
className,
)}
{...props}
diff --git a/components/ui/sheet.tsx b/components/ui/sheet.tsx
index c029d75c..1bf74e7a 100644
--- a/components/ui/sheet.tsx
+++ b/components/ui/sheet.tsx
@@ -60,7 +60,7 @@ function SheetContent({
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
- "fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
+ "fixed z-50 flex flex-col gap-4 bg-[var(--surface,var(--background))] shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
side === "right" &&
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
side === "left" &&
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 687a712a..eea5a966 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `ui` preserve workspace state and share dynamic shell layout
- `export` create the markdown export atomically, closing a TOCTOU write
- `a11y` scope the drawer inert to the compact layout
- `tui` the panel no longer scrolls itself away, and command output survives (#261)
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 7e3c3862..dfd4d1c9 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,22 @@
+## 2026-11-03: dynamic shell presentation and workspace recovery (local verification)
+
+The shell manifest now accepts per-shell layout metrics. Feature frames can override those
+metrics while shared controls, dialogs and the Integrations iframe inherit the active values.
+Viewport projection preserves preferred window geometry across resize, shell changes and
+reload; layout persistence flushes before page exit and ignores malformed cache entries.
+
+Mobile shells forward window identity to shared feature state. URL sync defers rewrites until
+a restored connected app appears in the asynchronous registry, preserving reload on phones.
+
+Integrations uses opaque navigation, one sidebar scroll, initial compact-pane inert state,
+deduplicated account badges and an explicit same-origin ready handshake. Workflows adds a
+real Sources action, distinct empty/filter states and unsaved-change guards. Desktop widgets
+remain reachable after resize, the dock keeps a usable size floor, n8n refreshes cancel stale
+requests, and live System Monitor no longer displays a fabricated GPU gauge.
+
+Validation and release status are recorded in `docs/UI-UX-FOUNDATION.md`. This entry describes
+local work on the task branch; it does not claim deployment or release to main.
+
## 2026-11-03: integrations UI closed out, and one merged fix that had been silently deleted
Everything below is merged. `main` at `269b6721`, working tree clean, gate green.
diff --git a/docs/README.md b/docs/README.md
index b624332f..8a7912ca 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -86,6 +86,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`ORCA-INTEGRATION.md`](./ORCA-INTEGRATION.md) | Orca web bridge readiness/identity contract, private state root and shared-runtime operator limits |
| [`MODELS-INTEGRATION.md`](./MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex provider model |
| [`SLICE-CATALOG.md`](./SLICE-CATALOG.md) | Current slice/AppShell feature inventory |
+| [`UI-UX-FOUNDATION.md`](./UI-UX-FOUNDATION.md) | Dynamic shell, feature and UI-kit spacing, workspace geometry and per-window feature state |
| [`TROUBLESHOOTING.md`](./TROUBLESHOOTING.md) | Symptom → cause → supported recovery |
| [`FAQ.md`](./FAQ.md) | Product/security/operator boundaries |
| [`../SECURITY.md`](../SECURITY.md) | Security posture and vulnerability reporting |
diff --git a/docs/UI-UX-FOUNDATION.md b/docs/UI-UX-FOUNDATION.md
new file mode 100644
index 00000000..e09a19bb
--- /dev/null
+++ b/docs/UI-UX-FOUNDATION.md
@@ -0,0 +1,100 @@
+# Dynamic MSO interface contract
+
+This is a refinement of the existing five shell identities in DESIGN.md. Shell chrome remains
+platform specific; feature behaviour and state are shared. No new adapter or backend provider
+has been added. Public MCP tools and authorization remain unchanged.
+
+## Configuration and ownership
+
+| Level | Owner | Contract |
+| --- | --- | --- |
+| Shell | ShellManifest.layout | Per-shell pagePadding, gap, controlHeight, controlPadding and sidebarWidth |
+| Feature | AppFrame.layout | Optional local metric overrides; padded=true opts a scrolling content body into page spacing |
+| UI kit | Button, Input, responsive dialog parts | Inherits semantic CSS metrics, with coarse-pointer minimum targets |
+
+All configuration values are finite positive CSS pixel dimensions up to 512, converted to rem.
+CSS variables are `--feature-padding`, `--feature-gap`, `--feature-sidebar-width`,
+`--ui-control-height` and `--ui-control-padding`. Root variables also reach portalled UI.
+The same-origin Integrations bridge copies only reviewed presentation tokens into its iframe.
+Feature containers still own their breakpoints. A compact window on a desktop must behave
+like a compact panel; it must not infer layout from the outer monitor width.
+
+```tsx
+const manifest: ShellManifest = {
+ brand, apps, features,
+ layout: { windows: { pagePadding: 24, sidebarWidth: 248 }, ios: { controlHeight: 44 } },
+};
+// A feature may override inherited values without changing other windows.
+<AppFrame padded layout={{ pagePadding: 16, gap: 8 }}>...</AppFrame>
+```
+
+Default controls: macOS/Windows/Dashboard 36 px, iOS 44 px, Android 48 px.
+Coarse-pointer buttons and inputs keep at least a 44 px target. Dense, intentionally sized
+variants can preserve desktop chrome proportions. Canvas features keep padded=false.
+Metric overrides are code configuration, not a new settings editor or remote preference API.
+
+## Feature state
+
+`useFeatureState(winId, key, initial)` keeps ephemeral UI state owned by an exact window.
+Desktop, mobile and dashboard mounts read the same snapshot; window closure prunes it.
+State is not written to disk or shared across users. Workflows uses this for drafts, selected
+nodes, runs, library mode, sessions, filters and details. Async updates after window closure
+are ignored. Browser reload still requires saving the workflow; the unsaved guard explains
+that boundary. Other features may adopt the hook; this does not claim every local state hook
+in the application has been migrated.
+
+Mobile iOS and Android now pass the exact window ID to feature content, just like desktop
+and Dashboard. A restored external-app URL is retained while its asynchronous registry loads;
+an unavailable descriptor cannot silently rewrite that route to Home.
+
+## State and geometry
+
+Window preferredRect stores user intent. Rendered x/y/w/h are a projection into the current
+work area. Viewport changes do not overwrite preferredRect. Explicit moves update position
+without losing a width constrained by a temporary viewport; explicit resizes update size.
+Snap/maximize preserve the normal rectangle. Reflow includes minimized windows and publishes
+one store notification for a batch, with none when nothing changed.
+
+Legacy saved arrays remain supported. Invalid geometry, invalid snap zones, duplicate IDs and
+unsafe object keys are discarded per entry. Boot hydration still merges under deep-link
+windows. Persistence stays browser-local and flushes pending snapshots on pagehide,
+visibility-hidden and hook cleanup. Storage quota/private mode failures remain nonfatal.
+
+Desktop widget positions are projected into measured container bounds without replacing their
+saved positions on resize. Oversized widgets scroll internally. Pointer cancellation and lost
+capture cancel dragging; pointer-up computes its final movement from the event coordinates.
+
+## Feature corrections
+
+- Integrations: solid sidebar background; one sidebar scroll; full owner picker header;
+ container-based initial inert state measured before visual transforms; resized panes reset navigation correctly; old observers
+ disconnect on redraw; credential fields use four desktop columns; duplicate source badges
+ collapse; Composio tools/session use progressive disclosure.
+- Manager readiness: the iframe posts a ready event after mounting. Parent accepts the exact
+ event only from that iframe and the same origin. A non-empty iframe src is not success.
+- Workflows: separate no-automation and no-match copy, Clear filters, real View sources action,
+ and confirmation before discarding changes on close, reload or changing workflow/session.
+- Dialogs/drawers/sheets: semantic opaque surfaces and inherited feature spacing.
+- Dock: 36 px icon floor, overflow scrolling, no magnification for touch or reduced motion.
+- n8n: pending requests abort on replacement/unmount; initial loading differs from not-configured;
+ external frames reset on URL changes and retain Open plus an origin-home fallback.
+- System Monitor: live sessions show real CPU/memory/disk. GPU simulation is limited to demo mode.
+
+## Verification and operational limits
+
+Targeted regression tests cover viewport/reload/maximize/minimize round trips, atomic updates,
+legacy cache validation and layout inheritance. Existing deep-link, shell, Integrations and
+dock tests remain in the validation set. Typecheck, lint and a separate-clone preview build
+passed during implementation. Full repository and security gates must be recorded against
+the final committed SHA before claiming PR readiness.
+
+Browser checks use a disposable release fixture with synthetic credentials and private stores.
+They must inspect actual readiness, keyboard access, scroll bounds and both themes, rather
+than infer correctness from source strings or an iframe load event.
+
+The reviewed external n8n route previously returned 404 and SAMEORIGIN. A frontend fallback
+does not repair a third-party route or override its frame policy. Missing provider setup and
+uninstalled apps from the feature audit remain installation/configuration facts. No deployment,
+provider credential changes, external security-header weakening or production session changes
+are part of this local implementation. Shipping follows the repository's main/release path
+after the operator authorizes push/PR/merge.
diff --git a/frontend/slices/appshell/components/desktop.tsx b/frontend/slices/appshell/components/desktop.tsx
index 1fd7fd78..f22c3427 100644
--- a/frontend/slices/appshell/components/desktop.tsx
+++ b/frontend/slices/appshell/components/desktop.tsx
@@ -1,5 +1,6 @@
"use client";
+import { LayoutBoundary } from "../design/layout-boundary";
import { Suspense, useEffect, useState, type ComponentType } from "react";
import { useResponsive } from "../responsive/use-responsive";
import { inEditable } from "../lib/use-focused-hotkey";
@@ -80,6 +81,7 @@ function Surface() {
return (
<ActiveShellProvider id={desc.id} surface={surface}>
+ <LayoutBoundary>
<div id="main-content" data-shell={desc.id} className="relative w-screen overflow-hidden" style={{ height: "var(--mso-visual-vh, 100dvh)" }}>
<Wallpaper shellDefault={desc.wallpaper} />
<ContextMenuHost>
@@ -90,6 +92,7 @@ function Surface() {
<Slot region="notifications" />
</ContextMenuHost>
</div>
+ </LayoutBoundary>
</ActiveShellProvider>
);
}
diff --git a/frontend/slices/appshell/components/dock.test.ts b/frontend/slices/appshell/components/dock.test.ts
index 240a402c..a1a46e0d 100644
--- a/frontend/slices/appshell/components/dock.test.ts
+++ b/frontend/slices/appshell/components/dock.test.ts
@@ -20,19 +20,19 @@ describe("dockFit", () => {
it("shrinks below the user's size before it ever scrolls", () => {
const { base, cramped } = dockFit(1280, 27, 2, MED, true);
expect(base).toBeLessThan(MED);
- expect(base).toBeGreaterThanOrEqual(22);
+ expect(base).toBeGreaterThanOrEqual(36);
expect(cramped).toBe(false);
});
- it("scrolls once even the 22px floor can't fit (agent workspace on a phone-width viewport)", () => {
+ it("scrolls once even the 36px floor can't fit (agent workspace on a phone-width viewport)", () => {
const { base, cramped, dockExtra } = dockFit(768, 27, 2, MED, true);
expect(cramped).toBe(true);
- expect(base).toBe(22); // floored, never smaller
+ expect(base).toBe(36); // floored, never smaller
expect(dockExtra).toBe(0); // magnification off — its geometry assumes no scroll
});
it("reclaims the hover-growth reserve when magnification is off", () => {
- expect(dockFit(900, 27, 2, MED, false).base).toBeGreaterThan(dockFit(900, 27, 2, MED, true).base);
+ expect(dockFit(1400, 27, 2, MED, false).base).toBeGreaterThan(dockFit(1400, 27, 2, MED, true).base);
});
it("reserves the entire hover pool inside the viewport", () => {
diff --git a/frontend/slices/appshell/components/dock.tsx b/frontend/slices/appshell/components/dock.tsx
index 6165f0c0..a32857d3 100644
--- a/frontend/slices/appshell/components/dock.tsx
+++ b/frontend/slices/appshell/components/dock.tsx
@@ -21,7 +21,7 @@ import type { AppDescriptor, WindowState } from "../lib/types";
const SEP_W = 13; // divider slot px
const GAP = 8; // px between slots
const MAG_SIGMA = 100; // bell-curve spread (≈3 icons each side ripple)
-const MIN_ICON = 22; // shrink floor — past it the row scrolls instead
+const MIN_ICON = 36; // shrink floor — past it the row scrolls instead
// Resting icon size shrinks to fit the viewport, like the real macOS dock: slots
// are shrink-0, so an overrun silently eats BOTH ends (Launchpad + Mission Control
@@ -173,7 +173,7 @@ export function Dock({ onMissionControl }: { onMissionControl?: () => void }) {
<div className={cramped ? "-mt-64 max-w-[calc(100vw-16px)] overflow-x-auto pt-64 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" : "contents"}>
<div
ref={rowRef}
- onPointerMove={(e) => { mouseX.current = e.clientX; schedule(); }}
+ onPointerMove={(e) => { if (e.pointerType !== "mouse" || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return; mouseX.current = e.clientX; schedule(); }}
onPointerLeave={() => { mouseX.current = null; schedule(); }}
className={`macos-dock glass pointer-events-auto flex items-end rounded-[22px] border border-white/40 px-2.5 py-2 shadow-[0_1px_0_rgba(255,255,255,0.4)_inset,0_18px_50px_-10px_rgba(0,0,0,0.5)] dark:border-white/10 ${cramped ? "w-max" : ""}`}
style={{ background: "var(--dock-bg)", gap: GAP }}
diff --git a/frontend/slices/appshell/components/mobile-shell.tsx b/frontend/slices/appshell/components/mobile-shell.tsx
index 590d029a..0dc5fa86 100644
--- a/frontend/slices/appshell/components/mobile-shell.tsx
+++ b/frontend/slices/appshell/components/mobile-shell.tsx
@@ -224,7 +224,7 @@ export function MobileShell() {
className="relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto [container-type:inline-size]"
style={{ "--sai-bottom": "max(env(safe-area-inset-bottom, 0px), 34px)" } as React.CSSProperties}
>
- <WindowContent app={top.app} payload={top.payload} />
+ <WindowContent key={top.id} app={top.app} payload={top.payload} winId={top.id} />
</main>
<div className="absolute inset-x-0 bottom-0 z-[5]">
<HomeIndicator light={false} onHome={goHome} onSwitcher={openSwitcher} onSwitchApp={switchApp} />
diff --git a/frontend/slices/appshell/components/shells/android/android-shell.tsx b/frontend/slices/appshell/components/shells/android/android-shell.tsx
index f47f8740..3b1572a5 100644
--- a/frontend/slices/appshell/components/shells/android/android-shell.tsx
+++ b/frontend/slices/appshell/components/shells/android/android-shell.tsx
@@ -217,7 +217,7 @@ function AndroidShell() {
onAI={toggleInspector}
/>
<main className="relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto [container-type:inline-size]">
- <WindowContent app={top.app} payload={top.payload} />
+ <WindowContent key={top.id} app={top.app} payload={top.payload} winId={top.id} />
</main>
{showSystemNav && <NavBar onBack={mobileNav?.onBack ?? goHome} onHome={goHome} onRecents={() => setRecents(true)} />}
</div>
diff --git a/frontend/slices/appshell/design/index.ts b/frontend/slices/appshell/design/index.ts
index 57550938..1cc6c85f 100644
--- a/frontend/slices/appshell/design/index.ts
+++ b/frontend/slices/appshell/design/index.ts
@@ -1,3 +1,6 @@
export { SHELL_DESIGN_PROFILES, designProfileFor } from "./profiles";
export { useShellDesign } from "./use-shell-design";
export type { ShellDesignProfile, SettingsNavigationStyle, DialogPresentation, MobileNavigationStyle } from "./types";
+
+export { shellLayout, layoutVariables } from "./layout";
+export type { LayoutMetrics, LayoutConfig } from "./layout";
diff --git a/frontend/slices/appshell/design/layout-boundary.tsx b/frontend/slices/appshell/design/layout-boundary.tsx
new file mode 100644
index 00000000..b7a85533
--- /dev/null
+++ b/frontend/slices/appshell/design/layout-boundary.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { useEffect, useMemo, type ReactNode } from "react";
+import { useActiveShell } from "../registry/shells";
+import { useShellConfig } from "../registry/shell-config";
+import { shellLayout } from "./layout";
+
+/** Portalled UI and iframe bridges inherit the same active shell metrics. */
+export function LayoutBoundary({ children }: { children: ReactNode }) {
+ const { id } = useActiveShell();
+ const { layout } = useShellConfig();
+ const variables = useMemo(() => shellLayout(id, layout), [id, layout]);
+ useEffect(() => {
+ const style = document.documentElement.style;
+ const previous = Object.keys(variables).map((key) => [key, style.getPropertyValue(key)]);
+ Object.entries(variables).forEach(([key, value]) => style.setProperty(key, String(value)));
+ return () => previous.forEach(([key, value]) => { if (value) style.setProperty(key, value); else style.removeProperty(key); });
+ }, [variables]);
+ return <div className="contents" style={variables}>{children}</div>;
+}
diff --git a/frontend/slices/appshell/design/layout.test.ts b/frontend/slices/appshell/design/layout.test.ts
new file mode 100644
index 00000000..bb4617fd
--- /dev/null
+++ b/frontend/slices/appshell/design/layout.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { layoutVariables, shellLayout } from "./layout";
+
+describe("three-level presentation configuration", () => {
+ it("inherits each shell profile and applies only its own overrides", () => {
+ expect(shellLayout("ios")).toMatchObject({ "--ui-control-height": "2.75rem" });
+ expect(shellLayout("android")).toMatchObject({ "--ui-control-height": "3rem" });
+ const config = { windows: { pagePadding: 32, sidebarWidth: 288 } };
+ expect(shellLayout("windows", config)).toMatchObject({ "--feature-padding": "2rem", "--feature-sidebar-width": "18rem" });
+ expect(shellLayout("macos", config)).toEqual(shellLayout("macos"));
+ });
+ it("allows feature overrides without accepting invalid CSS dimensions", () => {
+ expect(layoutVariables({ gap: 24, controlHeight: NaN, pagePadding: -3, sidebarWidth: Infinity })).toEqual({ "--feature-gap": "1.5rem" });
+ });
+});
diff --git a/frontend/slices/appshell/design/layout.ts b/frontend/slices/appshell/design/layout.ts
new file mode 100644
index 00000000..f3daa364
--- /dev/null
+++ b/frontend/slices/appshell/design/layout.ts
@@ -0,0 +1,23 @@
+import type { CSSProperties } from "react";
+import type { ShellId } from "../registry/shells";
+
+export type LayoutMetrics = { pagePadding: number; gap: number; controlHeight: number; controlPadding: number; sidebarWidth: number };
+export type LayoutConfig = Partial<Record<ShellId, Partial<LayoutMetrics>>>;
+const defaults: Record<ShellId, LayoutMetrics> = {
+ macos: { pagePadding: 20, gap: 12, controlHeight: 36, controlPadding: 12, sidebarWidth: 240 },
+ windows: { pagePadding: 24, gap: 12, controlHeight: 36, controlPadding: 12, sidebarWidth: 248 },
+ ios: { pagePadding: 20, gap: 16, controlHeight: 44, controlPadding: 16, sidebarWidth: 272 },
+ android: { pagePadding: 16, gap: 16, controlHeight: 48, controlPadding: 16, sidebarWidth: 280 },
+ dashboard: { pagePadding: 16, gap: 8, controlHeight: 36, controlPadding: 12, sidebarWidth: 224 },
+};
+const names: Record<keyof LayoutMetrics, string> = {
+ pagePadding: "--feature-padding", gap: "--feature-gap", controlHeight: "--ui-control-height",
+ controlPadding: "--ui-control-padding", sidebarWidth: "--feature-sidebar-width",
+};
+export function layoutVariables(metrics: Partial<LayoutMetrics>): CSSProperties {
+ return Object.fromEntries(Object.entries(metrics).filter(([, value]) => Number.isFinite(value) && value > 0 && value <= 512)
+ .map(([key, value]) => [names[key as keyof LayoutMetrics], `${value / 16}rem`])) as CSSProperties;
+}
+export function shellLayout(id: ShellId, config?: LayoutConfig): CSSProperties {
+ return layoutVariables({ ...defaults[id], ...config?.[id] });
+}
diff --git a/frontend/slices/appshell/features/widgets/components/desktop-widgets.tsx b/frontend/slices/appshell/features/widgets/components/desktop-widgets.tsx
index 0c80cfe4..32f4f620 100644
--- a/frontend/slices/appshell/features/widgets/components/desktop-widgets.tsx
+++ b/frontend/slices/appshell/features/widgets/components/desktop-widgets.tsx
@@ -29,6 +29,17 @@ const SIZE_PX: Record<WidgetSize, number> = { s: 176, m: 240, l: 288 };
// buttons keep working); the move commits once on drop (not every frame). Right-
// click sets its size or removes it.
function DesktopWidget({ id, size, pos }: { id: string; size: WidgetSize; pos: WidgetPos }) {
+ const element = useRef<HTMLDivElement>(null);
+ const [bounds, setBounds] = useState({ w: 0, h: 0, cardH: 0 });
+ useEffect(() => {
+ const card = element.current, parent = card?.parentElement;
+ if (!card || !parent) return;
+ const measure = () => setBounds({ w: parent.clientWidth, h: parent.clientHeight, cardH: card.offsetHeight });
+ const observer = new ResizeObserver(measure);
+ observer.observe(parent); observer.observe(card);
+ measure();
+ return () => observer.disconnect();
+ }, []);
const ctx = useContextMenu();
const Render = WIDGET_RENDER[id];
const drag = useRef<{ x: number; y: number } | null>(null);
@@ -47,12 +58,14 @@ function DesktopWidget({ id, size, pos }: { id: string; size: WidgetSize; pos: W
if (!drag.current) return;
setOffset({ dx: e.clientX - drag.current.x, dy: e.clientY - drag.current.y });
};
- const onPointerUp = () => {
- if (drag.current && offset) setWidgetPos(id, pos.x + offset.dx, pos.y + offset.dy);
+ const onPointerUp = (e: React.PointerEvent) => {
+ if (drag.current) setWidgetPos(id, origin.x + e.clientX - drag.current.x, origin.y + e.clientY - drag.current.y);
drag.current = null;
setOffset(null);
};
+ const origin = { x: Math.max(0, Math.min(pos.x, bounds.w - SIZE_PX[size])), y: Math.max(0, Math.min(pos.y, bounds.h - bounds.cardH)) };
+ const cancelDrag = () => { drag.current = null; setOffset(null); };
const items: MenuItem[] = [
{ label: "Small", icon: size === "s" ? Check : undefined, onClick: () => setWidgetSize(id, "s") },
{ label: "Medium", icon: size === "m" ? Check : undefined, onClick: () => setWidgetSize(id, "m") },
@@ -64,6 +77,7 @@ function DesktopWidget({ id, size, pos }: { id: string; size: WidgetSize; pos: W
return (
<div
+ ref={element}
className={cn(
// Elevation so a widget reads as the same floating surface family as
// windows (which carry --shadow-win). filter drop-shadow — not box-shadow
@@ -71,10 +85,12 @@ function DesktopWidget({ id, size, pos }: { id: string; size: WidgetSize; pos: W
"pointer-events-auto absolute touch-none cursor-grab active:cursor-grabbing drop-shadow-[0_8px_24px_rgba(0,0,0,0.28)]",
SIZE_W[size],
)}
- style={{ left: pos.x + (offset?.dx ?? 0), top: pos.y + (offset?.dy ?? 0) }}
+ style={{ left: origin.x + (offset?.dx ?? 0), top: origin.y + (offset?.dy ?? 0), maxWidth: "100%", maxHeight: "100%", overflowY: "auto" }}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
+ onPointerCancel={cancelDrag}
+ onLostPointerCapture={cancelDrag}
onContextMenu={(e) => { e.stopPropagation(); ctx.open(e); }}
>
{createElement(Render)}
diff --git a/frontend/slices/appshell/hooks/use-feature-state.ts b/frontend/slices/appshell/hooks/use-feature-state.ts
new file mode 100644
index 00000000..1c6e5085
--- /dev/null
+++ b/frontend/slices/appshell/hooks/use-feature-state.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { useCallback, useState, useSyncExternalStore, type Dispatch, type SetStateAction } from "react";
+import { shellStore } from "../lib/store-state";
+import { featureStateKey, readFeatureState, subscribeFeatureState, writeFeatureState } from "../lib/feature-state";
+
+/** Per-window UI state shared by desktop, mobile and dashboard mounts. No disk storage. */
+export function useFeatureState<T>(windowId: string | undefined, feature: string, initial: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
+ const [fallback, setFallback] = useState(initial);
+ const key = featureStateKey(windowId ?? "", feature);
+ const subscribe = useCallback((notify: () => void) => subscribeFeatureState(key, notify), [key]);
+ const snapshot = useCallback(() => windowId ? readFeatureState(key, fallback) : fallback, [key, windowId, fallback]);
+ const serverSnapshot = useCallback(() => fallback, [fallback]);
+ const value = useSyncExternalStore(subscribe, snapshot, serverSnapshot);
+ const setValue = useCallback<Dispatch<SetStateAction<T>>>((next) => {
+ if (!windowId) { setFallback(next); return; }
+ if (!shellStore.getWindow(windowId)) return;
+ const previous = readFeatureState(key, fallback);
+ const result = typeof next === "function" ? (next as (value: T) => T)(previous) : next;
+ writeFeatureState(key, windowId, result);
+ }, [key, windowId, fallback]);
+ return [value, setValue];
+}
diff --git a/frontend/slices/appshell/hooks/use-persist-layout.ts b/frontend/slices/appshell/hooks/use-persist-layout.ts
index 0e01eb4e..3397ca60 100644
--- a/frontend/slices/appshell/hooks/use-persist-layout.ts
+++ b/frontend/slices/appshell/hooks/use-persist-layout.ts
@@ -4,7 +4,7 @@ import { useEffect, useRef } from "react";
import { shellStore, hydrateBoot, serialize, retileSnapped } from "../lib/store";
import { useApps } from "../lib/registry";
import { useShellConfig } from "../registry/shell-config";
-import type { PersistedWindow } from "../lib/types";
+import { parseLayout } from "../lib/parse-layout";
// Window layout persists to localStorage (per-browser, debounced). No backend —
// the layout is inherently per-device, so the browser IS the right home for it.
@@ -28,7 +28,7 @@ export function usePersistLayout() {
useEffect(() => {
try {
const raw = localStorage.getItem(persistKey);
- if (raw) hydrateBoot(JSON.parse(raw) as PersistedWindow[], multiApps.current);
+ if (raw) hydrateBoot(parseLayout(raw), multiApps.current);
} catch {
/* corrupt cache — start clean */
}
@@ -52,20 +52,30 @@ export function usePersistLayout() {
useEffect(() => {
let timer: ReturnType<typeof setTimeout> | null = null;
+ let pending = false;
+ const flush = () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ if (!pending) return;
+ try {
+ localStorage.setItem(persistKey, JSON.stringify(serialize()));
+ pending = false;
+ } catch { /* quota / private mode */ }
+ };
+ const onVisibility = () => { if (document.visibilityState === "hidden") flush(); };
const unsub = shellStore.subscribe(() => {
if (!ready.current) return;
+ pending = true;
if (timer) clearTimeout(timer);
- timer = setTimeout(() => {
- try {
- localStorage.setItem(persistKey, JSON.stringify(serialize()));
- } catch {
- /* quota / private mode */
- }
- }, 600); // never persist per-frame
+ timer = setTimeout(flush, 600);
});
+ window.addEventListener("pagehide", flush);
+ document.addEventListener("visibilitychange", onVisibility);
return () => {
- if (timer) clearTimeout(timer);
+ flush();
unsub();
+ window.removeEventListener("pagehide", flush);
+ document.removeEventListener("visibilitychange", onVisibility);
};
}, [persistKey]);
}
diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.ts
index 66f29c0c..390fbaa2 100644
--- a/frontend/slices/appshell/index.ts
+++ b/frontend/slices/appshell/index.ts
@@ -202,3 +202,6 @@ export type {
// consumer drops `features: DEFAULT_FEATURES` into its manifest in one line.
export { mdToHtml } from "./features/widgets/components/md";
export * from "./defaults";
+
+export { useFeatureState } from "./hooks/use-feature-state";
+export type { LayoutMetrics, LayoutConfig } from "./design";
diff --git a/frontend/slices/appshell/lib/feature-state.test.ts b/frontend/slices/appshell/lib/feature-state.test.ts
new file mode 100644
index 00000000..501a0bbc
--- /dev/null
+++ b/frontend/slices/appshell/lib/feature-state.test.ts
@@ -0,0 +1,24 @@
+import { afterEach, expect, it } from "vitest";
+import { featureStateKey, readFeatureState, writeFeatureState, subscribeFeatureState, pruneFeatureState } from "./feature-state";
+import { openWindow, closeWindow } from "./store";
+
+afterEach(() => pruneFeatureState(new Set()));
+it("preserves a draft across unmount/remount subscriptions and isolates each window", () => {
+ const key = featureStateKey("w1", "draft"), other = featureStateKey("w2", "draft");
+ const draft = { title: "Unsaved" }; let calls = 0;
+ const off = subscribeFeatureState(key, () => calls++);
+ writeFeatureState(key, "w1", draft); off();
+ expect(readFeatureState(key, null)).toBe(draft);
+ expect(readFeatureState(other, null)).toBeNull();
+ const offAgain = subscribeFeatureState(key, () => calls++);
+ writeFeatureState(key, "w1", draft);
+ expect(calls).toBe(1); offAgain();
+});
+it("releases state when the owning window closes without affecting another window", () => {
+ const id = openWindow("a", "A"), other = openWindow("b", "B");
+ const key = featureStateKey(id, "draft"), otherKey = featureStateKey(other, "draft");
+ writeFeatureState(key, id, "a"); writeFeatureState(otherKey, other, "b");
+ closeWindow(id);
+ expect(readFeatureState(key, null)).toBeNull();
+ expect(readFeatureState(otherKey, null)).toBe("b"); closeWindow(other);
+});
diff --git a/frontend/slices/appshell/lib/feature-state.ts b/frontend/slices/appshell/lib/feature-state.ts
new file mode 100644
index 00000000..9935dff3
--- /dev/null
+++ b/frontend/slices/appshell/lib/feature-state.ts
@@ -0,0 +1,25 @@
+type Entry = { windowId: string; value: unknown };
+const entries = new Map<string, Entry>();
+const listeners = new Map<string, Set<() => void>>();
+export const featureStateKey = (windowId: string, feature: string) => JSON.stringify([windowId, feature]);
+export function readFeatureState<T>(key: string, initial: T): T {
+ return entries.has(key) ? entries.get(key)!.value as T : initial;
+}
+export function writeFeatureState<T>(key: string, windowId: string, value: T) {
+ if (entries.has(key) && Object.is(entries.get(key)!.value, value)) return;
+ entries.set(key, { windowId, value });
+ listeners.get(key)?.forEach((notify) => notify());
+}
+export function subscribeFeatureState(key: string, notify: () => void) {
+ const group = listeners.get(key) ?? new Set<() => void>();
+ group.add(notify); listeners.set(key, group);
+ return () => { group.delete(notify); if (!group.size) listeners.delete(key); };
+}
+/** Ephemeral UI state survives a shell remount, but never the owning window. */
+export function pruneFeatureState(activeWindows: ReadonlySet<string>) {
+ for (const [key, entry] of entries) {
+ if (activeWindows.has(entry.windowId)) continue;
+ entries.delete(key);
+ listeners.get(key)?.forEach((notify) => notify());
+ }
+}
diff --git a/frontend/slices/appshell/lib/layout-roundtrip.test.ts b/frontend/slices/appshell/lib/layout-roundtrip.test.ts
new file mode 100644
index 00000000..4ef3f1c6
--- /dev/null
+++ b/frontend/slices/appshell/lib/layout-roundtrip.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { closeAll, openWindow, moveWindow, resizeWindow, toggleMaximize, minimizeWindow, snapWindow, retileSnapped, applyChromeInsets, serialize, hydrate } from "./store";
+import { shellStore } from "./store-state";
+import { parseLayout } from "./parse-layout";
+
+function viewport(w: number, h: number) { vi.stubGlobal("window", { innerWidth: w, innerHeight: h }); }
+beforeEach(() => { viewport(1920, 1080); closeAll(); applyChromeInsets({ top: 34, bottom: 92 }); });
+afterEach(() => { closeAll(); vi.unstubAllGlobals(); });
+
+describe("preferred workspace geometry", () => {
+ it("restores desktop size after phone rotation and a saved-layout reload", () => {
+ const id = openWindow("editor", "Editor", { w: 1100, h: 700 });
+ moveWindow(id, 160, 80);
+ viewport(390, 844); retileSnapped();
+ expect(shellStore.getWindow(id)?.w).toBe(374);
+ moveWindow(id, 8, 8);
+ expect(shellStore.getWindow(id)?.preferredRect?.w).toBe(1100);
+ moveWindow(id, 160, 80);
+ const saved = parseLayout(JSON.stringify(serialize()));
+ hydrate(saved);
+ viewport(1920, 1080); retileSnapped();
+ expect(shellStore.getWindow(id)).toMatchObject({ x: 160, y: 80, w: 1100, h: 700 });
+ });
+ it("preserves the requested size when first opened on a small viewport", () => {
+ viewport(320, 568);
+ const id = openWindow("files", "Files", { w: 900, h: 650 });
+ viewport(1920, 1080); retileSnapped();
+ expect(shellStore.getWindow(id)).toMatchObject({ w: 900, h: 650 });
+ });
+ it("updates intent on explicit resize and restores it after maximize", () => {
+ const id = openWindow("files", "Files");
+ resizeWindow(id, 920, 600); toggleMaximize(id);
+ viewport(390, 844); retileSnapped(); toggleMaximize(id);
+ expect(shellStore.getWindow(id)?.w).toBe(374);
+ viewport(1920, 1080); retileSnapped();
+ expect(shellStore.getWindow(id)).toMatchObject({ w: 920, h: 600, maximized: false });
+ });
+ it("reflows minimized windows and publishes one atomic geometry update", () => {
+ const a = openWindow("a", "A"), b = openWindow("b", "B");
+ minimizeWindow(a); snapWindow(b, "right");
+ const listener = vi.fn(), off = shellStore.subscribe(listener);
+ viewport(390, 844); retileSnapped();
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(shellStore.getWindow(a)?.w).toBe(374);
+ expect(shellStore.getWindow(b)?.x).toBeGreaterThan(0);
+ off();
+ });
+ it("does not emit or rewrite state when geometry is unchanged", () => {
+ openWindow("a", "A");
+ const listener = vi.fn(), off = shellStore.subscribe(listener);
+ retileSnapped(); retileSnapped();
+ expect(listener).not.toHaveBeenCalled(); off();
+ });
+});
+
+describe("saved layout validation", () => {
+ it("keeps valid legacy windows while rejecting malformed and duplicate records", () => {
+ openWindow("a", "A"); const valid = serialize()[0];
+ const legacy = { ...valid, preferredRect: undefined };
+ expect(parseLayout(JSON.stringify([null, {}, legacy, legacy, { ...valid, id: "bad", w: -1 }, { ...valid, id: "zone", snapZone: "unknown" }]))).toEqual([legacy]);
+ });
+ it("rejects malformed geometry and accepts an empty workspace", () => {
+ openWindow("a", "A"); const valid = serialize()[0];
+ expect(parseLayout(JSON.stringify([{ ...valid, preferredRect: { x: 0, y: 0, w: null, h: 1 } }]))).toEqual([]);
+ expect(parseLayout("{}")).toEqual([]);
+ expect(parseLayout("[]")).toEqual([]);
+ });
+});
diff --git a/frontend/slices/appshell/lib/parse-layout.ts b/frontend/slices/appshell/lib/parse-layout.ts
new file mode 100644
index 00000000..57a809d2
--- /dev/null
+++ b/frontend/slices/appshell/lib/parse-layout.ts
@@ -0,0 +1,26 @@
+import type { PersistedWindow, Rect, SnapZone } from "./types";
+
+const zones = new Set<SnapZone>(["left", "right", "top", "tl", "tr", "bl", "br", "l13", "r23", "l23", "r13"]);
+function validRect(value: unknown): value is Rect {
+ if (!value || typeof value !== "object") return false;
+ const r = value as Rect;
+ return [r.x, r.y, r.w, r.h].every(Number.isFinite) && r.w > 0 && r.h > 0;
+}
+
+/** Ignore corrupt entries without discarding the remaining saved workspace. */
+export function parseLayout(raw: string): PersistedWindow[] {
+ const value: unknown = JSON.parse(raw);
+ if (!Array.isArray(value)) return [];
+ const ids = new Set<string>();
+ return value.filter((entry): entry is PersistedWindow => {
+ if (!entry || typeof entry !== "object" || !validRect(entry)) return false;
+ const p = entry as PersistedWindow;
+ if (typeof p.id !== "string" || !p.id || ["__proto__", "constructor", "prototype"].includes(p.id) || ids.has(p.id) || typeof p.app !== "string" || !p.app || typeof p.title !== "string") return false;
+ if (typeof p.minimized !== "boolean" || typeof p.maximized !== "boolean") return false;
+ if (p.snapZone !== undefined && !zones.has(p.snapZone)) return false;
+ if (p.preferredRect !== undefined && !validRect(p.preferredRect)) return false;
+ if (p.prevRect !== undefined && !validRect(p.prevRect)) return false;
+ ids.add(p.id);
+ return true;
+ });
+}
diff --git a/frontend/slices/appshell/lib/store-geometry.ts b/frontend/slices/appshell/lib/store-geometry.ts
index 769745f8..6c53fa1d 100644
--- a/frontend/slices/appshell/lib/store-geometry.ts
+++ b/frontend/slices/appshell/lib/store-geometry.ts
@@ -87,13 +87,13 @@ export function spawnRect(n: number, w: number, h: number): Rect {
export function clampRect(r: Rect): Rect {
if (typeof window === "undefined") return r;
const { vw, top, bottom } = workArea();
- const w = Math.min(r.w, vw - GAP * 2);
- const h = Math.min(r.h, bottom - top);
+ const w = Math.max(1, Math.min(Number.isFinite(r.w) && r.w > 0 ? r.w : 720, vw - GAP * 2));
+ const h = Math.max(1, Math.min(Number.isFinite(r.h) && r.h > 0 ? r.h : 460, bottom - top));
return {
w,
h,
- x: Math.max(GAP, Math.min(r.x, vw - GAP - w)),
- y: Math.max(top, Math.min(r.y, bottom - h)),
+ x: Math.max(GAP, Math.min(Number.isFinite(r.x) ? r.x : GAP, vw - GAP - w)),
+ y: Math.max(top, Math.min(Number.isFinite(r.y) ? r.y : top, bottom - h)),
};
}
diff --git a/frontend/slices/appshell/lib/store-persist.ts b/frontend/slices/appshell/lib/store-persist.ts
index 744a26f9..e0b48063 100644
Binary files a/frontend/slices/appshell/lib/store-persist.ts and b/frontend/slices/appshell/lib/store-persist.ts differ
diff --git a/frontend/slices/appshell/lib/store-snap.ts b/frontend/slices/appshell/lib/store-snap.ts
index bf11a124..ed29cfc4 100644
--- a/frontend/slices/appshell/lib/store-snap.ts
+++ b/frontend/slices/appshell/lib/store-snap.ts
@@ -1,5 +1,5 @@
import type { WinId, SnapZone } from "./types";
-import { M, patch } from "./store-state";
+import { M, patch, emit } from "./store-state";
import { GAP, workArea, snapRect, clampRect, setChromeInsets } from "./store-geometry";
// Snap + chrome-inset actions, split from store.ts (≤200 LOC discipline).
@@ -20,16 +20,23 @@ export function applyChromeInsets(i: { top?: number; bottom?: number }) {
export function retileSnapped() {
if (typeof window === "undefined") return;
const { vw, top, bottom } = workArea();
- M.state.order.forEach((id) => {
- const win = M.state.windows[id];
- if (!win || win.minimized) return;
- if (win.maximized) patch(id, { x: GAP, y: top, w: vw - GAP * 2, h: bottom - top });
- else if (win.snapZone) patch(id, snapRect(win.snapZone));
- else {
- const c = clampRect({ x: win.x, y: win.y, w: win.w, h: win.h });
- if (c.x !== win.x || c.y !== win.y || c.w !== win.w || c.h !== win.h) patch(id, c);
+ const windows = { ...M.state.windows };
+ let changed = false;
+ for (const id of M.state.order) {
+ const win = windows[id];
+ if (!win) continue;
+ const preferredRect = win.preferredRect ?? win.prevRect ?? { x: win.x, y: win.y, w: win.w, h: win.h };
+ const rect = win.maximized ? { x: GAP, y: top, w: vw - GAP * 2, h: bottom - top }
+ : win.snapZone ? snapRect(win.snapZone) : clampRect(preferredRect);
+ if (!win.preferredRect || Object.entries(rect).some(([key, value]) => win[key as keyof typeof rect] !== value)) {
+ windows[id] = { ...win, ...rect, preferredRect };
+ changed = true;
}
- });
+ }
+ if (changed) {
+ M.state = { ...M.state, windows };
+ emit();
+ }
}
export function snapWindow(id: WinId, zone: SnapZone) {
@@ -39,7 +46,8 @@ export function snapWindow(id: WinId, zone: SnapZone) {
...snapRect(zone),
maximized: false,
snapZone: zone,
- prevRect: { x: win.x, y: win.y, w: win.w, h: win.h },
+ prevRect: win.preferredRect ?? win.prevRect ?? { x: win.x, y: win.y, w: win.w, h: win.h },
+ preferredRect: win.preferredRect ?? win.prevRect ?? { x: win.x, y: win.y, w: win.w, h: win.h },
});
// Snap-Assist pulse: a transient one-shot for half-snaps (left/right) so a
// shell can offer the other windows for the complementary zone. Pure UI
diff --git a/frontend/slices/appshell/lib/store-state.ts b/frontend/slices/appshell/lib/store-state.ts
index d39f86f1..eac521f9 100644
--- a/frontend/slices/appshell/lib/store-state.ts
+++ b/frontend/slices/appshell/lib/store-state.ts
@@ -1,3 +1,4 @@
+import { pruneFeatureState } from "./feature-state";
import type { ShellState, WindowState, WinId } from "./types";
// Module-level external store, held in a mutable `M` object (not a rebindable
@@ -24,7 +25,12 @@ export const M = {
const listeners = new Set<Listener>();
+let previousOrder = M.state.order;
export function emit() {
+ if (previousOrder !== M.state.order) {
+ previousOrder = M.state.order;
+ pruneFeatureState(new Set(previousOrder));
+ }
listeners.forEach((l) => l());
}
diff --git a/frontend/slices/appshell/lib/store.ts b/frontend/slices/appshell/lib/store.ts
index 3b33c3d9..ed373a12 100644
--- a/frontend/slices/appshell/lib/store.ts
+++ b/frontend/slices/appshell/lib/store.ts
@@ -1,6 +1,6 @@
import type { WindowState, WinId } from "./types";
import { M, emit, patch, topZ } from "./store-state";
-import { GAP, workArea, spawnRect } from "./store-geometry";
+import { GAP, workArea, spawnRect, clampRect } from "./store-geometry";
// Store barrel: state in store-state; geometry in store-geometry; snap in
// store-snap; hydrate/serialize in store-persist.
@@ -34,6 +34,7 @@ export function openWindow(
app,
title,
...spawnRect(M.state.order.length, size?.w ?? 720, size?.h ?? 460),
+ preferredRect: { x: 80 + (M.state.order.length % 6) * 28, y: 64 + (M.state.order.length % 6) * 28, w: size?.w ?? 720, h: size?.h ?? 460 },
z: topZ() + 1,
minimized: false,
maximized: false,
@@ -113,10 +114,14 @@ export function focusApp(app: string, payload?: unknown): boolean {
}
export function moveWindow(id: WinId, x: number, y: number) {
- patch(id, { x, y, snapZone: undefined }); // free move leaves the snap grid
+ const win = M.state.windows[id];
+ if (!win) return;
+ patch(id, { x, y, preferredRect: { x, y, w: win.preferredRect?.w ?? win.w, h: win.preferredRect?.h ?? win.h }, snapZone: undefined }); // free move leaves the snap grid
}
export function resizeWindow(id: WinId, w: number, h: number) {
- patch(id, { w, h, snapZone: undefined });
+ const win = M.state.windows[id];
+ if (!win) return;
+ patch(id, { w, h, preferredRect: { x: win.x, y: win.y, w, h }, snapZone: undefined });
}
export function minimizeWindow(id: WinId) {
patch(id, { minimized: true });
@@ -129,8 +134,8 @@ export function toggleMaximize(id: WinId) {
const win = M.state.windows[id];
if (!win) return;
if (win.maximized) {
- const r = win.prevRect ?? { x: win.x, y: win.y, w: win.w, h: win.h };
- patch(id, { ...r, maximized: false, prevRect: undefined });
+ const r = win.preferredRect ?? win.prevRect ?? { x: win.x, y: win.y, w: win.w, h: win.h };
+ patch(id, { ...clampRect(r), preferredRect: r, maximized: false, prevRect: undefined });
return;
}
const { vw, top, bottom } = workArea();
diff --git a/frontend/slices/appshell/lib/types.ts b/frontend/slices/appshell/lib/types.ts
index bfb79838..974a3d1d 100644
--- a/frontend/slices/appshell/lib/types.ts
+++ b/frontend/slices/appshell/lib/types.ts
@@ -25,6 +25,8 @@ export type WindowState = {
maximized: boolean;
/** Saved rect for restore from maximize/snap. */
prevRect?: Rect;
+ /** User geometry, independent of temporary viewport constraints. */
+ preferredRect?: Rect;
/** The zone this window is snapped to. Kept so a shell switch (different
* chrome insets) can re-tile snapped/maximized windows into the new work
* area instead of leaving frozen geometry. Cleared on free move/resize. */
@@ -124,5 +126,5 @@ export type AppMenuItem =
* switch; the restore (hydrateBoot) also dedupes a multi-app window by payload. */
export type PersistedWindow = Pick<
WindowState,
- "id" | "app" | "title" | "x" | "y" | "w" | "h" | "minimized" | "maximized" | "pinned" | "spaceId" | "groupId" | "payload" | "snapZone" | "prevRect"
+ "id" | "app" | "title" | "x" | "y" | "w" | "h" | "minimized" | "maximized" | "pinned" | "spaceId" | "groupId" | "payload" | "snapZone" | "prevRect" | "preferredRect"
>;
diff --git a/frontend/slices/appshell/lib/window-url.test.ts b/frontend/slices/appshell/lib/window-url.test.ts
new file mode 100644
index 00000000..50453246
--- /dev/null
+++ b/frontend/slices/appshell/lib/window-url.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import type { AppDescriptor } from "./types";
+import { stateToUrl } from "./window-url";
+
+const app = { id: "external-tool", slug: "tool" } as AppDescriptor;
+describe("restored window URL ownership", () => {
+ it("defers a route rewrite until the connected app registry arrives", () => {
+ expect(stateToUrl([], app.id, undefined)).toBeNull();
+ expect(stateToUrl([app], app.id, undefined)).toBe("/tool");
+ });
+ it("keeps unavailable app routes for the explicit unavailable state", () => {
+ expect(stateToUrl([app], "not-authorized", null)).toBeNull();
+ expect(stateToUrl([app], null, null)).toBe("/");
+ });
+ it("preserves file paths and falls back to an app ID without a slug", () => {
+ expect(stateToUrl([app], app.id, { path: "///home/file.txt" })).toBe("/tool/home/file.txt");
+ expect(stateToUrl([{ ...app, slug: undefined }], app.id, { path: 1 })).toBe("/external-tool");
+ });
+});
diff --git a/frontend/slices/appshell/lib/window-url.ts b/frontend/slices/appshell/lib/window-url.ts
new file mode 100644
index 00000000..60229135
--- /dev/null
+++ b/frontend/slices/appshell/lib/window-url.ts
@@ -0,0 +1,11 @@
+import type { AppDescriptor } from "./types";
+
+/** null defers a rewrite while a restored app is absent from the async registry. */
+export function stateToUrl(apps: AppDescriptor[], appId: string | null, payload: unknown): string | null {
+ if (!appId) return "/";
+ const app = apps.find((entry) => entry.id === appId);
+ if (!app) return null;
+ const path = (payload as { path?: unknown } | null)?.path;
+ const suffix = typeof path === "string" && path ? "/" + path.replace(/^\/+/, "") : "";
+ return "/" + (app.slug ?? app.id) + suffix;
+}
diff --git a/frontend/slices/appshell/primitives/app-frame.tsx b/frontend/slices/appshell/primitives/app-frame.tsx
index 88df72de..b7418120 100644
--- a/frontend/slices/appshell/primitives/app-frame.tsx
+++ b/frontend/slices/appshell/primitives/app-frame.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
+import { layoutVariables, type LayoutMetrics } from "../design/layout";
import { useShellDesign } from "../design/use-shell-design";
// Standard app scaffold: optional header/toolbar row + a scrolling body that
@@ -16,6 +17,8 @@ export function AppFrame({
className,
bodyClassName,
safeArea = true,
+ layout,
+ padded = false,
}: {
header?: ReactNode;
toolbar?: ReactNode;
@@ -25,10 +28,12 @@ export function AppFrame({
bodyClassName?: string;
/** Pad the body for notch/home-bar (mobile fullscreen). Default on. */
safeArea?: boolean;
+ layout?: Partial<LayoutMetrics>;
+ padded?: boolean;
}) {
const design = useShellDesign();
return (
- <div data-slot="app-frame" data-shell-family={design.family} data-shell-density={design.density} className={cn("@container flex h-full min-h-0 flex-col", className)}>
+ <div data-slot="app-frame" style={layout && layoutVariables(layout)} data-shell-family={design.family} data-shell-density={design.density} className={cn("@container flex h-full min-h-0 flex-col", className)}>
{header && (
<div data-slot="app-frame-header" className="flex-none border-b border-border">{header}</div>
)}
@@ -39,7 +44,9 @@ export function AppFrame({
data-slot="app-frame-body"
className={cn(
"min-h-0 flex-1 overflow-x-hidden overflow-y-auto",
- safeArea && "[padding-bottom:var(--sai-bottom)]",
+ padded && "[padding:var(--feature-padding,1.25rem)]",
+ safeArea && "[padding-bottom:calc(var(--sai-bottom,0px)+var(--app-body-padding,0px))]",
+ padded && "[--app-body-padding:var(--feature-padding,1.25rem)]",
bodyClassName,
)}
>
diff --git a/frontend/slices/appshell/primitives/responsive-dialog-parts.tsx b/frontend/slices/appshell/primitives/responsive-dialog-parts.tsx
index ef43ab2f..0f6a8c34 100644
--- a/frontend/slices/appshell/primitives/responsive-dialog-parts.tsx
+++ b/frontend/slices/appshell/primitives/responsive-dialog-parts.tsx
@@ -38,20 +38,20 @@ export function ResponsiveDialogHeader({ className, children, ...props }: Respon
}
if (variant === "alert") {
return (
- <AlertDialogHeader className={cn(baseClasses, "gap-1.5 px-6 pb-4 pt-6", className)} {...props}>
+ <AlertDialogHeader className={cn(baseClasses, "gap-1.5 px-[var(--feature-padding,1.5rem)] pb-4 pt-[var(--feature-padding,1.5rem)]", className)} {...props}>
{children}
</AlertDialogHeader>
);
}
if (variant === "panel") {
return (
- <SheetHeader className={cn(baseClasses, "gap-1.5 px-6 pb-4 pt-6", className)} {...props}>
+ <SheetHeader className={cn(baseClasses, "gap-1.5 px-[var(--feature-padding,1.5rem)] pb-4 pt-[var(--feature-padding,1.5rem)]", className)} {...props}>
{children}
</SheetHeader>
);
}
return (
- <DialogHeader className={cn(baseClasses, "gap-1.5 px-6 pb-4 pt-6", className)} {...props}>
+ <DialogHeader className={cn(baseClasses, "gap-1.5 px-[var(--feature-padding,1.5rem)] pb-4 pt-[var(--feature-padding,1.5rem)]", className)} {...props}>
{children}
</DialogHeader>
);
@@ -90,7 +90,7 @@ export function ResponsiveDialogBody({ className, children, ...props }: Responsi
useResponsiveDialogContext("Body");
return (
<div
- className={cn("min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-5 py-4 sm:px-6", className)}
+ className={cn("min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-[var(--feature-padding,1.25rem)] py-[var(--feature-padding,1rem)]", className)}
{...props}
>
{children}
@@ -120,20 +120,20 @@ export function ResponsiveDialogFooter({ className, children, ...props }: Respon
}
if (variant === "alert") {
return (
- <AlertDialogFooter className={cn(baseClasses, "gap-2 px-6 pb-5 pt-4 sm:justify-end", className)} {...props}>
+ <AlertDialogFooter className={cn(baseClasses, "gap-2 px-[var(--feature-padding,1.5rem)] pb-[var(--feature-padding,1.25rem)] pt-4 sm:justify-end", className)} {...props}>
{children}
</AlertDialogFooter>
);
}
if (variant === "panel") {
return (
- <SheetFooter className={cn(baseClasses, "mt-0 flex-row justify-end gap-2 px-6 pb-5 pt-4", className)} {...props}>
+ <SheetFooter className={cn(baseClasses, "mt-0 flex-row justify-end gap-2 px-[var(--feature-padding,1.5rem)] pb-[var(--feature-padding,1.25rem)] pt-4", className)} {...props}>
{children}
</SheetFooter>
);
}
return (
- <DialogFooter className={cn(baseClasses, "gap-2 px-6 pb-5 pt-4 sm:justify-end", className)} {...props}>
+ <DialogFooter className={cn(baseClasses, "gap-2 px-[var(--feature-padding,1.5rem)] pb-[var(--feature-padding,1.25rem)] pt-4 sm:justify-end", className)} {...props}>
{children}
</DialogFooter>
);
diff --git a/frontend/slices/appshell/provider/app-shell.tsx b/frontend/slices/appshell/provider/app-shell.tsx
index f80166f2..e6b7ef27 100644
--- a/frontend/slices/appshell/provider/app-shell.tsx
+++ b/frontend/slices/appshell/provider/app-shell.tsx
@@ -50,8 +50,8 @@ export function AppShell({ manifest }: { manifest: ShellManifest }) {
.map((f) => f.provider)
.filter((p): p is ComponentType<{ children: ReactNode }> => Boolean(p));
const shellConfig = useMemo(
- () => ({ persistKey: manifest.persistKey ?? "appshell:layout" }),
- [manifest.persistKey],
+ () => ({ persistKey: manifest.persistKey ?? "appshell:layout", layout: manifest.layout }),
+ [manifest.persistKey, manifest.layout],
);
return (
diff --git a/frontend/slices/appshell/registry/shell-config.tsx b/frontend/slices/appshell/registry/shell-config.tsx
index 53abf3c0..20dc6b58 100644
--- a/frontend/slices/appshell/registry/shell-config.tsx
+++ b/frontend/slices/appshell/registry/shell-config.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { LayoutConfig } from "../design/layout";
import { createContext, useContext, type ReactNode } from "react";
// Non-brand runtime config the shell core needs (kept out of Brand so brand
@@ -7,6 +8,7 @@ import { createContext, useContext, type ReactNode } from "react";
// never hardcodes a consumer's localStorage key.
export type ShellConfig = {
persistKey: string;
+ layout?: LayoutConfig;
};
const ShellConfigContext = createContext<ShellConfig>({ persistKey: "appshell:layout" });
diff --git a/frontend/slices/appshell/registry/types.ts b/frontend/slices/appshell/registry/types.ts
index aa438a83..bef691c4 100644
--- a/frontend/slices/appshell/registry/types.ts
+++ b/frontend/slices/appshell/registry/types.ts
@@ -1,5 +1,6 @@
import type { ComponentType, ReactNode } from "react";
import type { AppDescriptor } from "../lib/types";
+import type { LayoutConfig } from "../design/layout";
import type { ShellCapabilities } from "./capabilities";
// Named regions a feature can mount into. The surfaces render <Slot region> at a
@@ -47,6 +48,7 @@ export type ShellManifest = {
persistKey?: string;
/** Consumer-injected capabilities (appearance/host) — keeps the shell generic. */
capabilities?: ShellCapabilities;
+ layout?: LayoutConfig;
};
/** Identity helper — gives a feature its type + a stable authoring shape. */
diff --git a/frontend/slices/appshell/runtime/use-url-sync.tsx b/frontend/slices/appshell/runtime/use-url-sync.tsx
index 92176e92..e7529592 100644
--- a/frontend/slices/appshell/runtime/use-url-sync.tsx
+++ b/frontend/slices/appshell/runtime/use-url-sync.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { openWindow, focusApp, shellStore } from "../lib/store";
import { useFocused, useWindow } from "../hooks/use-shell";
+import { stateToUrl } from "../lib/window-url";
import type { AppDescriptor } from "../lib/types";
// Maps the OS window model onto a single URL: the FOCUSED app (+ its launch
@@ -17,24 +18,12 @@ import type { AppDescriptor } from "../lib/types";
// ⌘/middle-click on the dock <Link>, back/forward) still loads/repaints normally.
//
// The two effects fire on DIFFERENT triggers and never on each other's:
-// • state → URL reacts to focus/payload, reads the latest pathname from a ref
+// • state → URL reacts to focus/payload and registry readiness, reading the latest pathname from a ref
// so OUR own address-bar rewrite doesn't re-trigger it.
// • URL → state reacts to the pathname (incl. popstate from back/forward),
// reads the focused app LIVE from the store (not a dep) so a focus change
// can't re-run it and fight the rewrite.
-function payloadPath(payload: unknown): string {
- const p = (payload as { path?: unknown } | null)?.path;
- return typeof p === "string" && p ? "/" + p.replace(/^\/+/, "") : "";
-}
-
-function stateToUrl(apps: AppDescriptor[], appId: string | null, payload: unknown): string {
- if (!appId) return "/";
- const app = apps.find((a) => a.id === appId);
- if (!app) return "/";
- return "/" + (app.slug ?? app.id) + payloadPath(payload);
-}
-
function urlToApp(
apps: AppDescriptor[],
pathname: string,
@@ -80,6 +69,7 @@ export function UrlSync({ apps }: { apps: AppDescriptor[] }) {
// URL→state opens its window.
useEffect(() => {
const target = stateToUrl(apps, visibleApp, payload);
+ if (target === null) return;
if (!booted.current || target === pathnameRef.current) {
booted.current = true;
prevApp.current = visibleApp;
@@ -94,8 +84,7 @@ export function UrlSync({ apps }: { apps: AppDescriptor[] }) {
}
pathnameRef.current = target;
prevApp.current = visibleApp;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [visibleApp, payload]);
+ }, [visibleApp, payload, apps]);
// URL → state: open/focus the app named in the URL (deep link + back/forward).
// Reads the focused app live so a focus change can't re-enter this effect.
diff --git a/frontend/slices/integrations/app.tsx b/frontend/slices/integrations/app.tsx
index 2d248730..f40f15de 100644
--- a/frontend/slices/integrations/app.tsx
+++ b/frontend/slices/integrations/app.tsx
@@ -18,6 +18,12 @@ export default function IntegrationsApp() {
useEffect(() => {
const target = frame.current;
if (!target) return;
+ const onReady = (event: MessageEvent) => {
+ if (event.source !== target.contentWindow || event.origin !== window.location.origin || event.data?.type !== "mso:integrations-ready") return;
+ syncIntegrationFrameTokens(target);
+ setStatus("ready");
+ };
+ window.addEventListener("message", onReady);
target.src = managerLocation(window.location.search, window.location.hash);
if (window.location.hash) window.history.replaceState(window.history.state, "", window.location.pathname + window.location.search);
const timer = window.setTimeout(() => setStatus(current => current === "loading" ? "error" : current), 15000);
@@ -33,6 +39,7 @@ export default function IntegrationsApp() {
scheme.addEventListener("change", sync);
sync();
return () => {
+ window.removeEventListener("message", onReady);
window.clearTimeout(timer);
window.cancelAnimationFrame(animation);
observer.disconnect();
@@ -49,7 +56,7 @@ export default function IntegrationsApp() {
</div>}
<ComposioSessionPanel />
<iframe ref={frame} title="MSO native Integrations manager" className="min-h-0 w-full flex-1 border-0"
- referrerPolicy="no-referrer" onLoad={() => { if (frame.current?.getAttribute("src")) { syncIntegrationFrameTokens(frame.current); setStatus("ready"); } }}
+ referrerPolicy="no-referrer" onLoad={() => { if (frame.current?.contentDocument?.querySelector(".integration.manager")) { syncIntegrationFrameTokens(frame.current); setStatus("ready"); } }}
onError={() => setStatus("error")} />
</section>
);
diff --git a/frontend/slices/integrations/composio-session-panel.tsx b/frontend/slices/integrations/composio-session-panel.tsx
index 5e761082..94ffb0d1 100644
--- a/frontend/slices/integrations/composio-session-panel.tsx
+++ b/frontend/slices/integrations/composio-session-panel.tsx
@@ -86,7 +86,7 @@ export function ComposioSessionPanel() {
if (kind === undefined) return null;
if (kind === "connect") {
return (
- <section className="border-b p-3" aria-label="Composio Connect">
+ <details className="shrink-0 border-b p-3" aria-label="Composio Connect"><summary className="cursor-pointer text-sm">Composio Connect tools</summary>
<div className="flex flex-wrap items-center gap-3">
<p className="text-sm">Composio Connect</p>
<Button variant="secondary" disabled={busy} onClick={() => void loadTools()}>List tools</Button>
@@ -98,13 +98,13 @@ export function ComposioSessionPanel() {
<ul className="mt-2 text-sm">{tools.map(tool => <li key={tool.name}>{tool.name}</li>)}</ul>
)}
{status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
- </section>
+ </details>
);
}
if (kind === null) return null;
return (
- <section className="border-b p-3" aria-label="Composio agent session">
+ <details className="shrink-0 border-b p-3" aria-label="Composio agent session"><summary className="cursor-pointer text-sm">Composio agent session</summary>
<div className="flex flex-wrap items-center gap-3">
<Button variant="secondary" disabled={busy} onClick={() => void create(false)}>Create agent session</Button>
{mcpUrl && <Button variant="ghost" disabled={busy} onClick={() => void create(true)}>Refresh session</Button>}
@@ -119,6 +119,6 @@ export function ComposioSessionPanel() {
</label>
)}
{status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
- </section>
+ </details>
);
}
diff --git a/frontend/slices/integrations/frame-theme.ts b/frontend/slices/integrations/frame-theme.ts
index fce1573c..100fac9b 100644
--- a/frontend/slices/integrations/frame-theme.ts
+++ b/frontend/slices/integrations/frame-theme.ts
@@ -6,6 +6,11 @@
* Settings-like content follows the active shell preset/accent dynamically.
*/
export const INTEGRATION_FRAME_TOKEN_MAP = [
+ ["--feature-padding", "--feature-padding"],
+ ["--feature-gap", "--feature-gap"],
+ ["--feature-sidebar-width", "--feature-sidebar-width"],
+ ["--ui-control-height", "--ui-control-height"],
+ ["--ui-control-padding", "--ui-control-padding"],
["--text", "--text"],
["--text-dim", "--text-dim"],
["--text-faint", "--text-faint"],
@@ -61,6 +66,7 @@ export function syncIntegrationFrameTokens(frame: HTMLIFrameElement): void {
const values = integrationFrameTokens((name) => source.getPropertyValue(name));
for (const [name, value] of Object.entries(values)) target.style.setProperty(name, value);
if (source.fontSize) target.style.fontSize = source.fontSize;
+ target.dataset.shell = document.getElementById("main-content")?.dataset.shell ?? "macos";
const theme = document.documentElement.dataset.theme;
if (theme === "light" || theme === "dark") target.dataset.theme = theme;
else target.removeAttribute("data-theme");
diff --git a/frontend/slices/n8n/app.tsx b/frontend/slices/n8n/app.tsx
index 831ec0ab..8436e824 100644
--- a/frontend/slices/n8n/app.tsx
+++ b/frontend/slices/n8n/app.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Boxes, RefreshCw } from "lucide-react";
import type { AppProps } from "@/features/appshell";
import { AppFrame, openWindow } from "@/features/appshell";
@@ -16,21 +16,28 @@ export default function N8nApp(_: AppProps) {
const [loading, setLoading] = useState(true);
const [message, setMessage] = useState("");
+ const request = useRef<AbortController | null>(null);
const load = useCallback(async () => {
+ request.current?.abort();
+ const controller = new AbortController();
+ request.current = controller;
try {
- const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store" });
+ const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store", signal: controller.signal });
+ if (controller.signal.aborted) return;
if (!response.ok) {
setApps([]);
setMessage(response.status === 403 ? "Owner access is required to view the reviewed n8n surface." : "Could not load the n8n surface.");
return;
}
const data = await response.json() as EmbedResponse;
+ if (controller.signal.aborted) return;
setApps(Array.isArray(data.apps) ? data.apps : []);
setMessage("");
} catch (error) {
+ if (controller.signal.aborted) return;
setMessage(error instanceof Error ? error.message : "Could not load the n8n surface.");
} finally {
- setLoading(false);
+ if (!controller.signal.aborted) setLoading(false);
}
}, []);
@@ -38,6 +45,7 @@ export default function N8nApp(_: AppProps) {
const frame = requestAnimationFrame(() => { void load(); });
window.addEventListener("focus", load);
return () => {
+ request.current?.abort();
cancelAnimationFrame(frame);
window.removeEventListener("focus", load);
};
@@ -59,7 +67,7 @@ export default function N8nApp(_: AppProps) {
return <div data-slot="n8n-feature" className="@container h-full min-h-0 min-w-0">
<AppFrame safeArea={false} className="h-full min-w-0" toolbar={toolbar}>
- {n8n ? <N8nEmbedPanel app={n8n}/> : <div className="grid h-full min-h-0 place-items-center overflow-y-auto p-6">
+ {loading && !n8n ? <div role="status" className="grid h-full place-items-center p-[var(--feature-padding,1.5rem)] text-sm text-muted-foreground">Loading n8n workspace…</div> : n8n ? <N8nEmbedPanel app={n8n}/> : <div className="grid h-full min-h-0 place-items-center overflow-y-auto p-6">
<div className="w-full max-w-2xl rounded-2xl border bg-card p-5 shadow-sm">
<div className="flex items-start gap-3">
<div className="grid size-10 shrink-0 place-items-center rounded-xl border bg-muted/40"><Boxes className="size-5 text-muted-foreground"/></div>
diff --git a/frontend/slices/system-monitor/app.tsx b/frontend/slices/system-monitor/app.tsx
index 34e8829e..d287699a 100644
--- a/frontend/slices/system-monitor/app.tsx
+++ b/frontend/slices/system-monitor/app.tsx
@@ -64,14 +64,14 @@ export default function SystemMonitor() {
</div>
</header>
}>
- {tab === "overview" ? <Overview stats={stats} procs={procs} cpuSeries={cpuSeries} netSeries={netSeries} gpu={gpu} error={error} refresh={refresh} /> : null}
+ {tab === "overview" ? <Overview stats={stats} procs={procs} cpuSeries={cpuSeries} netSeries={netSeries} gpu={api.mode === "mock" ? gpu : undefined} error={error} refresh={refresh} /> : null}
{tab === "services" ? <ServicesPanel /> : null}
{tab === "updates" ? <PackageUpdatesPanel /> : null}
</AppFrame>
);
}
-function Overview({ stats, procs, cpuSeries, netSeries, gpu, error, refresh }: ReturnType<typeof useStatsHistory>) {
+function Overview({ stats, procs, cpuSeries, netSeries, gpu, error, refresh }: Omit<ReturnType<typeof useStatsHistory>, "gpu"> & { gpu?: number }) {
if (!stats && error) return <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center"><AlertCircle className="size-6 text-destructive" /><p className="max-w-xs text-xs text-muted-foreground">{error}</p><Button variant="outline" size="sm" onClick={refresh}><RotateCw className="size-3.5" /> Retry</Button></div>;
if (!stats) return <div className="flex h-full items-center justify-center gap-2 text-xs text-[color:var(--text-faint)]"><Loader2 className="size-4 animate-spin" /> Reading host telemetry…</div>;
const lastNet = netSeries[netSeries.length - 1] ?? 0;
diff --git a/frontend/slices/system-monitor/components/gauge-grid.tsx b/frontend/slices/system-monitor/components/gauge-grid.tsx
index 2b13e261..a8c1501e 100644
--- a/frontend/slices/system-monitor/components/gauge-grid.tsx
+++ b/frontend/slices/system-monitor/components/gauge-grid.tsx
@@ -4,7 +4,7 @@ import { fmtGiBPair } from "../lib/format";
// The four headline gauges. CPU/Memory/Disk are real (from sys.stats); GPU is a
// local mock walk since it isn't part of the SysStats contract.
-export function GaugeGrid({ stats, gpu }: { stats: SysStats; gpu: number }) {
+export function GaugeGrid({ stats, gpu }: { stats: SysStats; gpu?: number }) {
const memPct = (stats.mem.used / stats.mem.total) * 100;
const diskPct = (stats.disk.used / stats.disk.total) * 100;
return (
@@ -27,12 +27,12 @@ export function GaugeGrid({ stats, gpu }: { stats: SysStats; gpu: number }) {
sub={fmtGiBPair(stats.disk.used, stats.disk.total)}
accent="--mon-disk"
/>
- <CircularGauge
- label="GPU (mock)"
+ {gpu !== undefined && <CircularGauge
+ label="GPU (demo)"
pct={gpu}
sub="render accel"
accent="--mon-gpu"
- />
+ />}
</div>
);
}
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index dff22a5b..fb4c4fdc 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -1,12 +1,14 @@
"use client";
+import { useUnsavedWorkflow } from "./lib/use-unsaved-workflow";
import { pruneGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Activity, Copy, Download, PanelLeft, PanelRight, Play, RefreshCw, Save, Sparkles, Trash2, Workflow } from "lucide-react";
import type { AppProps, ToolbarItem } from "@/features/appshell";
import type { SessionGraphView } from "@/lib/contracts/session-monitor";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
-import { AppFrame, ResponsiveDialog, ResponsiveToolbar, openWindow, saveAs, useContainer, useResponsive } from "@/features/appshell";
+import { AppFrame, ResponsiveDialog, ResponsiveToolbar, openWindow, saveAs, useContainer, useResponsive, useFeatureState } from "@/features/appshell";
+import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { WorkflowCanvas } from "./components/workflow-canvas";
@@ -29,20 +31,22 @@ export default function WorkflowsApp(props: AppProps) {
const { isMobile } = useResponsive();
const [appRef, pane] = useContainer<HTMLDivElement>();
const overlayPane = isMobile || pane !== "lg";
- const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null), [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
- const [busy, setBusy] = useState(false), [dirty, setDirty] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<WorkflowPanel>("inspector"), [search, setSearch] = useState("");
+ const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useFeatureState<WorkflowGraph | null>(props.winId, "workflow-graph", null), [selected, setSelected] = useFeatureState<string | null>(props.winId, "workflow-selection", null), [run, setRun] = useFeatureState<WorkflowGraphRun | null>(props.winId, "workflow-run", null);
+ const [busy, setBusy] = useState(false), [dirty, setDirty] = useFeatureState(props.winId, "workflow-dirty", false), [message, setMessage] = useState(""), [panel, setPanel] = useFeatureState<WorkflowPanel>(props.winId, "workflow-panel", "inspector"), [search, setSearch] = useFeatureState(props.winId, "workflow-search", "");
const [nodeCreator, setNodeCreator] = useState<{ open: boolean; sourceId?: string; sourceHandle?: string }>({ open: false });
const [libraryOpen, setLibraryOpen] = useState(false), [detailsOpen, setDetailsOpen] = useState(false), [showLibrary, setShowLibrary] = useState(true), [showDetails, setShowDetails] = useState(true);
- const [libraryMode, setLibraryMode] = useState<LibraryMode>(() => payloadSessionId(props.payload) ? "sessions" : "automations");
- const [sessionView, setSessionView] = useState<SessionGraphView | null>(null), [sessionSelected, setSessionSelected] = useState<string | null>(null);
+ const [libraryMode, setLibraryMode] = useFeatureState<LibraryMode>(props.winId, "workflow-library", () => payloadSessionId(props.payload) ? "sessions" : "automations");
+ const [sessionView, setSessionView] = useFeatureState<SessionGraphView | null>(props.winId, "workflow-session", null), [sessionSelected, setSessionSelected] = useFeatureState<string | null>(props.winId, "workflow-session-selection", null);
+ const confirmDiscard = useUnsavedWorkflow(dirty, props.winId);
const node = useMemo(() => graph?.nodes.find((item) => item.id === selected) ?? null, [graph, selected]);
const sessionNode = useMemo(() => sessionView?.graph.nodes.find((item) => item.id === sessionSelected) ?? null, [sessionSelected, sessionView]);
const runStates = useMemo(() => new Map(run?.nodes.map((item) => [item.id, item.state]) ?? []), [run]);
const runEdgeStates = useMemo(() => new Map(run?.edges?.map((item) => [item.id, item.state]) ?? []), [run]);
+ const preserveGraphAtBoot = useRef(graph !== null);
const load = async (selectId?: string, force=false) => { const list = await listGraphs(force); setGraphs(list); const id = selectId ?? graph?.id ?? list[0]?.id; if (id) { setGraph(await getGraph(id, force)); setDirty(false); } else { setGraph(null); setDirty(false); } };
- useEffect(() => { let cancelled = false; void listGraphs().then(async (list) => { if (cancelled) return; setGraphs(list); if (list[0]) { const first = await getGraph(list[0].id); if (!cancelled) setGraph(first); } }).catch((error: unknown) => { if (!cancelled) setMessage(error instanceof Error ? error.message : "Could not load workflows"); }); return () => { cancelled = true; }; }, []);
- useEffect(() => { if (!run || run.state !== "running") return; const timer = setInterval(() => { void runStatus(run.id).then(setRun).catch(() => undefined); }, 1600); return () => clearInterval(timer); }, [run]);
+ useEffect(() => { let cancelled = false; void listGraphs().then(async (list) => { if (cancelled) return; setGraphs(list); if (list[0] && !preserveGraphAtBoot.current) { const first = await getGraph(list[0].id); if (!cancelled) setGraph(first); } }).catch((error: unknown) => { if (!cancelled) setMessage(error instanceof Error ? error.message : "Could not load workflows"); }); return () => { cancelled = true; }; }, [setGraph]);
+ useEffect(() => { if (!run || run.state !== "running") return; const timer = setInterval(() => { void runStatus(run.id).then(setRun).catch(() => undefined); }, 1600); return () => clearInterval(timer); }, [run, setRun]);
useEffect(() => {
if (overlayPane) return;
const frame = requestAnimationFrame(() => { setLibraryOpen(false); setDetailsOpen(false); });
@@ -60,17 +64,17 @@ export default function WorkflowsApp(props: AppProps) {
let alive = true;
void getSessionGraph(id).then((next) => { if (!alive) return; setLibraryMode("sessions"); setMessage(""); setSessionView(next); setSessionSelected("session-root"); }).catch((error: unknown) => { if (alive) setMessage(error instanceof Error ? error.message : "Could not load session"); });
return () => { alive = false; };
- }, [props.payload]);
+ }, [props.payload, setLibraryMode, setSessionSelected, setSessionView]);
const wrap = async (fn: () => Promise<void>) => { setBusy(true); setMessage(""); try { await fn(); } catch (error) { setMessage(error instanceof Error ? error.message : "Action failed"); } finally { setBusy(false); } };
const mutate = (next: WorkflowGraph) => { setGraph(next); setDirty(true); };
- const selectGraph = async (id: string) => { setLibraryMode("automations"); setGraph(await getGraph(id)); setSelected(null); setRun(null); setDirty(false); setPanel("inspector"); setLibraryOpen(false); };
- const selectSession = async (id: string) => { const next = await getSessionGraph(id); setLibraryMode("sessions"); setSessionView(next); setSessionSelected("session-root"); setLibraryOpen(false); setDetailsOpen(false); };
+ const selectGraph = async (id: string) => { if (!confirmDiscard()) return; setLibraryMode("automations"); setGraph(await getGraph(id)); setSelected(null); setRun(null); setDirty(false); setPanel("inspector"); setLibraryOpen(false); };
+ const selectSession = async (id: string) => { if (!confirmDiscard()) return; const next = await getSessionGraph(id); setLibraryMode("sessions"); setSessionView(next); setSessionSelected("session-root"); setGraph(null); setDirty(false); setLibraryOpen(false); setDetailsOpen(false); };
const refreshSession = async () => { if (!sessionView) return; const next = await getSessionGraph(sessionView.session.id); setSessionView(next); if (sessionSelected && !next.graph.nodes.some((item) => item.id === sessionSelected)) setSessionSelected("session-root"); };
- const createBlank = () => wrap(async () => { const next = await createGraph(starterGraph()); setLibraryMode("automations"); await load(next.id); setSelected("manual"); setLibraryOpen(false); });
- const createTemplate = (id: string) => wrap(async () => { const next = await createFromTemplate(id); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
- const createAI = (definition: WorkflowDefinition) => wrap(async () => { const next = await createGraph(definition); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
- const createImported = (definition: WorkflowDefinition) => wrap(async () => { const next = await createGraph({ ...definition, metadata: { ...definition.metadata, provenance: "import" } }); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const createBlank = () => wrap(async () => { if (!confirmDiscard()) return; const next = await createGraph(starterGraph()); setLibraryMode("automations"); await load(next.id); setSelected("manual"); setLibraryOpen(false); });
+ const createTemplate = (id: string) => wrap(async () => { if (!confirmDiscard()) return; const next = await createFromTemplate(id); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const createAI = (definition: WorkflowDefinition) => wrap(async () => { if (!confirmDiscard()) return; const next = await createGraph(definition); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const createImported = (definition: WorkflowDefinition) => wrap(async () => { if (!confirmDiscard()) return; const next = await createGraph({ ...definition, metadata: { ...definition.metadata, provenance: "import" } }); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
const saveCurrent = async () => { if (!graph) throw new Error("No workflow selected"); if (!dirty) return graph; const next = await updateGraph(graph); setGraph(next); setDirty(false); setGraphs(await listGraphs()); return next; };
const save = () => graph && wrap(async () => { await saveCurrent(); setMessage("Saved"); });
const duplicate = () => graph && wrap(async () => { const next = await cloneGraph(graph.id); await load(next.id); });
@@ -122,7 +126,7 @@ export default function WorkflowsApp(props: AppProps) {
const details = libraryMode === "sessions" && sessionView ? <WorkflowSessionDetails view={sessionView} node={sessionNode} onOpenTerminal={openSessionTerminal} onOpenCode={openSessionCode} onSaveDraft={saveSessionDraft} savingDraft={busy}/> : graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={(next) => next === "optimizer" && dirty ? void openOptimizer() : setPanel(next)} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }} onOptimizerCloned={(next) => { setGraph(next); setSelected(null); setRun(null); setDirty(false); setPanel("optimizer"); void listGraphs(true).then(setGraphs); }}/> : null;
const toolbarItems: ToolbarItem[] = [
{ id: "library", label: "Workflow library", icon: PanelLeft, onClick: toggleLibrary, primary: true },
- { id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void wrap(async () => { if (libraryMode === "sessions") await refreshSession(); else await load(undefined, true); }), disabled: busy },
+ { id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void wrap(async () => { if (libraryMode === "sessions") await refreshSession(); else if (confirmDiscard()) await load(undefined, true); }), disabled: busy },
...(libraryMode === "automations" && graph ? [
{ id: "duplicate", label: "Duplicate", icon: Copy, onClick: () => void duplicate(), disabled: busy },
{ id: "export", label: "Export", icon: Download, onClick: exportCurrent, disabled: busy },
@@ -143,7 +147,7 @@ export default function WorkflowsApp(props: AppProps) {
<div className={`grid h-full min-h-0 min-w-0 ${showLibraryPanel ? "grid-cols-[300px_minmax(0,1fr)] @min-[1200px]:grid-cols-[340px_minmax(0,1fr)]" : "grid-cols-1"}`}>
{showLibraryPanel ? <aside className="min-h-0 min-w-0 border-r">{library}</aside> : null}
<main className="flex min-h-0 min-w-0 overflow-hidden">
- {libraryMode === "sources" ? <div className="flex h-full flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">Owner sources are listed in the library. Open an own workflow or copy a foreign source as a disabled draft for review.</div> : libraryMode === "automations" ? graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] text-muted-foreground"><span>Status</span><select aria-label="Workflow status" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs text-foreground" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select></label><WorkflowNodePalette onAdd={addNode} open={nodeCreator.open} context={nodeCreator.sourceId ? "after-node" : "all"} onOpenChange={(open) => setNodeCreator(open ? { open: true } : { open: false })}/>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} onCustomNodes={(customNodes) => mutate({ ...graph, metadata: { ...graph.metadata, customNodes } })} onMoveMany={(nodes) => mutate({ ...graph, nodes })} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onQuickAdd={(sourceId, sourceHandle) => setNodeCreator({ open: true, sourceId, ...(sourceHandle ? { sourceHandle } : {}) })} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Create an automation, or open Sources to discover workflows saved by MCP and other browser identities.</div>
+ {libraryMode === "sources" ? <div className="flex h-full flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">Owner sources are listed in the library. Open an own workflow or copy a foreign source as a disabled draft for review.</div> : libraryMode === "automations" ? graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] text-muted-foreground"><span>Status</span><select aria-label="Workflow status" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs text-foreground" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select></label><WorkflowNodePalette onAdd={addNode} open={nodeCreator.open} context={nodeCreator.sourceId ? "after-node" : "all"} onOpenChange={(open) => setNodeCreator(open ? { open: true } : { open: false })}/>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} onCustomNodes={(customNodes) => mutate({ ...graph, metadata: { ...graph.metadata, customNodes } })} onMoveMany={(nodes) => mutate({ ...graph, nodes })} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onQuickAdd={(sourceId, sourceHandle) => setNodeCreator({ open: true, sourceId, ...(sourceHandle ? { sourceHandle } : {}) })} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground"><div className="grid justify-items-center gap-[var(--feature-gap,0.75rem)]"><p>Create an automation or discover saved workflows in Sources.</p><Button variant="secondary" onClick={() => { setLibraryMode("sources"); setShowLibrary(true); setLibraryOpen(overlayPane); }}>View sources</Button></div></div>
: sessionView ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 shrink-0 items-center gap-2 border-b px-3 text-[11px] text-muted-foreground [@media(max-height:520px)]:hidden"><span className="font-medium text-foreground">{sessionView.session.label}</span><span>read-only</span><span>·</span><span>{sessionView.steps.length} steps</span><span>·</span><span>{sessionView.shownEvents}/{sessionView.totalEvents} actions</span>{message ? <span className="ml-auto truncate">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={sessionView.graph.revision} graph={sessionView.graph} selectedId={sessionSelected} onSelect={chooseSessionNode} onConnect={() => undefined} onMove={() => undefined} readOnly/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Select a session to inspect its semantic execution flow.</div>}
{showDetailsPanel ? <aside className="w-[320px] shrink-0 border-l @min-[1200px]:w-[360px]">{details}</aside> : null}
</main>
diff --git a/frontend/slices/workflows/components/workflow-library.tsx b/frontend/slices/workflows/components/workflow-library.tsx
index 9a91a133..58f353cf 100644
--- a/frontend/slices/workflows/components/workflow-library.tsx
+++ b/frontend/slices/workflows/components/workflow-library.tsx
@@ -35,7 +35,7 @@ export function WorkflowLibrary({ graphs, activeId, search, onSearch, onSelect,
</div>
</div>
<ScrollArea className="min-h-0 flex-1"><div className="space-y-2 p-2.5">
- {filtered.length === 0 ? <div className="grid min-h-32 place-items-center rounded-xl border border-dashed p-4 text-center text-xs text-muted-foreground">No workflows match this filter.</div> : null}
+ {filtered.length === 0 ? <div className="grid min-h-32 place-items-center rounded-xl border border-dashed p-4 text-center text-xs text-muted-foreground">{graphs.length ? <div><p>No workflows match this filter.</p><Button variant="ghost" size="sm" onClick={() => onSearch("")}>Clear filters</Button></div> : <p>No automations yet. Use New workflow to create one.</p>}</div> : null}
{filtered.map((graph) => <div key={graph.id} className={`overflow-hidden rounded-xl border text-xs shadow-sm transition ${activeId === graph.id ? "border-foreground/20 bg-accent/75" : "bg-card hover:bg-accent/35"}`}>
<button type="button" onClick={() => onSelect(graph.id)} className="w-full p-3 text-left" aria-pressed={activeId === graph.id}>
<div className="flex items-start gap-2.5">
diff --git a/frontend/slices/workflows/lib/use-unsaved-workflow.ts b/frontend/slices/workflows/lib/use-unsaved-workflow.ts
new file mode 100644
index 00000000..e7cc5093
--- /dev/null
+++ b/frontend/slices/workflows/lib/use-unsaved-workflow.ts
@@ -0,0 +1,18 @@
+"use client";
+
+import { useCallback, useEffect } from "react";
+import { setCloseGuard } from "@/features/appshell";
+
+export function useUnsavedWorkflow(dirty: boolean, winId?: string) {
+ const confirmDiscard = useCallback(() => !dirty || window.confirm("Discard unsaved workflow changes?"), [dirty]);
+ useEffect(() => {
+ if (winId) setCloseGuard(winId, dirty ? confirmDiscard : null);
+ const beforeUnload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ""; };
+ if (dirty) window.addEventListener("beforeunload", beforeUnload);
+ return () => {
+ if (winId) setCloseGuard(winId, null);
+ window.removeEventListener("beforeunload", beforeUnload);
+ };
+ }, [dirty, winId, confirmDiscard]);
+ return confirmDiscard;
+}
diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.ts
index 68ef1e32..7180fe80 100644
--- a/lib/infra/connection-ui-layout.test.ts
+++ b/lib/infra/connection-ui-layout.test.ts
@@ -14,7 +14,7 @@ it("uses the Settings master/detail navigation contract", () => {
expect(CONNECTION_MANAGER_SCRIPT).toContain('["variables","Variables",showVariables]');
expect(CONNECTION_MANAGER_SCRIPT).toContain('["transfer","Transfer & backup",showTransfer]');
expect(CONNECTION_MANAGER_SCRIPT).toContain('["project-mcp","Add project MCP",showProjectMcp]');
- expect(CONNECTION_MANAGER_STYLE).toContain('grid-template-columns:var(--settings-sidebar-width) minmax(0,1fr)');
+ expect(CONNECTION_MANAGER_STYLE).toContain('grid-template-columns:var(--feature-sidebar-width,var(--settings-sidebar-width)) minmax(0,1fr)');
expect(CONNECTION_MANAGER_STYLE).toContain('width:min(100%,var(--settings-content-width))');
expect(CONNECTION_MANAGER_STYLE).toContain('@container integration (max-width:37.5rem)');
expect(CONNECTION_MANAGER_STYLE).toContain('integration-sidebar-toggle');
@@ -128,9 +128,13 @@ it("supports bidirectional sidebar toggle, panel focus, inert content trap, and
expect(CONNECTION_MANAGER_SCRIPT).toContain('if(width>37.5*rem)');
expect(CONNECTION_MANAGER_SCRIPT).toContain('sidebarToggle.setAttribute("aria-expanded","false")');
- // 5. Short iframe responsiveness: header flex:none with max-height, nav min-height
- expect(CONNECTION_MANAGER_STYLE).toContain('.integration .integration-sidebar-header{display:grid;flex:none;max-height:calc(var(--control-size) * 4);overflow-y:auto;');
- expect(CONNECTION_MANAGER_STYLE).toContain('.integration .integration-settings-nav{min-height:calc(var(--control-size) * 2);flex:1;overflow-y:auto;');
+ // 5. One sidebar scroll keeps the owner picker reachable on short panes.
+ expect(CONNECTION_MANAGER_STYLE).toContain('.integration .integration-sidebar-header{display:grid;flex:none;');
+ expect(CONNECTION_MANAGER_STYLE).toContain('.integration .integration-settings-nav{min-height:calc(var(--control-size) * 2);flex:1 0 auto;');
+
+ // Layout width excludes window-entry transforms, matching CSS container queries.
+ expect(CONNECTION_MANAGER_SCRIPT).toContain("root.clientWidth<=37.5");
+ expect(CONNECTION_MANAGER_SCRIPT).not.toContain("root.getBoundingClientRect().width");
// 6. Search filters all nav items, including Manage utilities
expect(CONNECTION_MANAGER_SCRIPT).toContain('navButtons.push({mode,provider:null,button:item,label})');
diff --git a/lib/infra/connection-ui-style.ts b/lib/infra/connection-ui-style.ts
index c3b10959..8ff05993 100644
--- a/lib/infra/connection-ui-style.ts
+++ b/lib/infra/connection-ui-style.ts
@@ -29,7 +29,7 @@ export const CONNECTION_MANAGER_STYLE = String.raw`
.integration .connection-state{display:inline-block;max-width:100%;font-size:var(--type-caption);line-height:var(--line-body);border:var(--stroke) solid var(--border);border-radius:var(--radius-pill);padding:var(--space-1) var(--space-2);overflow-wrap:anywhere}.integration .connection-state[data-ready=true]{color:var(--success-text);background:var(--settings-success-fill)}
.integration .identity-tags{display:flex;flex-wrap:wrap;gap:var(--space-2);margin:var(--space-3) 0;color:var(--muted-foreground);font-size:var(--type-caption)}.integration .identity-tags span{display:inline-block;max-width:100%;border-radius:var(--radius-pill);background:var(--muted);padding:var(--space-1) var(--space-2);overflow-wrap:anywhere}
.integration .identity-secret{display:flex;flex-wrap:wrap;align-items:center;gap:var(--space-2);min-width:0;max-width:100%}.integration .identity-secret-value{display:inline-block;max-width:100%;min-width:0;padding:var(--space-1) var(--space-2);font:var(--type-small)/var(--line-body) var(--font-mono);background:var(--secondary);color:var(--foreground);border:var(--stroke) solid var(--border);border-radius:var(--radius-control);overflow-wrap:anywhere;word-break:break-word}.integration .identity-secret-toggle{min-height:var(--control-size);min-width:var(--control-size)}.integration .identity-secret-copy{min-height:var(--control-size);min-width:var(--control-size)}
-.integration .identity-credential-status{display:grid;margin:var(--space-3) calc(var(--space-4) * -1) 0;font-size:var(--type-small);border-top:var(--stroke) solid var(--border)}.integration .identity-credential-status>div{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:var(--space-2);min-height:var(--control-size);padding:var(--space-2) var(--space-4);border-bottom:var(--stroke) solid var(--border)}.integration .identity-credential-status>div:last-child{border-bottom:0}.integration .credential-field-state{font-size:var(--type-caption);color:var(--destructive-text)}.integration .credential-field-state[data-stored=true]{color:var(--success-text)}
+.integration .identity-credential-status{display:grid;margin:var(--space-3) calc(var(--space-4) * -1) 0;font-size:var(--type-small);border-top:var(--stroke) solid var(--border)}.integration .identity-credential-status>div{display:grid;grid-template-columns:minmax(0,1fr) auto auto auto;align-items:center;gap:var(--space-2);min-height:var(--control-size);padding:var(--space-2) var(--space-4);border-bottom:var(--stroke) solid var(--border)}.integration .identity-credential-status>div:last-child{border-bottom:0}.integration .credential-field-state{font-size:var(--type-caption);color:var(--destructive-text)}.integration .credential-field-state[data-stored=true]{color:var(--success-text)}
.integration .identity-fields{display:grid;grid-template-columns:1fr 1fr;gap:var(--space-4);margin:var(--space-4) 0}.integration .identity-fields label{min-width:0}.integration .identity-fields input,.integration .identity-fields select{margin-top:var(--space-2)}
.integration .identity-feedback{min-height:var(--control-size);margin:var(--space-3) 0;color:var(--muted-foreground);overflow-wrap:anywhere}.integration .identity-path{font:var(--type-caption) var(--font-mono);overflow-wrap:anywhere;margin:var(--space-3) 0 var(--space-4);color:var(--muted-foreground)}
.integration .identity-check{display:flex;align-items:center;gap:var(--space-2);min-height:var(--control-size);cursor:pointer;font-weight:var(--weight-regular)}.integration .identity-check input{width:var(--icon-size);height:var(--icon-size);flex:none;margin:0;accent-color:var(--primary)}
@@ -38,23 +38,24 @@ export const CONNECTION_MANAGER_STYLE = String.raw`
.integration .owner-picker{position:relative;min-width:0;width:100%}.integration .identity-picker-label{display:block;margin-bottom:var(--space-2);font-size:var(--type-caption);font-weight:var(--weight-strong);color:var(--muted-foreground)}.integration .owner-picker-trigger{display:flex;align-items:center;width:100%;justify-content:space-between;text-align:left;background:var(--secondary);border-color:var(--input)}
.integration .owner-picker-popup{position:absolute;z-index:var(--settings-layer-popover);top:calc(100% + var(--space-1));left:0;right:0;max-height:var(--settings-popover-max-height);overflow:auto;padding:var(--space-2);background:var(--card);border:var(--stroke) solid var(--border);border-radius:var(--radius-panel);box-shadow:var(--shadow-pop)}.integration .owner-picker-option{display:flex;width:100%;text-align:left;background:transparent;border-color:transparent}.integration .owner-picker-option:hover,.integration .owner-picker-option:focus-visible{background:var(--hover)}.integration .owner-picker-option[aria-selected=true]{background:var(--settings-selected);color:var(--settings-selected-text);font-weight:var(--weight-strong)}
.surface>.body.integration{margin:0!important;max-width:none!important;width:100%!important;padding:0!important}
-.integration.manager{position:relative;max-width:none;width:100%;height:100%;min-height:100%;overflow:hidden;background:var(--settings-canvas)}
-.integration .integration-settings-shell{display:grid;grid-template-columns:var(--settings-sidebar-width) minmax(0,1fr);height:100%;min-height:0;background:var(--settings-canvas)}
-.integration .integration-settings-sidebar{display:flex;min-height:0;flex-direction:column;border-right:var(--stroke) solid var(--border);background:var(--settings-sidebar);overflow:hidden;color:var(--sidebar-foreground)}
-.integration .integration-sidebar-header{display:grid;flex:none;max-height:calc(var(--control-size) * 4);overflow-y:auto;gap:var(--space-4);padding:var(--space-5) var(--space-3) var(--space-3)}
+.integration.manager{--settings-sidebar:var(--surface);position:relative;max-width:none;width:100%;height:100%;min-height:100%;overflow:hidden;background:var(--settings-canvas)}
+.integration .integration-settings-shell{display:grid;grid-template-columns:var(--feature-sidebar-width,var(--settings-sidebar-width)) minmax(0,1fr);height:100%;min-height:0;background:var(--settings-canvas)}
+.integration .integration-settings-sidebar{display:flex;min-height:0;flex-direction:column;border-right:var(--stroke) solid var(--border);background:var(--settings-sidebar);overflow-y:auto;overscroll-behavior:contain;color:var(--sidebar-foreground)}
+.integration .integration-sidebar-header{display:grid;flex:none;gap:var(--space-4);padding:var(--space-5) var(--space-3) var(--space-3)}
.integration .integration-sidebar-brand{display:flex;align-items:center;gap:var(--space-3);padding-inline:var(--space-1)}.integration .integration-sidebar-brand strong,.integration .integration-sidebar-brand small{display:block}.integration .integration-sidebar-brand strong{font-size:var(--type-small);font-weight:var(--weight-strong)}.integration .integration-sidebar-brand small{margin-top:var(--space-1);color:var(--muted-foreground);font-size:var(--type-caption)}
.integration .integration-brand-icon{display:flex;align-items:center;justify-content:center;width:var(--brand-size);height:var(--brand-size);flex:none}.integration .integration-brand-icon svg{display:block;width:100%;height:100%}
.integration .integration-sidebar-header>input[type=search]{width:100%;min-height:var(--control-size);margin:0;border-radius:var(--radius-control);background:var(--secondary);font-size:var(--type-body)}.integration .integration-settings-sidebar .owner-picker-trigger{min-height:var(--control-size);font-size:var(--type-body)}
-.integration .integration-settings-nav{min-height:calc(var(--control-size) * 2);flex:1;overflow-y:auto;padding:0 var(--space-2) var(--space-4);scrollbar-width:thin}.integration .integration-nav-group{display:grid;gap:var(--space-1);margin-top:var(--space-3)}.integration .integration-nav-label{margin:0;padding:0 var(--space-2) var(--space-1);font-size:var(--type-caption);font-weight:var(--weight-medium);color:var(--muted-foreground)}
+.integration .integration-settings-nav{min-height:calc(var(--control-size) * 2);flex:1 0 auto;padding:0 var(--space-2) var(--space-4);scrollbar-width:thin}.integration .integration-nav-group{display:grid;gap:var(--space-1);margin-top:var(--space-3)}.integration .integration-nav-label{margin:0;padding:0 var(--space-2) var(--space-1);font-size:var(--type-caption);font-weight:var(--weight-medium);color:var(--muted-foreground)}
.integration .integration-nav-item{position:relative;display:flex;width:100%;min-height:var(--control-size);align-items:center;gap:var(--space-2);border:0;border-radius:var(--radius-control);padding:var(--space-2);text-align:left;background:transparent;color:var(--foreground);font-size:var(--type-small);font-weight:var(--weight-regular)}.integration .integration-nav-item:hover:not(:disabled){background:var(--hover)}.integration .integration-nav-item[aria-current=page]{background:var(--settings-selected);color:var(--settings-selected-text);font-weight:var(--weight-strong)}
.integration .integration-nav-item .provider-mark{width:var(--settings-nav-icon-size);height:var(--settings-nav-icon-size);border-radius:var(--radius-control)}.integration .integration-nav-item[aria-current=page] .provider-mark{border-color:var(--settings-selected-border);background:var(--settings-selected-subtle);color:var(--settings-selected-text)}.integration .integration-nav-item .provider-count{margin-left:auto;font-size:var(--type-caption);color:inherit;opacity:var(--settings-muted-opacity)}
.integration .integration-nav-utility::before{content:"";width:var(--space-2);height:var(--space-2);flex:none;border-radius:var(--radius-pill);background:var(--border)}.integration .integration-nav-utility[aria-current=page]::before{background:var(--settings-selected-text)}
-.integration .integration-sidebar-footer{flex:none;border-top:var(--stroke) solid var(--border);padding:var(--space-3)}.integration .integration-sidebar-footer button{width:100%;justify-content:center;border-color:transparent;background:transparent;color:var(--muted-foreground)}
-.integration .integration-settings-content{min-width:0;min-height:0;overflow-y:auto;background:var(--settings-canvas)}.integration .integration-heading,.integration .integration-settings-detail,.integration .identity-feedback{width:min(100%,var(--settings-content-width));margin-inline:auto}.integration .integration-heading{margin:0 auto;padding:var(--space-5) var(--space-5) 0;font:var(--weight-strong) var(--type-title)/var(--line-title) var(--font-display)}.integration .integration-settings-detail{padding:var(--space-5);padding-bottom:max(var(--space-5),env(safe-area-inset-bottom))}.integration .identity-feedback{padding:0 var(--space-5) var(--space-5)}
+.integration .integration-sidebar-footer{position:sticky;bottom:0;background:var(--surface);flex:none;border-top:var(--stroke) solid var(--border);padding:var(--space-3)}.integration .integration-sidebar-footer button{width:100%;justify-content:center;border-color:transparent;background:transparent;color:var(--muted-foreground)}
+.integration .integration-settings-content{min-width:0;min-height:0;overflow-y:auto;background:var(--settings-canvas)}.integration .integration-heading,.integration .integration-settings-detail,.integration .identity-feedback{width:min(100%,var(--settings-content-width));margin-inline:auto}.integration .integration-heading{margin:0 auto;padding:var(--space-5) var(--space-5) 0;font:var(--weight-strong) var(--type-title)/var(--line-title) var(--font-display)}.integration .integration-settings-detail{padding:var(--feature-padding,var(--space-5));padding-bottom:max(var(--space-5),env(safe-area-inset-bottom))}.integration .identity-feedback{padding:0 var(--space-5) var(--space-5)}
.integration .integration-mobile-toolbar{display:none}.integration .integration-sidebar-backdrop{display:none}.integration .integration-sidebar-toggle{min-height:var(--control-size)}
@container integration (max-width:${SETTINGS_COMPACT_MAX}){
.integration .integration-settings-shell{display:block;position:relative;min-height:100%}
.integration .integration-settings-sidebar{position:absolute;inset:0 auto 0 0;z-index:var(--settings-layer-drawer);width:min(100%,var(--settings-sidebar-sheet-width));transform:translateX(-100%);transition:transform var(--settings-transition);box-shadow:var(--shadow-pop)}
+ .integration .integration-settings-sidebar:not([data-open=true]){visibility:hidden;pointer-events:none}
.integration .integration-settings-sidebar[data-open=true]{transform:translateX(0)}
.integration .integration-sidebar-backdrop{position:absolute;inset:0;z-index:var(--settings-layer-backdrop);display:block;width:100%;height:100%;padding:0;border:0;border-radius:0;background:var(--settings-overlay)}
.integration .integration-sidebar-backdrop[hidden]{display:none}
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index 241dc396..06279831 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -30,7 +30,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
async function reload(){const version=++sequence;if(!bridge.query){draw();return}try{const next=await bridge.query({view:"snapshot",...(user?{user}:{})});if(disposed||version!==sequence)return;snapshot=next;user=next.user||user;draw();remember()}catch(e){if(!disposed){draw();status.textContent=textError(e)}}}
async function change(args,after=reload){if(!bridge.manage)return;try{status.textContent="Saving connection metadata…";await bridge.manage({...args,confirm:true});await after()}catch(e){status.textContent=textError(e)}}
function guide(method,parent=detail){const d=n("details",undefined,"identity-guide");d.open=parent!==detail;d.append(n("summary","How to get this credential / authorization"));const g=method.guidance,ol=n("ol");for(const step of g.steps)ol.append(n("li",step));d.append(ol);for(const[url,label]of [[g.url,"Official setup page"],[g.reference,"Documentation"]]){const a=n("a",label);a.href=url;a.rel="noopener noreferrer";a.target="_blank";if(bridge.openLink)a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(bridge.openLink(url)).catch(error=>status.textContent=textError(error))});d.append(a)}parent.append(d)}
- function setSidebar(open){const wasOpen=sidebarOpen;sidebarOpen=Boolean(open);if(sidebarPanel)sidebarPanel.dataset.open=String(sidebarOpen);if(sidebarBackdrop)sidebarBackdrop.hidden=!sidebarOpen;if(sidebarToggle)sidebarToggle.setAttribute("aria-expanded",String(sidebarOpen));if(content){content.inert=sidebarOpen;if(sidebarOpen)content.setAttribute("inert","");else content.removeAttribute("inert");}if(sidebarPanel){if(typeof window!=="undefined"&&window.matchMedia&&window.matchMedia("(max-width:37.5rem)").matches){sidebarPanel.inert=!sidebarOpen;if(sidebarOpen)sidebarPanel.removeAttribute("inert");else sidebarPanel.setAttribute("inert","")}else{sidebarPanel.inert=false;sidebarPanel.removeAttribute("inert")}}if(sidebarOpen)setTimeout(()=>sidebarPanel?.focus(),0);else if(wasOpen&&sidebarToggle)setTimeout(()=>sidebarToggle.focus(),0)}
+ function setSidebar(open){const wasOpen=sidebarOpen;sidebarOpen=Boolean(open);if(sidebarPanel)sidebarPanel.dataset.open=String(sidebarOpen);if(sidebarBackdrop)sidebarBackdrop.hidden=!sidebarOpen;if(sidebarToggle)sidebarToggle.setAttribute("aria-expanded",String(sidebarOpen));if(content){content.inert=sidebarOpen;if(sidebarOpen)content.setAttribute("inert","");else content.removeAttribute("inert");}if(sidebarPanel){if(root.clientWidth<=37.5*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16)){sidebarPanel.inert=!sidebarOpen;if(sidebarOpen)sidebarPanel.removeAttribute("inert");else sidebarPanel.setAttribute("inert","")}else{sidebarPanel.inert=false;sidebarPanel.removeAttribute("inert")}}if(sidebarOpen)setTimeout(()=>sidebarPanel?.focus(),0);else if(wasOpen&&sidebarToggle)setTimeout(()=>sidebarToggle.focus(),0)}
function activateNav(mode){navMode=mode;for(const entry of navButtons){const on=entry.mode===mode&&(mode!=="provider"||entry.provider===provider.id);entry.button.setAttribute("aria-current",on?"page":"false");entry.button.setAttribute("aria-pressed",String(on))}}
function showProfiles(){navMode="owners";activateNav(navMode);setSidebar(false);profiles()}
function showBindings(){navMode="routing";activateNav(navMode);setSidebar(false);bindings()}
@@ -55,7 +55,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
function showAiProviders(){navMode="ai-providers";activateNav(navMode);setSidebar(false);void aiProviders()}
function selectProvider(p){provider=p;navMode="provider";remember();activateNav(navMode);setSidebar(false);drawProvider()}
function draw(){
- root.replaceChildren();root.classList.add("integration","manager");
+ if(ro)ro.disconnect();root.replaceChildren();root.classList.add("integration","manager");
const shell=n("div",undefined,"integration-settings-shell");
sidebarBackdrop=b("",()=>setSidebar(false),"integration-sidebar-backdrop");sidebarBackdrop.addEventListener("keydown",event=>{if(event.key==="Escape"){event.preventDefault();setSidebar(false)}});sidebarBackdrop.hidden=true;sidebarBackdrop.setAttribute("aria-label","Close Integrations sections");
sidebarPanel=n("aside",undefined,"integration-settings-sidebar");sidebarPanel.id="integration-settings-sidebar";sidebarPanel.dataset.open="false";sidebarPanel.tabIndex=-1;
@@ -63,7 +63,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const search=n("input");search.type="search";search.placeholder="Search";search.setAttribute("aria-label","Search integrations");
const owner=choicePicker("Credential owner",snapshot.users.map(row=>({id:row.id,text:row.label+" · "+row.id+(row.isDefault?" · default":"")})),user,row=>{user=row.id;remember();void reload()});
sidebarHeader.append(brand,search,owner.wrap);sidebarPanel.append(sidebarHeader);
- if(typeof ResizeObserver!=="undefined"){ro=new ResizeObserver(entries=>{for(const entry of entries){const rem=parseFloat(getComputedStyle(document.documentElement).fontSize)||16,width=entry.contentBoxSize?.[0]?.inlineSize??entry.contentRect.width;if(width>37.5*rem){if(sidebarOpen)setSidebar(false);else if(sidebarToggle)sidebarToggle.setAttribute("aria-expanded","false")}}});ro.observe(root)}sidebarPanel.addEventListener("keydown",event=>{if(event.key==="Escape"&&sidebarOpen){event.preventDefault();setSidebar(false)}else if(event.key==="Tab"&&sidebarOpen){const focusables=Array.from(sidebarPanel.querySelectorAll("button:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(!focusables.length)return;const first=focusables[0],last=focusables[focusables.length-1];if(event.shiftKey&&document.activeElement===first){event.preventDefault();last.focus()}else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first.focus()}}});
+ if(typeof ResizeObserver!=="undefined"){ro=new ResizeObserver(entries=>{for(const entry of entries){const rem=parseFloat(getComputedStyle(document.documentElement).fontSize)||16,width=entry.contentBoxSize?.[0]?.inlineSize??entry.contentRect.width;if(width>37.5*rem)setSidebar(false);else setSidebar(sidebarOpen)}});ro.observe(root)}sidebarPanel.addEventListener("keydown",event=>{if(event.key==="Escape"&&sidebarOpen){event.preventDefault();setSidebar(false)}else if(event.key==="Tab"&&sidebarOpen){const focusables=Array.from(sidebarPanel.querySelectorAll("button:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(!focusables.length)return;const first=focusables[0],last=focusables[focusables.length-1];if(event.shiftKey&&document.activeElement===first){event.preventDefault();last.focus()}else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first.focus()}}});
const nav=n("nav",undefined,"integration-settings-nav");nav.setAttribute("aria-label","Integrations sections");
const connectionGroup=n("div",undefined,"integration-nav-group"),connectionLabel=n("p","Connections","integration-nav-label");connectionGroup.append(connectionLabel);
navButtons=[];for(const p of catalog){const item=b(undefined,()=>selectProvider(p),"integration-nav-item");item.append(mark(p),n("span",p.title));const count=snapshot.connections.filter(c=>c.provider===p.id).length;if(count){const badge=n("span",String(count),"provider-count");badge.setAttribute("aria-hidden","true");item.append(badge)}navButtons.push({mode:"provider",provider:p.id,button:item});connectionGroup.append(item)}
@@ -87,7 +87,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const pageHeading=n(headingTag,"Integrations","integration-heading");content.append(pageHeading);
if(!bridge.manage)content.append(n("p","Sign in as an MSO Owner to manage credentials. Device roles and credential users are different; public setup guides remain available.","identity-readonly"));
detail=n("section",undefined,"identity-detail integration-settings-detail");status=n("p",undefined,"identity-feedback");status.setAttribute("role","status");status.setAttribute("aria-live","polite");content.append(detail,status);
- shell.append(sidebarPanel,sidebarBackdrop,content);root.append(shell);container=shell;
+ shell.append(sidebarPanel,sidebarBackdrop,content);root.append(shell);container=shell;setSidebar(false);
activateNav(navMode);
if(navMode==="owners")profiles();else if(navMode==="variables")variables();else if(navMode==="demo-users")void demoUsers();else if(navMode==="ai-providers")void aiProviders();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();
}
@@ -185,7 +185,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const rows=snapshot.connections.filter(c=>c.provider===provider.id);if(rows.length){const count=rows.filter(ready).length;detail.append(n("p",rows.length+" connection"+(rows.length===1?"":"s")+" · "+count+" verified","identity-summary-line"));}
if(!rows.length){const empty=n("div",undefined,"identity-empty");empty.append(n("h3","Connect "+provider.title),n("p",user?"Add an account to start using "+provider.title+" in your projects.":bridge.manage?"Select a credential owner to add an account.":"Read the setup guide below, then sign in to connect your account."));const start=b("Add "+provider.title+" account",newConnection,"primary");start.disabled=!user||!bridge.manage;if(bridge.manage)empty.append(start);detail.append(empty);const help=n("details");help.append(n("summary","Connection methods & setup guides"));for(const s of provider.sources)for(const m of s.methods){const info=n("section");info.append(n("h3",s.label+" · "+m.label));guide(m,info);help.append(info)}detail.append(help)}
- for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of [human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.addEventListener("keydown",event=>{if(event.key==="Escape"){event.preventDefault();more.open=false;const summary=more.querySelector("summary");if(summary)summary.focus()}});more.addEventListener("toggle",()=>{if(!more.open)return;const away=event=>{if(!more.contains(event.target)){more.open=false;document.removeEventListener("pointerdown",away,true)}};document.addEventListener("pointerdown",away,true)});more.append(n("summary","More"));more.append(secondary);
+ for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of new Set([human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""]))if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.addEventListener("keydown",event=>{if(event.key==="Escape"){event.preventDefault();more.open=false;const summary=more.querySelector("summary");if(summary)summary.focus()}});more.addEventListener("toggle",()=>{if(!more.open)return;const away=event=>{if(!more.contains(event.target)){more.open=false;document.removeEventListener("pointerdown",away,true)}};document.addEventListener("pointerdown",away,true)});more.append(n("summary","More"));more.append(secondary);
if(provider.nativeGoogle&&!provider.configurationOnly){mountNativeGoogleConnection(card,c,{n,b,user,provider,catalog,snapshot,bridge,status,reload,selectProvider});detail.append(card);continue}
const open=b(c.source==="direct"?(c.fields.some(f=>f.stored)?"Update credentials":"Finish setup"):"Authorize",()=>{if(c.source==="direct")void bridge.openSetup({user,provider:provider.id,connection:c.id}).catch(e=>status.textContent=textError(e));else external(c)});open.disabled=!bridge.manage;if(!c.sharedFrom)actions.append(open);
const verify=b("Verify",async()=>{try{status.textContent="Checking selected connection…";const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});await reload();status.textContent=(result.ok===true?"Verified: ":"Status: ")+result.detail}catch(e){status.textContent=textError(e)}});verify.disabled=!bridge.execute;actions.append(verify);
@@ -212,7 +212,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const broker=input("Composio project connection ID",c.external?.brokerConnection||""),config=input("Auth config ID (when several exist)",c.external?.authConfigId||""),managed=input("","","checkbox");managed.label.className="identity-check";managed.label.append(document.createTextNode("Allow creation of a managed OAuth config if none exists"));detail.append(broker.label,config.label,managed.label);
const authorize=b("Open hosted authorization",async()=>{try{authorize.disabled=true;const result=await bridge.manage({action:"connection.authorize",confirm:true,user,provider:provider.id,connection:c.id,...(broker.input.value?{brokerConnection:broker.input.value}:{}),...(config.input.value?{authConfigId:config.input.value}:{}),createManaged:managed.input.checked});if(result.privateUrl){const a=n("a","Continue on Composio");a.href=result.privateUrl;a.rel="noopener noreferrer";a.target="_blank";a.addEventListener("click",e=>{if(bridge.openLink){e.preventDefault();bridge.openLink(result.privateUrl)}});detail.append(a)}status.textContent="Authorization pending. Complete the provider flow, then refresh status."}catch(e){status.textContent=textError(e);authorize.disabled=false}});authorize.disabled=Boolean(c.external?.connectedAccountId);if(c.external?.connectedAccountId)authorize.title="Already linked to "+c.external.connectedAccountId;detail.append(authorize,b("Refresh authorization status",async()=>{try{const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});await reload();status.textContent=result.detail}catch(e){status.textContent=textError(e)}}),b("Back",drawProvider));if(c.external?.connectedAccountId)detail.append(n("small","Already linked to "+c.external.connectedAccountId,"identity-muted"));
}
- draw();if(bridge.query)void reload();
+ draw();if(window.parent!==window)window.parent.postMessage({type:"mso:integrations-ready"},window.location.origin);if(bridge.query)void reload();
return()=>{disposed=true;sequence++;if(ro)ro.disconnect();root.replaceChildren();root.classList.remove("integration","manager")};
}
`;
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 51a362ef..ba95fdb8 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -36,9 +36,11 @@ try {
page.on("pageerror", error => errors.push(error.message));
await page.goto(fixture.base + "/integrations");
await expect(page.locator("#mso-boot-splash")).toHaveCount(0);
- await expect(page.getByRole("navigation", { name: "Integrations sections", exact: true })).toBeVisible();
+ const sections = page.getByRole("navigation", { name: "Integrations sections", exact: true });
+ if (viewport.width < 600) await expect(sections).not.toBeVisible();
+ else await expect(sections).toBeVisible();
await expect(page.getByRole("heading", { name: "GitHub", exact: true, level: 2 })).toBeVisible();
- if (viewport.width < 600) {await page.getByRole("button", { name: "Integrations sections", exact: true }).click();await page.getByRole("navigation", { name: "Integrations sections", exact: true }).getByRole("button", { name:"GitHub", exact:true }).click();}
+ if (viewport.width < 600) {await page.getByRole("button", { name: "Integrations sections", exact: true }).click();await expect(sections).toBeVisible();await sections.getByRole("button", { name:"GitHub", exact:true }).click();await expect(sections).not.toBeVisible();}
else {await page.getByLabel("Search integrations").fill("GitHub");await page.getByRole("navigation", { name: "Integrations sections", exact: true }).getByRole("button", { name:"GitHub", exact:true }).click();}
await expect(page.getByRole("heading", {name:"GitHub", exact:true})).toBeVisible();
await page.getByText("Connection methods & setup guides", { exact: true }).click();
diff --git a/scripts/e2e/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjs
index ab195f82..9c37c4c8 100644
--- a/scripts/e2e/workflow-canvas.mjs
+++ b/scripts/e2e/workflow-canvas.mjs
@@ -67,6 +67,19 @@ export async function workflowCanvasJourney(page, fixture) {
await expect(insertedWait).toHaveCount(0);
await expect(canvas.locator(".react-flow__edge")).toHaveCount(7);
+ const workflowName = page.getByLabel("Workflow name");
+ const saveWorkflow = page.locator('[data-slot="workflows-feature"] [data-slot="app-frame-toolbar"]').getByRole("button", { name: "Save", exact: true });
+ const originalName = await workflowName.inputValue();
+ await workflowName.fill(originalName + " unsaved");
+ for (const viewport of [{ width: 390, height: 844 }, { width: 1280, height: 900 }]) {
+ await page.setViewportSize(viewport);
+ await expect(page.locator("#main-content")).toHaveAttribute("data-shell", viewport.width < 768 ? "ios" : "macos");
+ await expect(page.getByLabel("Workflow name")).toHaveValue(originalName + " unsaved");
+ }
+ await page.getByLabel("Workflow name").fill(originalName);
+ await saveWorkflow.click();
+ await expect(saveWorkflow).toBeDisabled();
+
// Responsive contract: on a phone-sized pane the wide graph starts focused on
// the trigger at a readable zoom, side panels become drawers, and the toolbar
// collapses secondary actions without horizontal feature overflow.
@@ -114,9 +127,9 @@ export async function workflowCanvasJourney(page, fixture) {
const directory = page.locator('[data-slot="workflow-directory-panel"]');
await expect(directory.getByPlaceholder("Search tools…")).toBeVisible();
await expect(directory.getByText("agent_memory_search", { exact: true })).toBeVisible();
- await page.getByRole("button", { name: "projects", exact: true }).click();
+ await directory.getByRole("button", { name: "projects", exact: true }).click();
await expect(directory.getByText("fixture-project", { exact: true })).toBeVisible();
- await page.getByRole("button", { name: "skills", exact: true }).click();
+ await directory.getByRole("button", { name: "skills", exact: true }).click();
await expect(directory.getByText("No matching skills.", { exact: true })).toBeHidden();
await page.getByRole("button", { name: "Builder", exact: true }).click();
@@ -144,7 +157,7 @@ export async function workflowCanvasJourney(page, fixture) {
await expect(statusSelect).toHaveValue("draft");
await statusSelect.selectOption("active");
await expect(statusSelect).toHaveValue("active");
- await page.getByRole("button", { name: "Save", exact: true }).click();
+ await saveWorkflow.click();
await expect(page.getByText("Unsaved", { exact: true })).toBeHidden();
response = await get(page, `graph_id=${encodeURIComponent(graph.id)}`);
expect(response.status).toBe(200); graph = response.body.graph;