diff --git a/.changeset/36501-studio-back-to-app.md b/.changeset/36501-studio-back-to-app.md new file mode 100644 index 00000000000..ad720150303 --- /dev/null +++ b/.changeset/36501-studio-back-to-app.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): the top bar's left end reads 「‹ Back to app」, the app's name and "Studio"; the Studio-home button, the package switcher and Open app are gone + +Clause-②: no +Metadata-protocol: none + +Studio's top bar now starts with one way out: 「‹ Back to app · APP · Studio」. Entered from an app, the link names that app and returns to the page the author came from, its query included. Opened directly (a Studio address in a new tab, a reload), it names the package's published app and lands on its first screen; with several apps, the first. A package with no published app (none yet, or only a draft) and the organization flows scope read 「‹ Back to app」 with no name and go to the console's landing. Leaving with unsaved work in a pillar asks first, as every other header departure does. + +The home icon, the package switcher and the top-right Open app button are removed. Another package is opened from the app, or from the Studio landing, whose cards also carry package management and New package. + +New studio catalogue keys (en, zh): `engine.studio.backToApp`, `engine.studio.backToAppTitle`, `engine.studio.backToAppTitleNoApp`, `engine.studio.mark`. Removed with the Open app button: `engine.studio.openApp`, `engine.studio.openAppTitle`, `engine.studio.openAppPick`. `engine.studio.app.willOpenAfterPublish` now names 「Back to app」. No props or exports of the published packages change. diff --git a/ui/e2e/live/studio-customize-journey.spec.ts b/ui/e2e/live/studio-customize-journey.spec.ts index e2455bd1115..fcc12a1d329 100644 --- a/ui/e2e/live/studio-customize-journey.spec.ts +++ b/ui/e2e/live/studio-customize-journey.spec.ts @@ -165,7 +165,9 @@ test('a read-only base is customized, restored and extended through Studio, and try { await test.step('Customize a view: the edit lands in the pair, and the server serves its columns', async () => { await page.goto(`/studio/${BASE}/interfaces?surface=${encodeURIComponent(`view:${VIEW}`)}`); - await expect(page.getByTestId('studio-pkg-readonly')).toBeVisible(); + // The read-only base offers Customize (the top bar's read-only chip left + // with the package switcher, objectstack#36501). + await expect(page.getByTestId('studio-customize')).toBeVisible(); await page.getByTestId('studio-customize').click(); const ensured = page.waitForResponse( diff --git a/ui/e2e/live/studio-object-designer.spec.ts b/ui/e2e/live/studio-object-designer.spec.ts index 2e95b199ff1..4f42faf2a1f 100644 --- a/ui/e2e/live/studio-object-designer.spec.ts +++ b/ui/e2e/live/studio-object-designer.spec.ts @@ -10,7 +10,8 @@ import { test, expect, type APIRequestContext, type Page } from '@playwright/tes * spec-liveness) cannot catch because the break only appears when a real user * drives the real controlled inputs against the real spec validator: * F2 — per-keystroke identifier sanitisation (must TYPE, not fill) - * F1 — cross-component reactivity (create package → switcher refresh) + * F1 — retired with the Studio top bar's package switcher (objectstack#36501); + * a package is created on the Studio landing now * F3 — label→api-name derivation on blur * F4 — empty picklist row must not trip spec validation, and is not stored * @@ -25,7 +26,6 @@ import { test, expect, type APIRequestContext, type Page } from '@playwright/tes // The area opens a create page on a WRITABLE package only: the showcase is // provided by code, so its create URL lands on the type's list, and every // test that opens the designer authors a package of its own first. -const PKG = 'com.example.showcase'; const newObjectIn = (pkg: string) => `/studio/${pkg}/metadata/object/new?package=${pkg}`; const API = process.env.LIVE_API_URL || 'http://localhost:3000'; @@ -124,41 +124,3 @@ test('F4: adding a picklist + an empty option row does not trip spec validation, await request.delete(`${API}/api/v1/packages/${pkgId}`); } }); - -test('F1: a newly created package appears in the switcher without a reload', async ({ page }) => { - const stamp = Date.now(); - const pkgId = `com.e2e.dogfood${stamp}`; - const pkgName = `E2E Dogfood ${stamp}`; - const pkgIdPattern = pkgId.replace(/\./g, '\\.'); - // The console's Studio surface (`/studio/:packageId/:tab`) carries the - // package switcher on a stock boot. The sidebar switcher (`package-switcher`) - // renders only for an app that declares `contextSelectors`, and no app a - // stock showcase boot serves declares one. - await page.goto(`/studio/${PKG}/data`); - const chip = page.getByTestId('studio-pkg-chip'); - await chip.click(); - await page.getByRole('button', { name: /New package/i }).click(); - await page.getByRole('dialog').getByLabel(/^Display name/).first().fill(pkgName); - // The id sits in the collapsed Advanced section (objectstack#27833). - await page.getByTestId('package-form-advanced-toggle').click(); - await page.getByTestId('package-form-id-input').fill(pkgId); - await page.getByTestId('package-form-submit').click(); - - // No reload: the surface moves into the new package, and the switcher's chip - // names it from the refreshed list (a stale list falls back to the raw id)… - await expect(page).toHaveURL(new RegExp(`/studio/${pkgIdPattern}/`)); - await expect(chip).toContainText(pkgName); - // …and the open switcher lists it by its name, which only the refreshed list - // carries (each entry's accessible name is its name, then its id). - await chip.click(); - await expect(page.getByRole('button', { name: new RegExp(`${pkgName}\\s*${pkgIdPattern}`) })).toBeVisible(); - - // Cleanup so we don't pollute the shared dev stack. - await page.evaluate(async (id) => { - const tok = localStorage.getItem('auth-session-token'); - await fetch(`/api/v1/packages/${id}`, { - method: 'DELETE', - headers: { Authorization: `Bearer ${tok}` }, - }).catch(() => {}); - }, pkgId); -}); diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 9e2bc8f6172..6e2ffa9d077 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -643,16 +643,16 @@ package writability stays a server-side concern — a read-only package opens in Studio as browse-only. For a read-only package the button draws an eye with the words "Open {app} in Studio" (ADR-0146 D5) instead of the pencil. -The way back is Studio's own "Open app" button in the workbench top bar -(`StudioOpenApp`). It reads the `?surface=` Studio has in focus — the same -target "Edit app" hands over — and lands on that object's list -(`/apps/:app/`), on that dashboard, page or report, or else on the -app's home, in the same tab. A package with several published apps gets a -picker; a package whose only app is still a draft gets no button. - -Studio's package switcher never lists a kernel package (ADR-0016 §3.8): neither -one whose manifest carries `scope: system | cloud` nor a row served with that -`scope` flat. There is no toggle that shows them. +The way back is the 「‹ Back to app」 link at the left end of Studio's top bar +(`StudioBackToApp`), followed by the app's name and the "Studio" mark. Entered +from an app, it names that app and returns to the page the author left, query +included (`utils/appReturnPage.ts`, recorded by `ConsoleLayout`, held in module +memory only). Opened directly (a new tab, a reload), it names the package's +first published app and lands on its home. A package with no published app (a +draft-only app counts as none) reads 「‹ Back to app」 with no name and goes to +the console's declared landing (`useHomePath()`). Leaving with unsaved work in a +pillar asks first. Studio's top bar has no package switcher: another package is +opened from its app or from the Studio landing. The sidebar's ⋯ menu offers the same bridge per entry: the **Design** entry of an `object`, `dashboard` or `page` navigation entry, and of the matching favorites, diff --git a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts index a086daa15cb..2d1fe0917f3 100644 --- a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts +++ b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts @@ -36,8 +36,8 @@ * agent; * - `console/ai/__tests__/resolveCollapseToDockTarget.test.ts` — the dock * landing on a cold deep link; - * - `views/studio-design/StudioDesignSurface.packageDeletionInference.test.tsx` - * — eviction when the edited package is deleted; + * - `views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx` — the + * Studio top bar's 「Back to app」 when the package has no published app; * - `apps/console/src/components/StudioRoute.test.tsx` — the `/studio` entry * gate and the front door's wordmark; * - `apps/console/src/pages/auth/__tests__/AcceptInvitationRoute.test.tsx` — @@ -139,12 +139,13 @@ const RECOVERY_SITES: ReadonlyArray<{ alsoReads: [ 'packages/app-shell/src/views/studio-design/StudioNavItemInspector.tsx', 'packages/app-shell/src/views/studio-design/PackageSwitcher.tsx', + 'packages/app-shell/src/views/studio-design/StudioBackToApp.tsx', 'packages/app-shell/src/views/studio-design/InterfacesNavRail.tsx', 'packages/app-shell/src/views/studio-design/AutomationsFlowRail.tsx', 'packages/app-shell/src/views/studio-design/StudioPillarKit.tsx', 'packages/app-shell/src/views/studio-design/DataPillarHelpers.tsx', ], - site: 'Studio: deleted-package eviction + header Home', + site: 'Studio: the header Back to app, with no app to name', expression: /const homePath = useHomePath\(\)/, }, { diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index 48fdfe32386..1453e95fcad 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -27,6 +27,7 @@ import { PhoneAppNavBar, isPhoneTabRoute } from './PhoneAppNavBar.js'; import { PhoneAppHomeSlotProvider } from './PhoneAppHome.js'; import { PhonePageBarProvider } from './PhonePageBar.js'; import { useLastApp } from '../context/LastAppProvider.js'; +import { rememberAppReturnPage } from '../utils/appReturnPage.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { appAddressSegment } from '../utils/appRoute.js'; import { ShellPageActionsScope, ShellSidebarExpandFallback } from './ShellPageActions.js'; @@ -202,6 +203,16 @@ export function ConsoleLayout({ useEffect(() => { if (activeAppName) rememberApp(activeAppName); }, [activeAppName, rememberApp]); + // objectstack#36501 — and the app page in view, where Studio's 「‹ Back to + // app」 returns: an app → Studio entry leaves from the page recorded last. + useEffect(() => { + if (!activeAppName) return; + rememberAppReturnPage({ + path: `${location.pathname}${location.search}${location.hash}`, + app: activeAppName, + label: appLabel, + }); + }, [activeAppName, appLabel, location.pathname, location.search, location.hash]); const { apps: metadataApps } = useMetadata(); const appBasePath = `/apps/${appAddressSegment(metadataApps, activeApp) ?? activeAppName}`; // objectstack#36362 — the app's design mode, held here so it stays on from diff --git a/ui/packages/app-shell/src/utils/appReturnPage.ts b/ui/packages/app-shell/src/utils/appReturnPage.ts new file mode 100644 index 00000000000..9a572dc14cc --- /dev/null +++ b/ui/packages/app-shell/src/utils/appReturnPage.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The app page the person last had open, for Studio's 「‹ Back to app」 + * (objectstack#36501). + * + * `ConsoleLayout` records it on every app route; Studio's top bar reads it. + * An app → Studio entry is an in-app navigation, so the record names the page + * the author came from, and the back link returns there. + * + * Held in module memory on purpose, never in browser storage: a Studio URL + * opened directly (a new tab, a pasted link, a reload) starts with no record, + * and the back link then lands on the package's own app instead of on a page + * from some earlier visit. + */ + +/** One app page, as the app bar names it. */ +export interface AppReturnPage { + /** The route, with its query and hash: where the back link navigates. */ + path: string; + /** The app's name (its route key). */ + app: string; + /** The app's display label, in the language it was shown in. */ + label: string; +} + +let lastAppPage: AppReturnPage | null = null; + +/** Records `page` as the app page now open. */ +export function rememberAppReturnPage(page: AppReturnPage): void { + if (!page.path || !page.app) return; + lastAppPage = { ...page }; +} + +/** The app page last open in this page load, or `null` when none was. */ +export function readAppReturnPage(): AppReturnPage | null { + return lastAppPage; +} + +/** Tests only: forget the record, as a fresh page load starts. */ +export function resetAppReturnPageForTests(): void { + lastAppPage = null; +} diff --git a/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx b/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx index 8aa933b9127..fb35e3c41e9 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageSwitcher.tsx @@ -1,83 +1,38 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Studio's top-bar package switcher, with the package-list toast id and the - * Studio landing path it shares with the surface: moved out of - * `StudioDesignSurface.tsx` unchanged by objectstack#29988 (slice 2 of the - * move-only split). + * The package helpers Studio's surface and its landing share: the + * package-list toast id, the Studio landing path and the installed-row read. + * The top-bar package switcher that lived here with them, since + * objectstack#29988's move-only split, was removed by objectstack#36501: the + * top bar's left end is 「‹ Back to app」 (`StudioBackToApp.tsx`), and a + * package is picked in the app or on the Studio landing (`BuilderLanding`), + * whose cards also open the management sheet. */ -import * as React from 'react'; -import { useNavigate } from 'react-router-dom'; -import { formatMetadataError } from '@object-ui/data-objectstack'; -import { AppMark, type AppMarkApp } from '../../layout/AppMark.js'; -import { STUDIO_PKG_READONLY_WORD } from './studio-tokens.js'; -import { - Popover, - PopoverTrigger, - PopoverContent, - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from '@object-ui/components'; -import { - AlertTriangle, - Boxes, - Building2, - Loader2, - Plus, - ChevronDown, - Lock, - Settings, - Home as HomeIcon, -} from 'lucide-react'; -import { studioOrgScopePath } from './studioScope.js'; -import { useHomePath } from '../../hooks/useHomePath.js'; -import { useRecentItems } from '../../context/RecentItemsProvider.js'; -import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; -import { CreatePackageDialog, PackageDetailSheet, type InstalledPackageRow } from '../metadata-admin/PackagesPage.js'; -import { fetchPackages, type PkgEntry } from './packages-io.js'; -import { foldCustomizationPairs } from './StudioRailCustomizations.js'; -import { toast } from 'sonner'; +import type { InstalledPackageRow } from '../metadata-admin/PackagesPage.js'; -/** Top-bar package switcher: list app packages (writable base vs read-only - * code), switch by navigation, create a new writable base via the standard - * CreatePackageDialog, and open the standard PackageDetailSheet (info + - * disable / duplicate / delete / publish …) for the current package. */ /** * One sonner id for EVERY `fetchPackages()` failure on this surface - * (objectui#7368). Three effects call that one endpoint on mount — the - * switcher list, the writability courtesy gate and the namespace lookup — so a - * single 503 rejects all three. Sonner UPDATES a toast that already carries the - * id instead of stacking a new one (the `outcomeToastId` pattern this repo - * already uses in `packages/components/src/renderers/form/form.tsx`), so one - * outage produces one toast, not three. Reporting the failure is the point; + * (objectui#7368). More than one effect calls that one endpoint on mount — the + * writability courtesy gate and the namespace lookup — so a single 503 rejects + * them all. Sonner UPDATES a toast that already carries the id instead of + * stacking a new one (the `outcomeToastId` pattern this repo already uses in + * `packages/components/src/renderers/form/form.tsx`), so one outage produces + * one toast, not several. Reporting the failure is the point; * reporting it three times is noise that would get the report muted. */ export const PACKAGE_LIST_TOAST_ID = 'studio-package-list'; -/** objectui#12513 — the Studio landing (`BuilderLanding`), where the header's first button and the switcher's first row lead. */ +/** objectui#12513 — the Studio landing (`BuilderLanding`). */ export const STUDIO_LANDING_PATH = '/studio'; -/** - * The rows the switcher offers: every listed package but a kernel one - * (ADR-0016 §3.8 — "you cannot author into a kernel package"). `null` while - * the list has not answered. There is no toggle that shows them: a kernel - * package opened by its URL is still named by the chip (`openEntry`). - */ -export function offeredPackages(pkgs: readonly PkgEntry[] | null): PkgEntry[] | null { - return pkgs === null ? null : pkgs.filter((p) => !p.kernel); -} - /** * The record the standard detail/management sheet opens on: a package's full * installed row (manifest + status), read from `GET /api/v1/packages`, since - * the switcher and the Studio landing hold only the trimmed {id,name,writable} - * view. `null` = the list answered and does not name `id`; a failed read - * throws. Shared by the switcher's "Package info & settings" entry and the - * landing cards' Manage (objectstack#35196), so both doors open the sheet on - * the same record. + * the Studio landing holds only the trimmed {id,name,writable} view. `null` = + * the list answered and does not name `id`; a failed read throws. Read by the + * landing cards' Manage (objectstack#35196). */ export async function fetchInstalledPackageRow(id: string): Promise { const res = await fetch('/api/v1/packages', { @@ -182,558 +137,3 @@ export async function fetchInstalledPackageRow(id: string): Promise; return list.find((p) => (p?.manifest?.id ?? p?.id) === id) ?? null; } - -export function PackageSwitcher({ - packageId, - tab, - beforeNavigate, - app = null, - openEntry = null, -}: { - /** The package's app, drawn as the chip's icon tile (objectui#12459); `null` draws the neutral tile. */ - app?: AppMarkApp | null; - /** - * objectstack#29567 — the surface's own entry for the open package, which - * the trigger reads when this list does not carry it: a kernel package is - * left out of the list (it is not offered), yet when it is open the chip - * still names it and says it is read-only. The menu never reads it. - */ - openEntry?: PkgEntry | null; - /** The open package, or `null` in the package-less scope (objectui#11553). */ - packageId: string | null; - tab: string; - /** objectui#2600 — veto hook for package-switch navigation: return false to - * stay put (the surface prompts about unsaved pillar edits). Not consulted - * for the deleted-package eviction in onManageChanged — that navigation is - * forced (the package under the editor is gone). */ - beforeNavigate?: () => boolean; -}): React.ReactElement { - const navigate = useNavigate(); - const locale = useMetadataLocale(); - // objectui#7373 — where the deleted-package eviction below lands when no - // other package is left to open: the DECLARED landing, the launcher only when - // the deployment declares none. - const homePath = useHomePath(); - const { removeRecentItem } = useRecentItems(); - const [open, setOpen] = React.useState(false); - const [pkgs, setPkgs] = React.useState(null); - /** - * The last package-list failure, or `null` if the last attempt did not fail - * (objectui#7368). - * - * `pkgs === null` alone cannot say WHY the list is absent, and the trigger's - * `current?.name ?? packageId` then renders the same raw reverse-domain id - * for THREE different situations — still loading, the fetch failed, and a - * package that genuinely declares no name. The author reading `app.b2r4` in - * the top bar had no way to tell whether to go fix the manifest or to go - * retry, and nothing else on screen told them either: no toast, no console - * line. This slot is the second bit that separates them, and the surface - * spells the three out the same way it already does at the Interfaces rail - * / Data rail / Automations rail empty states (`error ? loadFailed : loaded - * ? none : loading`). - */ - const [pkgsErr, setPkgsErr] = React.useState(null); - const [createOpen, setCreateOpen] = React.useState(false); - const [manage, setManage] = React.useState(null); - const [manageOpen, setManageOpen] = React.useState(false); - const [manageBusy, setManageBusy] = React.useState(false); - - React.useEffect(() => { - let cancelled = false; - const load = () => { - fetchPackages() - .then((parsed) => { - if (cancelled) return; - setPkgs(parsed); - setPkgsErr(null); - }) - .catch((e: unknown) => { - // objectui#7368 — the switcher still works for navigation-free - // display, so this stays a DEGRADATION and never a throw: one 503 - // must not take the whole Studio top bar down with it. What it stops - // being is SILENT. The failure is reported once (toast, this file's - // own posture — `formatMetadataError` is used at 19 other call - // sites in this file; this one was the exception, not the rule) - // and, because a toast disappears while the top bar keeps showing - // the id forever, it is also RECORDED so the trigger can say which - // of the three states it is in. - if (cancelled) return; - const message = formatMetadataError(e); - setPkgsErr(message); - toast.error(message, { id: PACKAGE_LIST_TOAST_ID }); - }); - }; - load(); - // Refresh the switcher list (and thus the top-bar package name) when a - // package is created or its manifest is edited elsewhere — PackageFormDialog - // dispatches `objectui:packages-changed` on create/edit. Without this the - // header showed the OLD name after a rename until a full page reload. - window.addEventListener('objectui:packages-changed', load); - return () => { - cancelled = true; - window.removeEventListener('objectui:packages-changed', load); - }; - }, [packageId]); - - // ADR-0016 §3.8 — kernel packages are not offered for authoring. `fetchPackages` - // already leaves out the manifest-scoped ones; a row the registry half serves - // flat with a kernel `scope` stays in that list, tagged `kernel`, because the - // app → Studio entry gate reads the tag. The switcher hides it here. - const offered = offeredPackages(pkgs); - // The trigger NAMES the open package, which is not offering it: a kernel - // package opened by its URL is still named from its listed row. - const listedCurrent = pkgs?.find((p) => p.id === packageId) ?? null; - // Only once the list has answered, so the three trigger states stay its own. - const current = listedCurrent ?? (pkgs !== null && openEntry?.id === packageId ? openEntry : null); - // objectstack#28572 (ADR-0146 D3) — a base's paired `.custom` has no - // row of its own: it is folded under its base, which names it. - const folded = React.useMemo(() => foldCustomizationPairs(offeredPackages(pkgs) ?? []), [pkgs]); - /** - * Which of the three the trigger is showing (objectui#7368). A failure wins - * over a list already in hand: after a failed refresh the names on screen are - * stale, and saying "loaded" about them would be the same lie in a new place. - */ - const pkgListState: 'loading' | 'failed' | 'loaded' = - pkgsErr !== null ? 'failed' : pkgs === null ? 'loading' : 'loaded'; - - const fetchFullPackage = fetchInstalledPackageRow; - - const openManage = React.useCallback( - async (id: string) => { - setOpen(false); - setManageBusy(true); - try { - const full = await fetchFullPackage(id); - /** - * ⛔ The sheet never opens on a `null` package (objectui#7881). With - * the read above now refusing, `null` means only what it always should - * have meant: the list came back, and this package is not in it — - * deleted or uninstalled elsewhere since the switcher last loaded. - * `PackageDetailSheet` renders `null` for a null `pkg`, so opening it - * anyway produced a click that did nothing and said nothing, and left - * `manageOpen` stuck true with no rendered sheet to close it. - * - * Reported, not thrown: the read SUCCEEDED, so there is no caught - * error to format and nothing about the endpoint to report. - */ - if (!full) { - toast.error(tFormat('engine.studio.pkg.manageMissing', locale, { id }), { - id: PACKAGE_LIST_TOAST_ID, - }); - return; - } - setManage(full); - setManageOpen(true); - } catch (e) { - /* - * This surface's EXISTING objectui#7368 posture, now also carrying the - * shared sonner id: `fetchFullPackage` is the FOURTH caller of - * `/api/v1/packages` on this surface (the switcher list, the - * writability courtesy gate and the namespace lookup are the other - * three), so one outage that rejects all four is one toast, not four. - * - * ⛔ Deliberately NOT also recorded in `pkgsErr`. That slot is the - * switcher LIST's state and is written exactly where `pkgs` is — the - * mount effect and `onManageChanged`. This callback never writes - * `pkgs`, so the names in the trigger are precisely as current as they - * were a moment ago, and the two sibling `fetchPackages` call sites - * that likewise do not write the list report the same way. - */ - toast.error(formatMetadataError(e), { id: PACKAGE_LIST_TOAST_ID }); - } finally { - setManageBusy(false); - } - }, - [fetchFullPackage, locale], - ); - - // A lifecycle action ran in the sheet — refresh the list AND the managed - // snapshot (so an edit shows immediately). If the managed package was the one - // we're editing and it's now gone (deleted), return to the Studio landing - // (home, when no package is left). - const onManageChanged = React.useCallback(async () => { - /** - * `null` means "the refresh did not tell us anything", which is NOT the - * same fact as "the server listed the packages and yours is not among - * them" (objectui#7821). Those two used to be the SAME value: `list` - * started as `[]` and the `.catch` left it that way — the comment there - * said "keep the stale list", true of the `pkgs` state, which simply is - * not written, but never of this local. So after a failed - * `GET /api/v1/packages` the `!list.some(...)` below was unconditionally - * true, the code took the branch labelled `// Deleted`, and with `list[0]` - * undefined a transient 503 evicted the author from the editor to - * `/home` — no toast, no confirmation, package still there. Absence of - * evidence is not evidence of deletion. - */ - let list: PkgEntry[] | null = null; - try { - list = await fetchPackages(); - setPkgs(list); - // A list we did receive is current, so it also clears an earlier - // failure — otherwise the trigger would keep reading `failed` over - // names that are now fresh. - setPkgsErr(null); - } catch (e) { - // Reported through this surface's EXISTING posture (objectui#7368): - // `formatMetadataError` on the shared sonner id (one outage, one toast) - // and recorded, so the trigger reads `failed` rather than showing a - // stale list as though it were current. ⛔ Still not a `throw` — one - // 503 must not take the Studio down — and ⛔ still no retry, whose - // count / backoff / give-up state nobody has ruled on. - const message = formatMetadataError(e); - setPkgsErr(message); - toast.error(message, { id: PACKAGE_LIST_TOAST_ID }); - } - const managedId = manage?.manifest.id; - if (!managedId) return; - // A list we actually received, that does not contain the managed package, - // is the ONLY evidence of deletion. `list === null` draws no inference - // either way: the author stays put, and the managed snapshot below is - // still refreshed (that call reports its own outcome). - if (list !== null && !list.some((p) => p.id === managedId)) { - // objectstack#32615 — the delete happened here, so the Studio landing's - // "Recently viewed" row forgets it now, from storage as well: the entry - // `StudioRoute` recorded (`package:`) names a package that is gone. - // The landing also hides any entry the package list does not hold, for a - // package removed anywhere else. - removeRecentItem(`package:${managedId}`); - // Deleted — only navigate away if it was the package we're editing. - // While other packages remain, that is the Studio landing - // (objectui#11784), where the author picks the next one or creates one; - // this used to open `list[0]`, whichever package the list started with, - // so a delete read as "Studio moved me into another app". With nothing - // left it is still the declared home (objectui#7373). - if (managedId === packageId) { - navigate(list.length > 0 ? '/studio' : homePath); - } - return; - } - /** - * The managed snapshot behind the OPEN sheet (objectui#7907). A lifecycle - * action has just run — disable / enable / duplicate / publish / - * publish-drafts / manifest edit — so the record in `manage` is ALREADY - * known to be out of date, and this read is what replaces it. Neither way - * it can fail may be silent, and neither may leave the PRE-ACTION record on - * screen as though it were current. - * - * The arm this replaces was `catch {}` under a comment reading "keep the - * current snapshot" — true of what it did, and the reason it was wrong: - * the author disabled the package, was told nothing, and went on reading - * `Status: Enabled`. ⚠️ It is a PRE-EXISTING defect that objectui#7881 - * (PR #7906) made much easier to hit, NOT a regression from it: before that - * card `fetchFullPackage` never read `res.ok`, so this catch could only - * ever see a `res.json()` rejection; now that the helper refuses a non-2xx, - * the same catch also swallows every 401 / 403 / 503 / 500. Fixing one - * swallowing site made the next swallowing site swallow more. - * - * ⛔ Why the sheet CLOSES rather than staying open on the stale record. - * `PackageDetailSheet` is an ACTION surface, and it derives its verb from - * the record it was handed: `enabled = pkg.enabled !== false && pkg.status - * !== 'disabled'` picks both the button's label and the endpoint it POSTs - * (`.../${enabled ? 'disable' : 'enable'}`, `PackagesPage.tsx`). Left open - * over a snapshot we KNOW is pre-action, it does not merely display a stale - * badge — it re-arms the author with the verb they just fired. Closing it - * is still a DEGRADATION and not a throw (objectui#7368's standing ruling - * — one 503 must not take the Studio down): the editor, the top bar and - * the package list all stay, and reopening the sheet re-runs this same read - * one click away, which objectui#7881 taught to report its own outcome. - * - * ⛔ `manage` is deliberately NOT nulled — a null `pkg` with `manageOpen` - * still true is precisely the stuck state objectui#7881 fixed, and the next - * `openManage` overwrites the record anyway. - * - * ⛔ Not recorded in `pkgsErr` either, and this arm was MEASURED rather - * than inherited: that slot is the switcher LIST's state and is written - * exactly where `pkgs` is — the mount effect and the HEAD of this callback, - * the only two sites that write either. This TAIL writes neither; it writes - * `manage`. The head has just recorded the list's own verdict (a fresh list - * and `null`, or its failure), so writing `pkgsErr` from here would mark - * the trigger `failed` over names the head refreshed successfully a moment - * ago — the same lie as objectui#7368's, pointed the other way. - * - * ⛔ And no navigation: a snapshot this read could not deliver is not - * evidence of deletion (objectui#7821). Reporting is not inferring. - */ - try { - const fresh = await fetchFullPackage(managedId); - if (fresh) { - setManage(fresh); - } else { - // The read SUCCEEDED and the package is not in the list — the same - // fact `openManage` reports when it refuses to open on it, said with - // the same key. Not a caught error: there is nothing about the - // endpoint to report. - toast.error(tFormat('engine.studio.pkg.manageMissing', locale, { id: managedId }), { - id: PACKAGE_LIST_TOAST_ID, - }); - setManageOpen(false); - } - } catch (e) { - // This surface's EXISTING objectui#7368 posture — `formatMetadataError` - // on the shared sonner id, so ONE outage that rejects both halves of this - // callback is one toast rather than a stack. ⛔ Not a second reporting - // channel: the message names the consequence the author can see (their - // panel closed) and carries the server's own words inside it. - toast.error( - tFormat('engine.studio.pkg.manageRefreshFailed', locale, { - id: managedId, - error: formatMetadataError(e), - }), - { id: PACKAGE_LIST_TOAST_ID }, - ); - setManageOpen(false); - } - }, [manage, packageId, navigate, fetchFullPackage, locale, homePath, removeRecentItem]); - - return ( - // Radix Popover (portaled to ) — the top bar is `overflow-x-auto`, - // which forces `overflow-y: auto` too, so an `absolute` panel used to be - // CLIPPED by the header instead of overlaying the canvas. Portaling escapes - // that clip. Create / manage open the standard dialog + sheet (also - // portaled), so neither is subject to the header clip either. - - {/* objectui#12611 — the chip's tooltip holds what a narrow chip drops: - the whole name, the read-only posture, and what the chip does (the - trigger's former `title`, moved here so one tooltip shows, not two). */} - - - - - - - - -

- {packageId === null ? t('engine.studio.org.name', locale) : (current?.name ?? packageId)} -

- {current && !current.writable && ( -

-

- )} -

{t('engine.studio.pkg.switchTitle', locale)}

-
-
-
- - - {/* objectui#12513 — the Studio landing leads the list: the way - back to every package, recent ones and the organization's - flows. Gated like every other row here. */} -
- -
-

- {t('engine.studio.pkg.heading', locale)} -

-
- {/* Same three-way the Interfaces / Data / Automations rails - already spell out in this file — a failed list stops reading - "Loading…" forever, and carries WHY. */} - {pkgListState === 'loading' && ( -

{t('engine.studio.loading', locale)}

- )} - {pkgListState === 'failed' && ( -

- {pkgsErr} -

- )} - {pkgListState === 'loaded' && offered?.length === 0 && ( -

{t('engine.studio.pkg.none', locale)}

- )} - {offered !== null && folded.rows.map((p) => ( - - ))} -
- - {/* objectui#11553 — the package-less scope, reachable from every - package as it is from the Studio home. It lands on its one - pillar whatever pillar is open here. */} -
- -
- -
- {listedCurrent && ( - - )} - -
-
- - { - // Same veto as a switch: the jump into the new package unmounts the - // current pillar. Declining keeps the edits; the created package - // stays reachable from the list above. - if (beforeNavigate && !beforeNavigate()) return; - navigate(`/studio/${encodeURIComponent(id)}/data`); - }} - /> - -
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx new file mode 100644 index 00000000000..a004a9e9de4 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Studio top bar's left end (objectstack#36501): 「‹ Back to app」, the + * app's name, and the Studio mark. It is Studio's one way out to the running + * app; it replaced the Studio-home button, the package switcher and the + * top-right Open app. + * + * Where it goes, first match wins ({@link studioBackTarget}): + * + * 1. the app page the author came from — an app → Studio entry is an in-app + * navigation, and `ConsoleLayout` records every app page + * (`utils/appReturnPage.ts`); the name is that app's; + * 2. opened directly (a Studio URL in a new tab, a reload), the package's + * own published app, on its first screen; + * 3. a package with no published app, and the package-less scope: the + * console's default landing (`useHomePath`), with no app name. A draft + * app has no running front-end yet, so it counts as none. + * + * Leaving asks first when a pillar holds unsaved work, like every other + * header departure (`beforeNavigate`). + */ + +import * as React from 'react'; +import { ChevronLeft } from 'lucide-react'; +import type { I18nLabel } from '@objectstack/spec/ui'; +import { useHomePath } from '../../hooks/useHomePath.js'; +import { readAppReturnPage, type AppReturnPage } from '../../utils/appReturnPage.js'; +import { navItemLabelText } from '../metadata-admin/previews/navItemLabel.js'; +import { t, tFormat } from '../metadata-admin/i18n.js'; + +/** A published app of the open package. */ +export interface StudioAppTarget { + name: string; + label: I18nLabel; +} + +/** Where the back link goes, and the app it names (`null`: none). */ +export interface StudioBackTarget { + path: string; + appLabel: string | null; +} + +/** + * The back link's target. The app segment of the package's own app is the + * package id when the package ships one app (ADR-0048 option A, the canonical + * address); with several they share that id and it opens only the first, so + * the first is addressed by its name, the alias the console resolves + * (`appAddressSegment`). + */ +export function studioBackTarget({ + remembered, + packageId, + apps, + locale, + landingPath, +}: { + remembered: AppReturnPage | null; + packageId: string | null; + apps: readonly StudioAppTarget[]; + locale: string; + landingPath: string; +}): StudioBackTarget { + if (remembered) return { path: remembered.path, appLabel: remembered.label || remembered.app }; + const [first] = apps; + if (packageId !== null && first) { + const segment = encodeURIComponent(apps.length > 1 ? first.name : packageId); + return { path: `/apps/${segment}`, appLabel: navItemLabelText(first.label, locale) || first.name }; + } + return { path: landingPath, appLabel: null }; +} + +export function StudioBackToApp({ + packageId, + apps, + locale, + beforeNavigate, + navigate, +}: { + /** The open package, or `null` in the package-less scope. */ + packageId: string | null; + /** The package's published apps. */ + apps: readonly StudioAppTarget[]; + locale: string; + /** The header's unsaved-work veto: return false to stay in Studio. */ + beforeNavigate: () => boolean; + navigate: (path: string) => void; +}): React.ReactElement { + // Read once per visit: nothing in Studio is an app page, so the record + // cannot change while the author is here. + const [remembered] = React.useState(readAppReturnPage); + const homePath = useHomePath(); + const target = studioBackTarget({ remembered, packageId, apps, locale, landingPath: homePath }); + const title = target.appLabel + ? tFormat('engine.studio.backToAppTitle', locale, { app: target.appLabel }) + : t('engine.studio.backToAppTitleNoApp', locale); + + return ( +
+ + {target.appLabel && ( + <> + + {/* The one piece that gives way on a narrow bar. */} + + {target.appLabel} + + + )} + + + {t('engine.studio.mark', locale)} + +
+ ); +} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx index c3507d0a3d0..45ae7e115ca 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx @@ -37,13 +37,16 @@ */ import '@testing-library/jest-dom/vitest'; +// The surface's reach loads `@objectstack/lint` lazily; pay that load during +// collection, not inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; // Module scope as well as in the `vi.mock` factory below: the cold transform is paid // during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). import '@object-ui/components'; import { render, screen, fireEvent, cleanup, waitFor, within, act } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom'; const PKG = 'com.acme.app'; const PKG_B = 'com.beta.app'; @@ -216,6 +219,25 @@ import { PagePreview } from '../metadata-admin/previews/PagePreview'; import { PageBlockInspector } from '../metadata-admin/inspectors/PageBlockInspector'; import { PageDefaultInspector } from '../metadata-admin/inspectors/PageDefaultInspector'; import { readFields } from '../metadata-admin/previews/object-fields-io'; +import { confirmUnsavedLeave } from '../../chrome/unsavedEdits'; + +/** + * A door to another package that leaves the surface mounted, asking first + * when a pillar holds unsaved work: the shell seam's question, the one the + * contributed rows' doors ask (`useOpenContributor`). The package switcher + * was these tests' door until objectstack#36501 removed it. + */ +function PackageDoor({ to }: { to: string }) { + const navigate = useNavigate(); + return ( + - - ) : null, - }; -}); - -const mockClient = { - list: vi.fn(async () => []), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (_t: string, name: string) => ({ effective: { name } })), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ loading: false, error: null, entries: [] }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); - -// Rail siblings / docks irrelevant to the top bar — keep the render light. -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { StudioDesignSurface } from './StudioDesignSurface'; - -// jsdom ships neither of these; useIsMobile / useIsWideViewport and the Radix -// popover's floating-ui measurement need them. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -/** What `GET /api/v1/packages` answers on the SUCCESS path: `sendOk` wraps the - * handler's `{ packages, total }` as `{ success: true, data }`. */ -const listOk = (packages: unknown[]) => ({ - ok: true, - status: 200, - json: async () => ({ success: true, data: { packages, total: packages.length } }), -}); - -/** The ADR-0112 failure envelope, as `sendError` / `sendThrownError` write it. */ -const listFailure = (status: number, code: string, message: string) => ({ - ok: false, - status, - json: async () => ({ success: false, error: { code, message } }), -}); - -/** What the SNAPSHOT read answers — reassigned per case after the sheet is - * open, so the sheet always opens on `preAction` and only the refresh differs. - * A thrown value here stands for a `fetch` that rejects with no response. */ -let snapshotResponse: unknown = listOk([postAction]); -/** Raw-`fetch` calls to the bare packages endpoint — `fetchFullPackage`. */ -let snapshotFetches = 0; - -beforeEach(() => { - fetchPackagesMock.mockReset(); - toastError.mockReset(); - snapshotFetches = 0; - snapshotResponse = listOk([postAction]); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - if (String(input) === '/api/v1/packages') { - snapshotFetches += 1; - if (snapshotResponse instanceof Error) throw snapshotResponse; - return snapshotResponse; - } - // The pending-drafts counter and the automation status probe. - return { ok: true, status: 200, json: async () => [] }; - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function LocationProbe() { - return
{useLocation().pathname}
; -} - -const trigger = () => screen.getByTestId('studio-pkg-chip'); -const where = () => screen.getByTestId('location').textContent; -const sheet = () => screen.queryByTestId('pkg-sheet'); -/** The one shared sonner id — one outage across this surface is one toast. */ -const toastIdOf = (call: number) => - (toastError.mock.calls[call]?.[1] as { id?: string } | undefined)?.id; - -/** - * Open the lifecycle sheet the way the author does — switcher trigger → - * "Package info & settings" — on the PRE-ACTION record, and hand back its - * "a lifecycle action ran" button. Every case shares this drive, so the only - * difference between the pins is what the snapshot refresh answers. - */ -async function openLifecycleSheet(): Promise { - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID)]); - snapshotResponse = listOk([preAction]); - render( - - - - } /> - } /> - - , - ); - await waitFor(() => expect(trigger()).toHaveAttribute('data-pkg-list-state', 'loaded')); - fireEvent.click(trigger()); - fireEvent.click(await screen.findByText('Package info & settings')); - const open = await screen.findByTestId('pkg-sheet'); - // The sheet really is showing the pre-action record — the thing the defect - // then leaves on screen. - expect(open).toHaveAttribute('data-managed-id', PACKAGE_ID); - expect(open).toHaveAttribute('data-managed-status', 'active'); - toastError.mockReset(); - return screen.getByTestId('lifecycle-ran'); -} - -/** Fire the lifecycle action with the HEAD succeeding, so anything reported - * afterwards is unambiguously the TAIL's. */ -function lifecycleActionRuns(button: HTMLElement): void { - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID)]); - fireEvent.click(button); -} - -describe('Studio managed-snapshot refresh — a failed refresh is not a current record (#7907)', () => { - describe('§1 a 503 SERVICE_UNAVAILABLE envelope on the refresh', () => { - it('REPORTS it, through this file\'s existing objectui#7368 channel', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listFailure(503, 'SERVICE_UNAVAILABLE', 'Internal server error'); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - // The 5xx band withholds the producer's prose, so the code is the only - // discriminating word and travels with the generic message — inside a - // sentence that names what the author can SEE happen (their panel went). - expect(toastError.mock.calls[0][0]).toBe( - `Package ${PACKAGE_ID} could not be refreshed after that change — closing the panel rather than showing the pre-change record as current. Internal server error (SERVICE_UNAVAILABLE)`, - ); - expect(toastIdOf(0)).toBe('studio-package-list'); - // ⛔ One channel, not two: one failure, one report. - expect(toastError).toHaveBeenCalledTimes(1); - }); - - it('no longer presents the PRE-ACTION record as current', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listFailure(503, 'SERVICE_UNAVAILABLE', 'Internal server error'); - lifecycleActionRuns(lifecycle); - - // The sheet derives its lifecycle VERB from this record, so leaving it - // open over a snapshot known to be pre-action re-arms the author with - // the button they just pressed. - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - }); - - it('stays a DEGRADATION: the Studio, the top bar and the list are untouched', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listFailure(503, 'SERVICE_UNAVAILABLE', 'Internal server error'); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - // ⛔ No eviction and no throw (objectui#7368 / objectui#7821): a snapshot - // that could not be read is not evidence of anything about the package. - expect(where()).toBe(START_PATH); - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument(); - // The HEAD succeeded, so the list is current and still says so. - expect(trigger()).toHaveAttribute('data-pkg-list-state', 'loaded'); - // Still a working trigger — the failure took nothing else down. - fireEvent.click(trigger()); - expect(await screen.findByText('Packages (apps)')).toBeInTheDocument(); - }); - }); - - describe('§2 the 401 / 403 band — an expired session, and the capability gate', () => { - it('403 FORBIDDEN: the server\'s own sentence reaches the author', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listFailure( - 403, - 'FORBIDDEN', - 'Reading packages requires the `studio.access` or `setup.access` capability.', - ); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - expect(toastError.mock.calls[0][0]).toContain( - 'Reading packages requires the `studio.access` or `setup.access` capability. (FORBIDDEN)', - ); - expect(toastIdOf(0)).toBe('studio-package-list'); - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - }); - - it('401 UNAUTHENTICATED: reported, and the stale record is not left current', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listFailure(401, 'UNAUTHENTICATED', 'Authentication required'); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - expect(toastError.mock.calls[0][0]).toContain('Authentication required (UNAUTHENTICATED)'); - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - }); - }); - - describe('§3 a non-JSON error body — the second shape on this path', () => { - it('names the status instead of a JSON syntax error', async () => { - // A proxy's HTML 502/504: `res.json()` rejects. This is the ONE arm the - // pre-objectui#7881 code could reach at all — and this catch swallowed - // it just the same. - const lifecycle = await openLifecycleSheet(); - snapshotResponse = { - ok: false, - status: 502, - json: async () => { - throw new SyntaxError("Unexpected token '<', \"\"... is not valid JSON"); - }, - }; - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - expect(toastError.mock.calls[0][0]).toContain('HTTP 502'); - expect(toastError.mock.calls[0][0]).not.toContain('Unexpected token'); - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - }); - }); - - describe('§4 no response at all — the transport itself rejects', () => { - it('reports the transport error and does not leave the stale record current', async () => { - // Offline / DNS / connection reset: `fetch` rejects, so there is no - // `res.ok` to read and no envelope to quote. Reachable on this arm - // precisely because it runs right after a mutating action. - const lifecycle = await openLifecycleSheet(); - snapshotResponse = new TypeError('Failed to fetch'); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - expect(toastError.mock.calls[0][0]).toContain('Failed to fetch'); - expect(toastIdOf(0)).toBe('studio-package-list'); - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - }); - }); - - describe('§5 a SUCCESSFUL refresh whose list no longer contains the package', () => { - it('says so — `fresh === null` was as silent as the swallowed throw', async () => { - // The read succeeded, so there is no caught error to format; the package - // is simply gone. `openManage` refuses to OPEN on this (objectui#7881) - // and says so with this key — the tail now refuses to KEEP it open, with - // the same sentence. - const lifecycle = await openLifecycleSheet(); - // The HEAD must not decide deletion itself, or the tail never runs: it - // fails, so `list === null` draws no inference (objectui#7821). - fetchPackagesMock.mockRejectedValue(new Error('Service Unavailable')); - snapshotResponse = listOk([]); - fireEvent.click(lifecycle); - - await waitFor(() => - expect( - toastError.mock.calls.some((c) => String(c[0]).includes('is not in the installed list')), - ).toBe(true), - ); - const missing = toastError.mock.calls.find((c) => - String(c[0]).includes('is not in the installed list'), - ); - expect(missing?.[0]).toBe( - `Package ${PACKAGE_ID} is not in the installed list — it may have been deleted or uninstalled elsewhere.`, - ); - expect((missing?.[1] as { id?: string } | undefined)?.id).toBe('studio-package-list'); - await waitFor(() => expect(sheet()).not.toBeInTheDocument()); - // ⛔ Reporting is not inferring: no eviction is added here (objectui#7821). - expect(where()).toBe(START_PATH); - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument(); - }); - - it('ONE outage that rejects both halves is still ONE toast', async () => { - // The head and the tail read the same endpoint, so a single outage - // rejects both — which is exactly why both report on the shared sonner - // id. Sonner UPDATES a toast that already carries the id. - const lifecycle = await openLifecycleSheet(); - fetchPackagesMock.mockRejectedValue(new Error('Service Unavailable')); - snapshotResponse = listFailure(503, 'SERVICE_UNAVAILABLE', 'Internal server error'); - fireEvent.click(lifecycle); - - await waitFor(() => expect(toastError).toHaveBeenCalledTimes(2)); - expect(toastIdOf(0)).toBe('studio-package-list'); - expect(toastIdOf(1)).toBe('studio-package-list'); - // The head's report is the list's; the tail's is the snapshot's. - expect(toastError.mock.calls[0][0]).toBe('Service Unavailable'); - expect(toastError.mock.calls[1][0]).toContain('could not be refreshed after that change'); - }); - }); - - /** - * ⭐ The negative controls. These pass with the fix REVERTED, which is what - * proves the pins above are not restating an existing assertion — and they - * are what a degenerate "just close the sheet" fix cannot pass. - */ - describe('§6 negative control — a genuinely successful refresh', () => { - it('updates the sheet in place, exactly as before', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listOk([postAction]); - lifecycleActionRuns(lifecycle); - - // The whole point of the tail: the disable the author just fired shows - // immediately. ⛔ A fix that closed the sheet unconditionally dies here. - await waitFor(() => expect(sheet()).toHaveAttribute('data-managed-status', 'disabled')); - expect(sheet()).toHaveAttribute('data-managed-enabled', 'false'); - expect(sheet()).toHaveAttribute('data-managed-id', PACKAGE_ID); - }); - - it('reports nothing — a success is not an outage', async () => { - const lifecycle = await openLifecycleSheet(); - snapshotResponse = listOk([postAction]); - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(sheet()).toHaveAttribute('data-managed-status', 'disabled')); - expect(toastError).not.toHaveBeenCalled(); - }); - - it('reads the BARE-ARRAY body the same endpoint also serves', async () => { - // `root = data.data ?? data` — the reader accepts the wrapped envelope - // and a bare array, and this card changes neither. - const lifecycle = await openLifecycleSheet(); - snapshotResponse = { ok: true, status: 200, json: async () => [postAction] }; - lifecycleActionRuns(lifecycle); - - await waitFor(() => expect(sheet()).toHaveAttribute('data-managed-status', 'disabled')); - expect(toastError).not.toHaveBeenCalled(); - }); - - it('a REAL deletion still evicts, unchanged (the head\'s decision — objectui#7821)', async () => { - // The list came back successfully WITHOUT the package: that is the one - // evidence of deletion, it belongs to the head, and the tail never runs. - const lifecycle = await openLifecycleSheet(); - fetchPackagesMock.mockResolvedValue([]); - const before = snapshotFetches; - fireEvent.click(lifecycle); - - expect(await screen.findByTestId('home-page')).toBeInTheDocument(); - expect(where()).toBe('/home'); - expect(snapshotFetches).toBe(before); - expect(toastError).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowChip-12611.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowChip-12611.test.tsx deleted file mode 100644 index f0a5ed56aba..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowChip-12611.test.tsx +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12611 — the shell header's package chip on a narrow header. At - * 1024 px the chip read "Hot… 🔒 Read-only ▾": a viewport-keyed 180 px cap - * gave the lock and the word objectui#12453 added the room, and the name - * kept three letters. Now the chip's room is the header's package column - * (a container), the cap is the chip's own, and the chip gives way in order: - * the "Read-only" word first (the lock stays), then the name truncates. The - * whole name, the posture and what the chip does are in its tooltip. - * - * jsdom has no layout: the pull request carries the browser readings (the - * chip's visible text at 1024 and 1280 px). This file pins the contract that - * produces them: the DOM order, which part carries the truncating and the - * hiding classes, the container, and the tooltip. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; - -const PACKAGE_ID = 'app.objectstack.hotcrm'; -const NAME = 'HotCRM'; - -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn(), dismiss: vi.fn() }, - Toaster: () => null, -})); - -const mockClient = { - list: vi.fn(async () => []), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (_t: string, name: string) => ({ effective: { name } })), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ loading: false, error: null, entries: [] }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); - -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { StudioDesignSurface } from './StudioDesignSurface'; -import { t } from '../metadata-admin/i18n'; -import { STUDIO_HEADER_PACKAGE_COLUMN, STUDIO_PKG_READONLY_WORD } from './studio-tokens'; - -const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); - -function servePackage(writable: boolean) { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => - String(input) === '/api/v1/packages' - ? answer({ success: true, data: { packages: [{ manifest: { id: PACKAGE_ID, name: NAME }, writable }] } }) - : answer([]), - ), - ); -} - -function renderData() { - render( - - - } /> - - , - ); -} - -beforeEach(() => { - vi.stubGlobal('matchMedia', (query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, - })); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('the package chip on a narrow header (objectui#12611)', () => { - it('reads the name first; the lock stays and only the word carries the hiding class', async () => { - servePackage(false); - renderData(); - const header = screen.getByTestId('studio-shell-header'); - const readOnly = await within(header).findByTestId('studio-pkg-readonly'); - const chip = within(header).getByTestId('studio-pkg-chip'); - - // The chip's text starts with the whole name. - expect(chip.textContent?.startsWith(NAME)).toBe(true); - const name = chip.querySelector('[data-slot="pkg-name"]') as HTMLElement; - expect(name).toHaveTextContent(NAME); - expect(name).toHaveClass('truncate'); - - // Order: the name, then the lock and the word, then the chevron. - const parts = Array.from(chip.children); - expect(parts.indexOf(name)).toBeLessThan(parts.indexOf(readOnly)); - expect(parts.indexOf(readOnly)).toBe(parts.length - 2); - - // The lock is the posture's part that stays: outside the folding word. - const word = readOnly.querySelector('[data-slot="pkg-readonly-word"]') as HTMLElement; - expect(word).toHaveTextContent(t('engine.studio.pkg.readonly', 'en')); - expect(word).toHaveClass(...STUDIO_PKG_READONLY_WORD.split(' ')); - expect(STUDIO_PKG_READONLY_WORD).toBe('hidden @min-[300px]:inline'); - const lock = readOnly.querySelector('svg'); - expect(lock).not.toBeNull(); - expect(word.contains(lock)).toBe(false); - expect(readOnly).toHaveClass('shrink-0'); - // objectui#12453's reason stays the posture's own title. - expect(readOnly).toHaveAttribute('title', t('engine.studio.pkg.readonlyHint', 'en')); - }); - - it('the room is the header column’s, never the viewport’s: a container column and a cap of the chip’s own', async () => { - servePackage(false); - renderData(); - const header = screen.getByTestId('studio-shell-header'); - await within(header).findByTestId('studio-pkg-readonly'); - const chip = within(header).getByTestId('studio-pkg-chip'); - - const column = header.children[0] as HTMLElement; - expect(column.contains(chip)).toBe(true); - expect(column).toHaveClass(STUDIO_HEADER_PACKAGE_COLUMN); - expect(STUDIO_HEADER_PACKAGE_COLUMN).toBe('@container'); - expect(chip).toHaveClass('min-w-0', 'max-w-[280px]'); - // No breakpoint variant sizes the chip. - expect(chip.className).not.toMatch(/(^|\s)(sm|md|lg|xl|2xl):/); - // The native title moved into the tooltip: one tooltip, not two. - expect(chip).not.toHaveAttribute('title'); - }); - - it('the tooltip holds the whole name, the posture and what the chip does', async () => { - servePackage(false); - renderData(); - const header = screen.getByTestId('studio-shell-header'); - await within(header).findByTestId('studio-pkg-readonly'); - await userEvent.setup().hover(within(header).getByTestId('studio-pkg-chip')); - const tip = await screen.findByRole('tooltip'); - expect(tip).toHaveTextContent(NAME); - expect(tip).toHaveTextContent(t('engine.studio.pkg.readonlyHint', 'en')); - expect(tip).toHaveTextContent(t('engine.studio.pkg.switchTitle', 'en')); - }); - - it('CONTROL — a writable package: the tooltip names the package and says nothing of read-only', async () => { - servePackage(true); - renderData(); - const header = screen.getByTestId('studio-shell-header'); - const chip = within(header).getByTestId('studio-pkg-chip'); - await vi.waitFor(() => expect(chip).toHaveAttribute('data-pkg-list-state', 'loaded')); - await userEvent.setup().hover(chip); - const tip = await screen.findByRole('tooltip'); - expect(tip).toHaveTextContent(NAME); - expect(tip).not.toHaveTextContent(t('engine.studio.pkg.readonlyHint', 'en')); - expect(within(header).queryByTestId('studio-pkg-readonly')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx index e0591e0ede9..05c00d8aba0 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx @@ -23,7 +23,7 @@ import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import { cleanup, render, screen, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; const PACKAGE_ID = 'app.n4rr'; @@ -150,7 +150,7 @@ describe('Studio shell header below and above 640 px (objectui#12509)', () => { const nav = within(header).getByTestId('studio-pillar-nav'); expect(nav).toHaveClass(...STUDIO_HEADER_PILLAR_NAV.split(' ')); - // Source order stays package · switcher · actions; only `order-last` moves the switcher below `sm`. + // Source order stays back link · switcher · actions; only `order-last` moves the switcher below `sm`. const groups = Array.from(header.children); expect(groups).toHaveLength(3); expect(groups[1]).toBe(nav); @@ -168,12 +168,8 @@ describe('Studio shell header below and above 640 px (objectui#12509)', () => { ); } - // The chip is the piece that gives way on a tight row. - const chip = await waitFor(() => { - const el = within(header).getByTestId('studio-pkg-chip'); - expect(el).toHaveAttribute('data-pkg-list-state', 'loaded'); - return el; - }); - expect(chip).toHaveClass('min-w-0'); + // objectstack#36501 — the left group is 「‹ Back to app」, and it gives way + // on a tight row (the app's name truncates inside it). + expect(within(groups[0] as HTMLElement).getByTestId('studio-back')).toHaveClass('min-w-0'); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noAppPackageLabel-12718.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noAppPackageLabel-12718.test.tsx index 80172358487..57cbcb84285 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noAppPackageLabel-12718.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noAppPackageLabel-12718.test.tsx @@ -2,8 +2,7 @@ /** * objectui#12718 — the Interfaces pillar of a package that has no app yet - * names the package by its display name, the one the Studio top bar prints, - * and never by its id. + * names the package by its display name, never by its id. * * `InterfacesPillar` seeded its app label with `packageId`, and the app * resolve returned on the no-app branch before it ever set one, so the rail @@ -20,8 +19,11 @@ */ import '@testing-library/jest-dom/vitest'; +// The surface's reach loads `@objectstack/lint` lazily; pay that load during +// collection, not inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; const PACKAGE_ID = 'com.qa.recheck'; @@ -102,12 +104,16 @@ function pillarText(): string { return text; } -/** Waits for the top bar to have the package list in hand. */ +/** + * Waits for the surface to have the package list in hand: the list read was + * made, and its answer has had a turn to land. (The package switcher's + * `data-pkg-list-state` said this until objectstack#36501 removed it.) + */ async function packageListLoaded() { - const header = screen.getByTestId('studio-shell-header'); - await waitFor(() => - expect(within(header).getByTestId('studio-pkg-chip')).toHaveAttribute('data-pkg-list-state', 'loaded'), - ); + await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledWith('/api/v1/packages', expect.anything())); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); } beforeEach(() => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx index 302b5a883e2..cf063ffbc3b 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx @@ -21,7 +21,7 @@ import '@testing-library/jest-dom/vitest'; // The source under test reaches `import('@objectstack/lint')`: paid here, at collection, never inside a test's clock. import '@objectstack/lint'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'; import * as React from 'react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; @@ -119,6 +119,19 @@ afterEach(() => { vi.unstubAllGlobals(); }); +/** + * The package list has answered and the surface has read it: the list read + * was made, and its answer has had a turn to land. (The package switcher's + * `data-pkg-list-state` said this until the switcher was removed, + * objectstack#36501.) + */ +async function listAnswered(fetchMock: ReturnType): Promise { + await waitFor(() => expect(packageListReads(fetchMock)).toBeGreaterThan(0), { timeout: 8000 }); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); +} + describe('Studio: a package id no package has renders "package not found" (objectstack#26708)', () => { it.each(['data', 'automations', 'interfaces', 'access'])('%s: not found, no pillars, no package actions', async (pillar) => { const fetchMock = servePackages(); @@ -144,35 +157,25 @@ describe('Studio: a package id no package has renders "package not found" (objec }); it('CONTROL — a listed package renders its builder', async () => { - servePackages(); + const fetchMock = servePackages(); renderAt(`/studio/${PACKAGE_ID}/data`); - const header = screen.getByTestId('studio-shell-header'); - await waitFor(() => - expect(within(header).getByTestId('studio-pkg-chip')).toHaveAttribute('data-pkg-list-state', 'loaded'), - ); + await listAnswered(fetchMock); expect(screen.queryByTestId('studio-package-not-found')).toBeNull(); // The four pillars and, objectstack#28561, the "All metadata" area. expect(within(screen.getByTestId('studio-pillar-nav')).getAllByRole('link')).toHaveLength(5); }); - it('CONTROL — a kernel package the switcher hides is installed, never "not found"', async () => { - servePackages(); + it('CONTROL — a kernel package the Studio landing hides is installed, never "not found"', async () => { + const fetchMock = servePackages(); renderAt(`/studio/${KERNEL_ID}/data`); - const header = screen.getByTestId('studio-shell-header'); - await waitFor(() => - expect(within(header).getByTestId('studio-pkg-chip')).toHaveAttribute('data-pkg-list-state', 'loaded'), - ); + await listAnswered(fetchMock); expect(screen.queryByTestId('studio-package-not-found')).toBeNull(); }); it('CONTROL — a package list that failed to load leaves the builder as it was', async () => { const fetchMock = servePackages({ fail: true }); renderAt(`/studio/${PHANTOM}/data`); - await waitFor(() => expect(packageListReads(fetchMock)).toBeGreaterThan(0)); - await waitFor(() => - expect(within(screen.getByTestId('studio-shell-header')).getByTestId('studio-pkg-chip')) - .toHaveAttribute('data-pkg-list-state', 'failed'), - ); + await listAnswered(fetchMock); expect(screen.queryByTestId('studio-package-not-found')).toBeNull(); expect(within(screen.getByTestId('studio-pillar-nav')).getAllByRole('link')).toHaveLength(5); }); @@ -217,12 +220,9 @@ describe('Studio: no copilot beside a package that is not there (objectstack#326 }); it('CONTROL — a listed package keeps its copilot', async () => { - servePackages(); + const fetchMock = servePackages(); renderAt(`/studio/${PACKAGE_ID}/data`); - await waitFor(() => - expect(within(screen.getByTestId('studio-shell-header')).getByTestId('studio-pkg-chip')) - .toHaveAttribute('data-pkg-list-state', 'loaded'), - ); + await listAnswered(fetchMock); expect(screen.queryByTestId('studio-package-not-found')).toBeNull(); expect(screen.getByTestId('studio-chat-dock')).toBeInTheDocument(); }); @@ -234,12 +234,9 @@ describe('Studio: no copilot beside a package that is not there (objectstack#326 expect(screen.queryByTestId('injected-copilot')).toBeNull(); cleanup(); - servePackages(); + const listedFetch = servePackages(); renderAt(`/studio/${PACKAGE_ID}/data`, } />); - await waitFor(() => - expect(within(screen.getByTestId('studio-shell-header')).getByTestId('studio-pkg-chip')) - .toHaveAttribute('data-pkg-list-state', 'loaded'), - ); + await listAnswered(listedFetch); expect(screen.getByTestId('injected-copilot')).toBeInTheDocument(); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.oneSurface-28572.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.oneSurface-28572.test.tsx index 5830036f8c9..e9edc509ef6 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.oneSurface-28572.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.oneSurface-28572.test.tsx @@ -510,19 +510,10 @@ describe('the Data rail lists the pair’s objects with the base’s (objectstac }); }); -describe('the package switcher and the pair’s URLs (objectstack#28572)', () => { - it('the switcher gives the pair no row, and names it under its base', async () => { - renderAt(`/studio/${BASE}/interfaces`); - await waitFor(() => expect(document.querySelector('[data-slot="pkg-name"]')).toHaveTextContent('HotCRM'), { timeout: 8000 }); - fireEvent.click(document.querySelector('[data-slot="pkg-name"]')!.closest('button')!); - await waitFor(() => expect(screen.getAllByTestId('studio-switcher-row').length).toBeGreaterThan(0), { timeout: 8000 }); - const rows = screen.getAllByTestId('studio-switcher-row'); - expect(rows.map((r) => r.getAttribute('data-package'))).toEqual([BASE, ADDON]); - expect(within(rows[0]!).getByTestId('studio-switcher-pair')).toHaveTextContent( - tFormat('engine.studio.pkg.withPair', 'en', { pair: PAIR }), - ); - }); - +describe('the pair’s URLs (objectstack#28572)', () => { + // The package switcher's case (the pair has no row, named under its base) + // left with the switcher, objectstack#36501; the Studio landing's cards + // fold the pair the same way (`foldCustomizationPairs`). it('a pillar URL of the pair lands on the base’s surface, its query kept', async () => { renderAt(`/studio/${encodeURIComponent(PAIR)}/interfaces?surface=dashboard:wins`); await waitFor(() => expect(screen.getByTestId('location').textContent).toMatch(new RegExp(`^/studio/${BASE}/interfaces\\?`))); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.openApp-34593.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.openApp-34593.test.tsx deleted file mode 100644 index 324fec265f6..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.openApp-34593.test.tsx +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#34593 — the Studio workbench and the running app, both ways. - * - * 1. The header offers "Open app", the mirror of the app bar's - * Edit app: from the object in focus (`?surface=object:`, the - * target Edit app hands Studio) it lands on that object's list in the - * app; with no surface in focus it lands on the app's home. A package - * with several published apps offers a choice; a package whose only app - * is still a draft offers nothing (no running front-end yet). - * 2. The package switcher offers business packages only (ADR-0016 §3.8 — - * "you cannot author into a kernel package"): the kernel rows the - * registry half serves with a flat `scope` are hidden too, while the list - * keeps them tagged `kernel` for the app → Studio entry gate. No toggle - * shows them. - * - * The REAL `StudioDesignSurface` and metadata client over a fetch stub that - * serves the package list, the package's apps and objects. The running app is - * a route that prints where the author landed. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; -// The surface's reach loads `@objectstack/lint` lazily; pay that load during -// collection, not inside a case's clocked window (`check:test-source-alias`). -import '@objectstack/lint'; - -const OWN = 'com.example.sales'; -const FLAT_KERNEL = 'sys.env-artifact-cache'; -const MANIFEST_KERNEL = 'com.objectstack.plugin-auth'; - -const srv = vi.hoisted(() => ({ - apps: [] as Array>, - appDrafts: [] as Array>, -})); - -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); -vi.mock('sonner', () => ({ - toast: { warning: vi.fn(), error: vi.fn(), success: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, - Toaster: () => null, -})); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { StudioDesignSurface } from './StudioDesignSurface'; -import { studioOpenAppPath } from './StudioOpenApp'; -import { offeredPackages } from './PackageSwitcher'; -import { parsePackages } from './packages-io'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -function json(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); -} - -/** `GET /api/v1/packages` as both producers serve it: the durable half nested, the registry half flat. */ -const PACKAGE_LIST = { - success: true, - data: [ - { id: FLAT_KERNEL, name: 'Environment artifact cache', scope: 'system', writable: false }, - { manifest: { id: MANIFEST_KERNEL, name: 'Authentication', scope: 'system' }, writable: false }, - { manifest: { id: OWN, name: 'Sales', namespace: 'sales', version: '0.1.0' }, writable: true }, - ], -}; - -const SALES_APP = { name: 'sales', label: 'Sales', navigation: [{ id: 'nav_opp', type: 'object', objectName: 'opportunity' }] }; -const SERVICE_APP = { name: 'service', label: 'Service desk', navigation: [] }; - -beforeEach(() => { - srv.apps = [SALES_APP]; - srv.appDrafts = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = new URL(String(input), 'http://localhost'); - const path = url.pathname; - if (path === '/api/v1/packages') return json(PACKAGE_LIST); - if (path === '/api/v1/meta/_drafts') { - return json({ drafts: url.searchParams.get('type') === 'app' ? srv.appDrafts : [] }); - } - if (path === '/api/v1/meta/app') return json(srv.apps); - if (path === '/api/v1/meta/object') { - return json([ - { name: 'opportunity', label: 'Opportunity', fields: {} }, - { name: 'account', label: 'Account', fields: {} }, - ]); - } - if (path.endsWith('/layers')) return json({ code: null, overlay: null, overlayScope: null, effective: null }); - if (/^\/api\/v1\/meta\/[^/]+\/[^/]+$/.test(path)) return json({}, 404); - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function RunningApp() { - const location = useLocation(); - return

{location.pathname}

; -} - -function renderAt(entry: string) { - return render( - - - } /> - } /> - - , - ); -} - -const header = () => screen.getByTestId('studio-shell-header'); - -describe('Open app returns from the workbench to the running app (objectstack#34593)', () => { - it('from the Opportunity in focus, Open app lands back on the Opportunity list', async () => { - renderAt(`/studio/${OWN}/data?surface=object:opportunity`); - const button = await within(header()).findByTestId('studio-open-app', undefined, { timeout: 8000 }); - expect(button).toHaveAccessibleName('Open app'); - fireEvent.click(button); - expect(await screen.findByTestId('running-app')).toHaveTextContent(`/apps/${OWN}/opportunity`); - }); - - it('with no surface in focus, it lands on the app home', async () => { - renderAt(`/studio/${OWN}/access`); - fireEvent.click(await within(header()).findByTestId('studio-open-app', undefined, { timeout: 8000 })); - expect(await screen.findByTestId('running-app')).toHaveTextContent(new RegExp(`^/apps/${OWN.replace(/\./g, '\\.')}$`)); - }); - - it('a package with several apps offers a choice, and each lands under its own address', async () => { - srv.apps = [SALES_APP, SERVICE_APP]; - renderAt(`/studio/${OWN}/data?surface=object:opportunity`); - fireEvent.click(await within(header()).findByTestId('studio-open-app', undefined, { timeout: 8000 })); - const menu = await screen.findByTestId('studio-open-app-menu'); - const rows = within(menu).getAllByTestId('studio-open-app-row'); - expect(rows.map((r) => r.textContent)).toEqual(['Sales', 'Service desk']); - fireEvent.click(rows[1]!); - expect(await screen.findByTestId('running-app')).toHaveTextContent('/apps/service/opportunity'); - }); - - it('a package whose only app is a draft offers no Open app (nothing runs yet)', async () => { - srv.apps = []; - srv.appDrafts = [{ name: 'sales', label: 'Sales', type: 'app' }]; - renderAt(`/studio/${OWN}/data`); - await waitFor(() => expect(within(header()).getByTestId('studio-pkg-chip')).toHaveAttribute('data-pkg-list-state', 'loaded'), { - timeout: 8000, - }); - // The draft app is resolved (the header's create-app slot reads it), and still no way out is drawn. - await waitFor(() => expect(within(header()).queryByRole('button', { name: /Create app/ })).toBeNull()); - expect(within(header()).queryByTestId('studio-open-app')).toBeNull(); - }); - - it('the path mirrors the app bar\'s Edit app targets: object list, interface page, else app home', () => { - const one = [{ name: 'sales', label: 'Sales' }]; - const two = [...one, { name: 'service', label: 'Service' }]; - expect(studioOpenAppPath(OWN, one, 'sales', { type: 'object', name: 'opportunity' })).toBe(`/apps/${OWN}/opportunity`); - expect(studioOpenAppPath(OWN, one, 'sales', { type: 'dashboard', name: 'pipeline' })).toBe(`/apps/${OWN}/dashboard/pipeline`); - expect(studioOpenAppPath(OWN, one, 'sales', { type: 'flow', name: 'close_won' })).toBe(`/apps/${OWN}`); - expect(studioOpenAppPath(OWN, one, 'sales', null)).toBe(`/apps/${OWN}`); - expect(studioOpenAppPath(OWN, two, 'service', { type: 'object', name: 'opportunity' })).toBe('/apps/service/opportunity'); - }); -}); - -describe('the package switcher offers business packages only (objectstack#34593, ADR-0016 §3.8)', () => { - it('no kernel row in the menu — neither the manifest-scoped one nor the one served with a flat `scope`', async () => { - renderAt(`/studio/${OWN}/access`); - const chip = await within(header()).findByTestId('studio-pkg-chip', undefined, { timeout: 8000 }); - await waitFor(() => expect(chip).toHaveAttribute('data-pkg-list-state', 'loaded'), { timeout: 8000 }); - fireEvent.click(chip); - const menu = await screen.findByRole('dialog'); - const rows = within(menu).getAllByTestId('studio-switcher-row').map((r) => r.getAttribute('data-package')); - expect(rows).toEqual([OWN]); - expect(within(menu).queryByText(FLAT_KERNEL)).toBeNull(); - expect(within(menu).queryByText(/show system/i)).toBeNull(); - }); - - it('CONTROL — the list itself keeps the flat kernel row, tagged, for the app → Studio entry gate', () => { - const listed = parsePackages(PACKAGE_LIST); - expect(listed.map((p) => [p.id, p.kernel ?? false])).toEqual([ - [FLAT_KERNEL, true], - [OWN, false], - ]); - expect(offeredPackages(listed)?.map((p) => p.id)).toEqual([OWN]); - expect(offeredPackages(null)).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageDeletionInference.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageDeletionInference.test.tsx deleted file mode 100644 index d3097b7395c..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageDeletionInference.test.tsx +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#7821 — `onManageChanged` read a FAILED package-list refresh as - * "the package was deleted" and evicted the author out of the Studio. - * - * The callback runs after every package lifecycle action fired from the - * `PackageDetailSheet` (disable / duplicate / delete / publish / manifest - * edit). It refreshed the list into a LOCAL `list`, initialised to `[]`, and - * swallowed the rejection under a comment reading "keep the stale list" — - * true of the `pkgs` state, which is simply not written, and false of the - * local, which stayed `[]`. Three lines later `!list.some((p) => p.id === - * managedId)` was therefore UNCONDITIONALLY true after a failure, so the code - * took the branch labelled `// Deleted`; when the managed package was the one - * under the editor it navigated away, and `list[0]` being `undefined` made - * the destination `/home`. - * - * Net effect: one transient `GET /api/v1/packages` failure — a 503 from the - * durable half, a network blip, an auth expiry — threw the author out of the - * editor, with no toast and no confirmation, while the package was still - * there. That is the sibling defect of objectui#7368 escalated: not a - * swallowed failure, but a swallowed failure that then decides the OPPOSITE - * of the truth. - * - * These pins are behavioural, and there are three of them because the fix has - * two ways to be wrong: - * 1. a FAILED refresh causes NO navigation (the defect), and - * 2. it is still REPORTED, through this file's existing objectui#7368 - * posture (`formatMetadataError` on the shared sonner id, recorded so - * the trigger reads `failed`) — a fix must not buy pin 1 with silence; - * 3. a REAL deletion — the list comes back successfully WITHOUT the package - * — still navigates. ⛔ Not optional: pinning only 1 and 2 lets the fix - * degrade into "never navigate", which strands the author on a package - * that no longer exists. - * - * Where a REAL deletion lands while other packages remain changed with - * objectui#11784 (triage comment 6041966855: "return to `/studio` after a - * delete"): the Studio landing. It used to open `list[0]`, whichever package - * the list started with, so a delete read as "Studio moved me into another - * app". The "sibling survives" case says the new destination; every other case - * here is unchanged and stays as a control, the two "nothing left" cases - * included (that arm is still objectui#7373's declared home). - * - * ⛔ The `.catch` is deliberately still a `.catch` (one 503 must not take the - * Studio down — objectui#7368's ruling) and there is deliberately still no - * retry (count / backoff / what-after-giving-up are unruled policy). - */ - -import '@testing-library/jest-dom/vitest'; -// The source under test reaches `import('@objectstack/lint')`: paid here, at collection, never inside a test's clock. -import '@objectstack/lint'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; -import React from 'react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; -import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; - -const PACKAGE_ID = 'app.b2r4'; -const SIBLING_ID = 'app.other'; -const START_PATH = `/studio/${PACKAGE_ID}/interfaces`; - -const row = (id: string) => ({ id, name: id, writable: true, namespace: id.split('.')[1] }); - -// The package list refresh is the system under test — every case installs its -// own resolution/rejection for the refresh that `onManageChanged` performs. -const fetchPackagesMock = vi.fn(); -vi.mock('./packages-io', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, fetchPackages: (...args: unknown[]) => fetchPackagesMock(...args) }; -}); - -// The report channel (objectui#7368's posture). Captured rather than rendered -// so a pin can read both the message and the shared sonner id. -const toastError = vi.fn(); -vi.mock('sonner', () => ({ - toast: { - error: (...args: unknown[]) => toastError(...args), - success: vi.fn(), - info: vi.fn(), - dismiss: vi.fn(), - }, - Toaster: () => null, -})); - -/** - * The lifecycle sheet, stubbed down to the one thing this file is about: the - * `onChanged` callback it fires after a lifecycle action. Driving the real - * sheet's delete/disable/publish buttons would test THOSE, and the defect is - * in the surface's reaction, which every one of them reaches the same way. - */ -vi.mock('../metadata-admin/PackagesPage', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - PackageDetailSheet: ({ - pkg, - open, - onChanged, - }: { - pkg: { manifest?: { id?: string } } | null; - open: boolean; - onChanged: () => void | Promise; - }) => - open ? ( -
- -
- ) : null, - }; -}); - -const mockClient = { - list: vi.fn(async () => []), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (_t: string, name: string) => ({ effective: { name } })), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ loading: false, error: null, entries: [] }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); - -// Rail siblings / docks irrelevant to the top bar — keep the render light. -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { StudioDesignSurface } from './StudioDesignSurface'; -import { RecentItemsProvider, useRecentItems } from '../../context/RecentItemsProvider'; - -// jsdom ships neither of these; useIsMobile / useIsWideViewport and the Radix -// popover's floating-ui measurement need them. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -/** Raw-`fetch` calls to the bare packages endpoint — that is `fetchFullPackage`, - * the managed-snapshot refresh `onManageChanged` performs AFTER the - * deletion decision. Counting it gives the negative pin a positive event to - * wait for: the callback provably ran past the branch that used to navigate. */ -let snapshotFetches = 0; - -beforeEach(() => { - fetchPackagesMock.mockReset(); - toastError.mockReset(); - snapshotFetches = 0; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String(input); - if (url === '/api/v1/packages') { - snapshotFetches += 1; - // What `fetchFullPackage` reads: the full installed record. - return { ok: true, json: async () => [{ manifest: { id: PACKAGE_ID, name: PACKAGE_ID } }] }; - } - // The pending-drafts counter and the automation status probe. - return { ok: true, json: async () => [] }; - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function LocationProbe() { - return
{useLocation().pathname}
; -} - -/** - * The app list the eviction's destination resolves against (objectui#7373). - * `undefined` mounts the surface with no metadata context — every case written - * before that card, for which `useHomePath()` answers the launcher. - */ -function withMetadata( - apps: MetadataContextValue['apps'] | undefined, - children: React.ReactNode, -) { - if (!apps) return <>{children}; - const value: MetadataContextValue = { - apps, - objects: [], dashboards: [], reports: [], pages: [], - loading: false, error: null, - refresh: async () => {}, invalidate: () => {}, ensureType: async () => [], - getItem: async () => null, getItemsByType: () => [], getTypeStatus: () => 'ready', - }; - return {children}; -} - -/** objectstack#32615 — the ids the REAL recent store holds, on every render. */ -function RecentStoreProbe() { - const { recentItems } = useRecentItems(); - return
{recentItems.map((i) => i.id).join(' ')}
; -} - -function renderSurface(apps?: MetadataContextValue['apps'], recentStore = false) { - const tree = ( - - - {recentStore && } - {withMetadata( - apps, - - } /> - } /> - } /> - } /> - , - )} - - ); - return render(recentStore ? {tree} : tree); -} - -const trigger = () => screen.getByTestId('studio-pkg-chip'); -const where = () => screen.getByTestId('location').textContent; - -/** - * Open the lifecycle sheet the way the author does — switcher trigger → - * "Package info & settings" — and hand back its "a lifecycle action ran" - * button. Every case shares this drive, so the ONLY difference between the - * pins below is what the refresh does. - */ -async function openLifecycleSheet( - initial = [row(PACKAGE_ID)], - apps?: MetadataContextValue['apps'], - recentStore = false, -): Promise { - fetchPackagesMock.mockResolvedValue(initial); - renderSurface(apps, recentStore); - await waitFor(() => expect(trigger()).toHaveAttribute('data-pkg-list-state', 'loaded')); - fireEvent.click(trigger()); - fireEvent.click(await screen.findByText('Package info & settings')); - const sheet = await screen.findByTestId('pkg-sheet'); - expect(sheet).toHaveAttribute('data-managed-id', PACKAGE_ID); - toastError.mockReset(); - return screen.getByTestId('lifecycle-ran'); -} - -describe('Studio package lifecycle — a failed refresh is not a deletion (#7821)', () => { - it('FAILED refresh: the author is NOT evicted — no navigation at all', async () => { - const lifecycle = await openLifecycleSheet(); - const before = snapshotFetches; - - // The refresh that follows the lifecycle action rejects. - fetchPackagesMock.mockRejectedValue(new Error('Service Unavailable')); - fireEvent.click(lifecycle); - - // Wait until the callback has SETTLED, whichever way it goes: either it - // navigated (the defect — the `/home` route mounts) or it went on to - // refresh the managed snapshot (what follows the deletion decision). Both - // arms are observable, so the assertions below are not racing a pending - // navigation, and the red lands on the eviction itself rather than on a - // timeout. - await waitFor(() => - expect(snapshotFetches > before || screen.queryByTestId('home-page') !== null).toBe(true), - ); - - expect(where()).toBe(START_PATH); - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument(); - // Still in the editor, still on the same package. - expect(trigger()).toHaveTextContent(PACKAGE_ID); - }); - - it('FAILED refresh: the failure is still REPORTED through this file\'s own posture', async () => { - const lifecycle = await openLifecycleSheet(); - - fetchPackagesMock.mockRejectedValue(new Error('Service Unavailable')); - fireEvent.click(lifecycle); - - // objectui#7368's channel, reused: the error's own message, on the one - // shared sonner id, so an outage that rejects several call sites is one - // toast rather than a stack. - await waitFor(() => expect(toastError).toHaveBeenCalled()); - expect(toastError.mock.calls[0][0]).toBe('Service Unavailable'); - expect((toastError.mock.calls[0][1] as { id?: string } | undefined)?.id).toBe('studio-package-list'); - - // …and recorded, so the switcher stops presenting the now-stale list as - // though it were current. - await waitFor(() => expect(trigger()).toHaveAttribute('data-pkg-list-state', 'failed')); - // ⛔ Never a throw: the top bar is still a working trigger. - fireEvent.click(trigger()); - expect(await screen.findByText('Packages (apps)')).toBeInTheDocument(); - }); - - it('REAL deletion, nothing left: still navigates to /home (behaviour unchanged)', async () => { - const lifecycle = await openLifecycleSheet(); - - // The list came back — successfully — and the package is gone from it. - fetchPackagesMock.mockResolvedValue([]); - fireEvent.click(lifecycle); - - expect(await screen.findByTestId('home-page')).toBeInTheDocument(); - expect(where()).toBe('/home'); - // A successful refresh is not a failure: nothing was reported. - expect(toastError).not.toHaveBeenCalled(); - }); - - it('REAL deletion, nothing left, a DECLARED landing: evicts to it, not to the launcher (objectui#7373)', async () => { - // Same eviction as the case above — the only difference is that this - // deployment declares where home is. Pre-#7373 the destination was the - // `/home` literal either way, which on a control plane drops the author - // into the environment launcher. - const lifecycle = await openLifecycleSheet([row(PACKAGE_ID)], [ - { name: 'cloud_control', label: 'Cloud', isDefault: true }, - { name: 'account', label: 'Account' }, - ]); - - fetchPackagesMock.mockResolvedValue([]); - fireEvent.click(lifecycle); - - expect(await screen.findByTestId('declared-landing')).toBeInTheDocument(); - expect(where()).toBe('/apps/cloud_control'); - expect(toastError).not.toHaveBeenCalled(); - }); - - it('REAL deletion, a sibling survives: returns to the Studio landing, not into the sibling (objectui#11784)', async () => { - // The card's measured complaint: after the delete, Studio landed on - // another package (showcase), the list's first entry, instead of the - // Studio landing. Triage 6041966855: "return to `/studio` after a delete". - const lifecycle = await openLifecycleSheet([row(PACKAGE_ID), row(SIBLING_ID)]); - - fetchPackagesMock.mockResolvedValue([row(SIBLING_ID)]); - fireEvent.click(lifecycle); - - expect(await screen.findByTestId('studio-landing')).toBeInTheDocument(); - expect(where()).toBe('/studio'); - expect(screen.queryByTestId('home-page')).not.toBeInTheDocument(); - }); - - it('successful refresh, package still there: no navigation, and an earlier failure clears', async () => { - const lifecycle = await openLifecycleSheet(); - - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID)]); - const before = snapshotFetches; - fireEvent.click(lifecycle); - - await waitFor(() => expect(snapshotFetches).toBeGreaterThan(before)); - expect(where()).toBe(START_PATH); - expect(trigger()).toHaveAttribute('data-pkg-list-state', 'loaded'); - }); -}); - -describe('Studio package lifecycle — a deletion here drops the package from "Recently viewed" (objectstack#32615)', () => { - /** The key `RecentItemsProvider` hydrates from with no signed-in user. */ - const STORAGE_KEY = 'objectui-recent-items'; - const visit = (id: string) => ({ - id: `package:${id}`, - type: 'package', - name: id, - href: `/studio/${encodeURIComponent(id)}`, - visitedAt: '2026-11-12T08:00:00.000Z', - }); - const stored = () => screen.getByTestId('recent-store').textContent; - - beforeEach(() => { - localStorage.setItem(STORAGE_KEY, JSON.stringify([visit(PACKAGE_ID), visit(SIBLING_ID)])); - }); - afterEach(() => { - localStorage.clear(); - }); - - it('REAL deletion: the deleted package leaves the store, the sibling stays', async () => { - const lifecycle = await openLifecycleSheet([row(PACKAGE_ID), row(SIBLING_ID)], undefined, true); - expect(stored()).toBe(`package:${PACKAGE_ID} package:${SIBLING_ID}`); - - fetchPackagesMock.mockResolvedValue([row(SIBLING_ID)]); - fireEvent.click(lifecycle); - - expect(await screen.findByTestId('studio-landing')).toBeInTheDocument(); - expect(stored()).toBe(`package:${SIBLING_ID}`); - const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]') as Array<{ id: string }>; - expect(persisted.map((e) => e.id)).toEqual([`package:${SIBLING_ID}`]); - }); - - it('CONTROL — a FAILED refresh is not a deletion: the store keeps the entry', async () => { - const lifecycle = await openLifecycleSheet([row(PACKAGE_ID), row(SIBLING_ID)], undefined, true); - const before = snapshotFetches; - - fetchPackagesMock.mockRejectedValue(new Error('Service Unavailable')); - fireEvent.click(lifecycle); - - await waitFor(() => expect(snapshotFetches).toBeGreaterThan(before)); - expect(stored()).toBe(`package:${PACKAGE_ID} package:${SIBLING_ID}`); - }); - - it('CONTROL — the package still listed after the action: the store keeps the entry', async () => { - const lifecycle = await openLifecycleSheet([row(PACKAGE_ID), row(SIBLING_ID)], undefined, true); - const before = snapshotFetches; - - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID), row(SIBLING_ID)]); - fireEvent.click(lifecycle); - - await waitFor(() => expect(snapshotFetches).toBeGreaterThan(before)); - expect(stored()).toBe(`package:${PACKAGE_ID} package:${SIBLING_ID}`); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx index e21b40adefe..eff1f02b66e 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageLessFlows-11553.test.tsx @@ -24,7 +24,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; const SHOWCASE = 'com.example.showcase'; const NODES = [ @@ -207,10 +207,17 @@ function LocationProbe() { return
{`${pathname}${search}`}
; } +/** A route change into the package-less scope, the surface left mounted. */ +function OrgScopeDoor() { + const navigate = useNavigate(); + return - - ) : null, - }; -}); - -const mockClient = { - list: vi.fn(async () => []), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async (_t: string, name: string) => ({ effective: { name } })), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => undefined), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ loading: false, error: null, entries: [] }), - }; -}); - -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); - -// Rail siblings / docks irrelevant to the top bar — keep the render light. -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { StudioDesignSurface } from './StudioDesignSurface'; - -// jsdom ships neither; useIsMobile / useIsWideViewport and the Radix popover's -// floating-ui measurement need them. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -/** The success shape: `sendOk` wraps the handler's `{ packages, total }`. */ -const listOk = (packages: unknown[]) => ({ - ok: true, - status: 200, - json: async () => ({ success: true, data: { packages, total: packages.length } }), -}); - -/** - * A failure envelope exactly as `sendError` writes it — `{ code, message, - * ...extra }` under `error`. `extra` is spread verbatim so a case can put a - * marked text on the body, omit `message` entirely, or send a non-string mark. - */ -const listFailure = (status: number, body: Record) => ({ - ok: false, - status, - json: async () => ({ success: false, error: body }), -}); - -/** The generic sentence the 5xx prose withhold substitutes (`INTERNAL_ERROR_MESSAGE`). */ -const GENERIC = 'Internal server error'; -/** A producer's marked text: what `userMessage` carries, written for the author. */ -const MARKED = 'Publishing is temporarily unavailable. Nothing was changed.'; - -/** The response `fetchFullPackage` receives; each case installs its own. */ -let lookupResponse: unknown = listOk([{ manifest: { id: PACKAGE_ID, name: PACKAGE_ID } }]); - -beforeEach(() => { - fetchPackagesMock.mockReset(); - toastError.mockReset(); - lookupResponse = listOk([{ manifest: { id: PACKAGE_ID, name: PACKAGE_ID } }]); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - // `fetchPackages` is mocked above, so this URL is `fetchFullPackage`'s alone. - if (String(input) === '/api/v1/packages') return lookupResponse; - // The pending-drafts counter and the automation status probe. - return { ok: true, status: 200, json: async () => [] }; - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -const trigger = () => screen.getByTestId('studio-pkg-chip'); -/** The one shared sonner id — one outage across this surface is one toast. */ -const toastId = () => (toastError.mock.calls[0]?.[1] as { id?: string } | undefined)?.id; - -/** - * Drive the FIRST caller the way the author does — switcher trigger → - * "Package info & settings" — so the only difference between the cases is what - * the lookup answers. - */ -async function clickManage(): Promise { - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID)]); - render( - - - } /> - - , - ); - await waitFor(() => expect(trigger()).toHaveAttribute('data-pkg-list-state', 'loaded')); - fireEvent.click(trigger()); - fireEvent.click(await screen.findByText('Package info & settings')); -} - -/** - * Wait until `openManage` has SETTLED whichever way it goes — it either - * reported or opened the sheet — so the assertions are not racing a pending - * promise and a red lands on the defect rather than on a timeout. - */ -async function settled(): Promise { - await waitFor(() => - expect(toastError.mock.calls.length > 0 || screen.queryByTestId('pkg-sheet') !== null).toBe(true), - ); -} - -/** What the author is shown, once the lookup answered `body` at `status`. */ -async function reportedFor(status: number, body: Record): Promise { - lookupResponse = listFailure(status, body); - await clickManage(); - await settled(); - expect(toastError).toHaveBeenCalled(); - return toastError.mock.calls[0][0] as string; -} - -describe('Studio package lookup — a producer-marked userMessage reaches the author (#7938)', () => { - /** - * ⭐ GREEN with the fix reverted, and load-bearing for that reason. The - * unmarked refusal is the overwhelmingly common case, and this is the pin - * that stops "prefer `userMessage`" from being implemented as "read - * `userMessage` instead of `message`" — which would have blanked every - * refusal the platform serves today. - */ - describe('§1 `message` only — the unmarked refusal, unchanged', () => { - it('renders the diagnostic prose with its code, byte for byte as before', async () => { - expect( - await reportedFor(403, { - code: 'FORBIDDEN', - message: 'Reading packages requires the `studio.access` or `setup.access` capability.', - }), - ).toBe('Reading packages requires the `studio.access` or `setup.access` capability. (FORBIDDEN)'); - expect(toastId()).toBe('studio-package-list'); - }); - - it('does not open the sheet — objectui#7881\'s refusal still holds', async () => { - await reportedFor(503, { code: 'SERVICE_UNAVAILABLE', message: GENERIC }); - expect(screen.queryByTestId('pkg-sheet')).not.toBeInTheDocument(); - }); - }); - - /** - * The marked text is the ONLY prose on the body. `sendError` requires a - * `message` argument, so this shape reaches a browser as a body whose - * `message` is absent or non-string (a hand-written intermediary, a - * generation that predates the field) — and the pre-fix ladder answered it - * with the bare status, discarding a sentence it was holding. - */ - describe('§2 `userMessage` only — the mark is the only prose', () => { - it('renders the marked text instead of the bare status', async () => { - expect(await reportedFor(503, { code: 'SERVICE_UNAVAILABLE', userMessage: MARKED })).toBe( - `${MARKED} (SERVICE_UNAVAILABLE)`, - ); - }); - - it('⛔ never falls back to `HTTP ` when a mark is present', async () => { - const shown = await reportedFor(503, { code: 'SERVICE_UNAVAILABLE', userMessage: MARKED }); - expect(shown).not.toBe('HTTP 503'); - expect(shown).toContain(MARKED); - }); - - /** - * ⭐ GREEN with the fix reverted, deliberately — measured, not predicted: - * this asserts the CHANNEL (objectui#7368's posture — one outage, one - * toast, one id), not the words, and reverting changes only the words. It - * is here because a fix that reached for a second reporting channel to - * carry the marked text would pass every words-pin above and fail here. - */ - it('reports once, on the shared sonner id', async () => { - await reportedFor(500, { code: 'INTERNAL_ERROR', userMessage: MARKED }); - expect(toastError).toHaveBeenCalledTimes(1); - expect(toastId()).toBe('studio-package-list'); - }); - }); - - /** - * ⭐ The case that motivated the card, and the one the framework pins on its - * own side (`package-door-user-message.test.ts` §4): a sanitised 500 whose - * `message` is the generic sentence and whose `userMessage` rode through. - */ - describe('§3 both — the 5xx band, where the loss was visible', () => { - it('shows the MARKED sentence, not the generic substitution', async () => { - expect(await reportedFor(500, { code: 'INTERNAL_ERROR', message: GENERIC, userMessage: MARKED })).toBe( - `${MARKED} (INTERNAL_ERROR)`, - ); - }); - - it('⛔ the generic sentence does not also appear — it is displaced, not appended', async () => { - const shown = await reportedFor(500, { code: 'INTERNAL_ERROR', message: GENERIC, userMessage: MARKED }); - expect(shown).not.toContain(GENERIC); - }); - - /** - * ⛔ NOT scoped to 5xx. The producing door applies no status condition to - * this channel — "a marked text is the producer's deliberate statement to - * the caller at any status" — so a consumer that honoured it in one band - * only would re-create on the reading end the divergence that door refused - * to create on the writing end. - */ - it('prefers the mark in the 4xx band too, where `message` was never withheld', async () => { - expect( - await reportedFor(409, { - code: 'RESOURCE_CONFLICT', - message: 'version 1.2.0 already published for app.b2r4', - userMessage: 'That version is already published. Bump the version and retry.', - }), - ).toBe('That version is already published. Bump the version and retry. (RESOURCE_CONFLICT)'); - }); - }); - - /** - * `code` is orthogonal to which prose won: it is appended to whichever - * sentence is rendered, and it never rescues a body that carried no prose at - * all. The last two cases are the reason the read is a typed `string` check - * rather than a truthiness one. - */ - describe('§4 how `code` composes across the three combinations', () => { - it('a marked body with NO code renders the bare sentence', async () => { - expect(await reportedFor(503, { message: GENERIC, userMessage: MARKED })).toBe(MARKED); - }); - - it('neither prose, code present — still the status, and the code is NOT it', async () => { - // Unchanged: a code alone is not a sentence to show an author. - expect(await reportedFor(503, { code: 'SERVICE_UNAVAILABLE' })).toBe('HTTP 503'); - }); - - it('a non-string `userMessage` is not a mark — it falls through to `message`', async () => { - expect(await reportedFor(500, { code: 'INTERNAL_ERROR', message: GENERIC, userMessage: 42 })).toBe( - `${GENERIC} (INTERNAL_ERROR)`, - ); - }); - - it('an empty-string `userMessage` is not a mark either', async () => { - // The producer's `declaredUserMessage` already applies this rule, so an - // empty mark should never ship — the reader does not depend on that. - expect(await reportedFor(500, { code: 'INTERNAL_ERROR', message: GENERIC, userMessage: '' })).toBe( - `${GENERIC} (INTERNAL_ERROR)`, - ); - }); - }); - - /** - * ⭐ The read is SHARED. `fetchFullPackage` has two callers — `openManage` - * (§1-§4 above) and the TAIL of `onManageChanged`, the managed-snapshot - * refresh objectui#7907 taught to report and close. Fixing the reader fixes - * both; this drives the second so that is shown rather than assumed. - */ - describe('§5 the second caller — the managed-snapshot refresh (objectui#7907\'s tail)', () => { - it('carries the marked sentence into the refresh-failed report, and closes the panel', async () => { - lookupResponse = listOk([{ manifest: { id: PACKAGE_ID, name: PACKAGE_ID } }]); - await clickManage(); - expect(await screen.findByTestId('pkg-sheet')).toHaveAttribute('data-managed-id', PACKAGE_ID); - toastError.mockReset(); - - // A lifecycle action runs; the snapshot refresh meets a marked 500. - fetchPackagesMock.mockResolvedValue([row(PACKAGE_ID)]); - lookupResponse = listFailure(500, { code: 'INTERNAL_ERROR', message: GENERIC, userMessage: MARKED }); - fireEvent.click(screen.getByTestId('lifecycle-ran')); - - await waitFor(() => expect(toastError).toHaveBeenCalled()); - const shown = toastError.mock.calls[0][0] as string; - // objectui#7907's key, carrying the server's own words inside it — ⛔ one - // mechanism, not a second reporting channel for this card. - expect(shown).toContain(`Package ${PACKAGE_ID} could not be refreshed after that change`); - expect(shown).toContain(`${MARKED} (INTERNAL_ERROR)`); - expect(shown).not.toContain(GENERIC); - expect(toastId()).toBe('studio-package-list'); - await waitFor(() => expect(screen.queryByTestId('pkg-sheet')).not.toBeInTheDocument()); - }); - }); - - /** - * ⭐ Negative controls — GREEN with the fix reverted. Without them a "fix" - * that reported on every read, or stopped opening the sheet at all, would - * satisfy every assertion above. - */ - describe('§6 negative control — a successful lookup is untouched', () => { - it('opens the sheet on the real package and reports nothing', async () => { - lookupResponse = listOk([{ manifest: { id: PACKAGE_ID, name: PACKAGE_ID }, writable: true }]); - await clickManage(); - - expect(await screen.findByTestId('pkg-sheet')).toHaveAttribute('data-managed-id', PACKAGE_ID); - expect(toastError).not.toHaveBeenCalled(); - }); - - it('a non-JSON error body still names the status (objectui#7881 §4)', async () => { - lookupResponse = { - ok: false, - status: 502, - json: async () => { - throw new SyntaxError("Unexpected token '<', \"\"... is not valid JSON"); - }, - }; - await clickManage(); - await settled(); - expect(toastError.mock.calls[0][0]).toBe('HTTP 502'); - }); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx index 65c2d5bb964..46f4a194ed6 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx @@ -3,16 +3,17 @@ /** * Studio header — unsaved-changes guard on SPA navigation (objectui#2600). * - * The pillar links, the Home button and the PackageSwitcher are pure - * react-router client navigation, so the editors' `beforeunload` guard never + * The pillar links and 「‹ Back to app」 (objectstack#36501; it replaced the + * Home button and the PackageSwitcher, whose package switch the shell seam + * below still guards for every other door) are pure react-router client + * navigation, so the editors' `beforeunload` guard never * fires; before this guard existed they unmounted a dirty pillar silently and * discarded its unsaved edits. Pillars now mirror their dirty state up to the * surface (same `onDirtyChange` contract as the Access rail guard, PR #2588), * and every header-driven departure gates on a native confirm: * * • dirty + pillar switch → confirm; cancel keeps the pillar and its edits, - * • dirty + Home → same confirm; cancel stays, confirm leaves, - * • dirty + package switch → same confirm, + * • dirty + 「‹ Back to app」 → same confirm; cancel stays, confirm leaves, * • dirty OWD overview rows + pillar switch → same confirm (the pillar * folds the overview's report into the same bit, objectui#2600 follow-up), * • clean navigation never prompts, @@ -187,6 +188,7 @@ async function renderSurfaceOnAccess() { } /> } /> + } /> , ); @@ -315,55 +317,28 @@ describe('Studio header — unsaved pillar edits guard (#2600)', () => { matrixEditSurvived(); }); - it('gates the Studio home button; cancel stays, confirm returns to the Studio landing', async () => { + it('gates 「‹ Back to app」; cancel stays, confirm leaves Studio (objectstack#36501)', async () => { await renderSurfaceOnAccess(); dirtyTheMatrix(); confirmSpy.mockReturnValueOnce(false); - fireEvent.click(screen.getByTitle('Studio home')); + fireEvent.click(screen.getByTestId('studio-back-to-app')); expect(confirmSpy).toHaveBeenCalledTimes(1); expect(inSetHeader().getByTitle('set_a')).toBeInTheDocument(); matrixEditSurvived(); confirmSpy.mockReturnValueOnce(true); - fireEvent.click(screen.getByTitle('Studio home')); - expect(await screen.findByTestId('studio-landing-page')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('studio-back-to-app')); + expect(await screen.findByTestId('left-studio')).toBeInTheDocument(); }); - it('gates a package switch; cancel keeps the edits in place', async () => { - await renderSurfaceOnAccess(); - dirtyTheMatrix(); - - // Open the switcher (its label resolves once fetchPackages lands). - fireEvent.click(await screen.findByRole('button', { name: /App A/ })); - const other = await screen.findByRole('button', { name: /App B/ }); - - confirmSpy.mockReturnValueOnce(false); - fireEvent.click(other); - expect(confirmSpy).toHaveBeenCalledTimes(1); - expect(inSetHeader().getByTitle('set_a')).toBeInTheDocument(); - matrixEditSurvived(); - - // Confirming jumps to the other package (header re-labels; matrix reloads). - fireEvent.click(await screen.findByRole('button', { name: /App A/ })); - confirmSpy.mockReturnValueOnce(true); - fireEvent.click(await screen.findByRole('button', { name: /App B/ })); - expect(confirmSpy).toHaveBeenCalledTimes(2); - await waitFor(() => - expect(screen.getByTestId('studio-pkg-chip')).toHaveTextContent('App B'), - ); - }); - - it('never prompts a clean package switch', async () => { + it('never prompts a clean 「‹ Back to app」', async () => { await renderSurfaceOnAccess(); - fireEvent.click(await screen.findByRole('button', { name: /App A/ })); - fireEvent.click(await screen.findByRole('button', { name: /App B/ })); + fireEvent.click(screen.getByTestId('studio-back-to-app')); expect(confirmSpy).not.toHaveBeenCalled(); - await waitFor(() => - expect(screen.getByTestId('studio-pkg-chip')).toHaveTextContent('App B'), - ); + expect(await screen.findByTestId('left-studio')).toBeInTheDocument(); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx index f3dac2f2714..70407670da3 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx @@ -1,10 +1,10 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#12453 — a read-only package says so twice, the same in every - * pillar: a lock and "Read-only" in the app chip, muted, its title the - * package's read-only sentence; and one read-only mark at the right of the - * item header. With no item open (these pillars list nothing here) the mark + * objectui#12453 — a read-only package says so, the same in every pillar: one + * read-only mark at the right of the item header. (The app chip's lock and + * "Read-only" left the top bar with the chip, objectstack#36501: the bar's left + * end is 「‹ Back to app」 now, and the item header's mark is the posture.) With no item open (these pillars list nothing here) the mark * reads "Read-only" and links nowhere: it offers an overlay only for an open * item whose type accepts one (#27356 row 13, `StudioReadOnlyLink.overlay-27356`). * @@ -15,8 +15,11 @@ */ import '@testing-library/jest-dom/vitest'; +// The surface's reach loads `@objectstack/lint` lazily; pay that load during +// collection, not inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; const PACKAGE_ID = 'app.r34d'; @@ -110,18 +113,11 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('Studio read-only posture: the app chip and the item header link (objectui#12453)', () => { - it.each(PILLARS)('%s: the chip carries a muted lock, the header one read-only mark that links nowhere', async (pillar) => { +describe('Studio read-only posture: the item header link (objectui#12453)', () => { + it.each(PILLARS)('%s: the item header carries one read-only mark that links nowhere', async (pillar) => { servePackage(false); renderPillar(pillar); - const header = screen.getByTestId('studio-shell-header'); - const chip = await within(header).findByTestId('studio-pkg-readonly'); - expect(chip).toHaveTextContent(READ_ONLY); - expect(chip).toHaveAttribute('title', t('engine.studio.pkg.readonlyHint', 'en')); - expect(chip).toHaveClass('text-muted-foreground'); - expect(chip.className).not.toMatch(/amber/); - const links = await screen.findAllByTestId('studio-readonly-link'); expect(links).toHaveLength(1); expect(links[0]).toHaveTextContent(READ_ONLY); @@ -129,21 +125,18 @@ describe('Studio read-only posture: the app chip and the item header link (objec expect(links[0]).not.toHaveAttribute('href'); expect(links[0]).toHaveAttribute('title'); - expect(visibleReadOnlyCount()).toBe(2); + expect(visibleReadOnlyCount()).toBe(1); }); it.each(PILLARS)('CONTROL — %s on a writable package: no lock, no link', async (pillar) => { servePackage(true); renderPillar(pillar); - const header = screen.getByTestId('studio-shell-header'); - await waitFor(() => - expect(within(header).getByTestId('studio-pkg-chip')).toHaveAttribute( - 'data-pkg-list-state', - 'loaded', - ), - ); - expect(screen.queryByTestId('studio-pkg-readonly')).toBeNull(); + // Settled: the package list has answered, and the surface has read it. + await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledWith('/api/v1/packages', expect.anything())); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); expect(screen.queryByTestId('studio-readonly-link')).toBeNull(); expect(visibleReadOnlyCount()).toBe(0); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index b8e19b0805a..5aa78a8d0fb 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -99,8 +99,8 @@ import { } from './flowGrouping.js'; import { StudioRefusalStrip } from './StudioRefusalStrip.js'; import { StudioNavItemInspector, StudioPicker } from './StudioNavItemInspector.js'; -import { PACKAGE_LIST_TOAST_ID, PackageSwitcher, STUDIO_LANDING_PATH } from './PackageSwitcher.js'; -import { StudioOpenApp, type StudioOpenAppTarget } from './StudioOpenApp.js'; +import { PACKAGE_LIST_TOAST_ID, STUDIO_LANDING_PATH } from './PackageSwitcher.js'; +import { StudioBackToApp, type StudioAppTarget } from './StudioBackToApp.js'; import { ContributedNavRows, InterfacesNavContributionsContext, @@ -219,7 +219,6 @@ import { Rocket, ChevronDown, Lock, - Home as HomeIcon, Shield, ShieldCheck, ShieldQuestion, @@ -829,7 +828,7 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re const ensurePair = React.useCallback(async (): Promise => (await ensurePairPackage()).packageId, [ensurePairPackage]); const baseLabel = pkgEntry?.id === packageId ? pkgEntry.name : (packageId ?? ''); - // objectui#2600 — the header's pillar links, Home button and PackageSwitcher + // objectui#2600 — the header's pillar links and its 「‹ Back to app」 link // are pure SPA client navigation, so the editors' `beforeunload` guard never // fires; a dirty pillar unmounts silently and its unsaved edits are gone // (Access matrix cells, Interfaces nav). Each pillar mirrors its dirty state @@ -1275,10 +1274,10 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re ? { id: publishNoneReasonId, text: t('engine.studio.publishNoneTitle', locale), testId: 'publish-none-reason' } : null; - // Builder → running-app bridge (Airtable's Launch): the builder edits the - // package (the design surface), the app is its published front-end. If this - // package ships a published app, the header offers Open app (`StudioOpenApp`, - // objectstack#34593), in the same tab, mirroring the app bar's Edit app. + // Builder → running-app bridge: the builder edits the package (the design + // surface), the app is its published front-end. The header's way back to it + // is 「‹ Back to app」 at the left (`StudioBackToApp`, objectstack#36501), in + // the same tab, mirroring the app bar's Edit app. const shellNavigate = useNavigate(); React.useEffect(() => { openAccessRef.current = () => { @@ -1295,13 +1294,14 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // order: the Automations rail orders its groups by it. Read off the same // app row as `packageApp`, so the pillar adds no read of its own. const [packageAppObjectOrder, setPackageAppObjectOrder] = React.useState([]); - // objectstack#34593 — the package's PUBLISHED apps, the header's Open app - // targets: a draft app has no running front-end to open. Read off the same - // list as `packageApp`. - const [publishedApps, setPublishedApps] = React.useState([]); + // objectstack#36501 — the package's PUBLISHED apps, where the header's + // 「‹ Back to app」 goes when the author did not come from an app: a draft + // app has no running front-end to open. Read off the same list as + // `packageApp`. + const [publishedApps, setPublishedApps] = React.useState([]); // Create app (package has no app yet): create a draft `app` item — the - // published front-end's on-ramp. The button flips to Open app after the - // package publish. + // published front-end's on-ramp. After the package publish, 「‹ Back to + // app」 names it. const [appCreating, setAppCreating] = React.useState(false); const [appBusy, setAppBusy] = React.useState(false); const [appErr, setAppErr] = React.useState(null); @@ -1641,37 +1641,24 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re
- {/* objectui#12459 — three columns: the package at the left, the - pillars centered, the package actions at the right. + {/* objectui#12459 — three columns: the way back to the app at the + left, the pillars centered, the package actions at the right. objectui#12509 — below `sm` the pillars take a second row of their own (`STUDIO_HEADER_PILLAR_NAV`), and on any row the - package chip is the piece that gives way. */} + app's name is the piece that gives way. */}
- {/* Never a dead end: walk back to the Studio landing - (objectui#12513), where the author picks the next package. - The console home stays one click away from there, through - the landing's own top bar. */} - -
- -
+ {/* objectstack#36501 — 「‹ Back to app」, the app's name and the + Studio mark: Studio's one way out, to the app page the author + came from. It replaced the Studio-home button, the package + switcher and the top-right Open app; a different package is + picked in the app, or on the Studio landing. */} +