Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: onboarding flow, the first four screens (#21599)
zchpeter95e31afc65fc
diff --git a/docs/design/onboarding-flow.md b/docs/design/onboarding-flow.mdindex a531b8cea1..b2ebc39b71 100644--- a/docs/design/onboarding-flow.md+++ b/docs/design/onboarding-flow.md@@ -1,6 +1,6 @@# Onboarding flow, the first four screens-Status: proposal · 2026-10-12 (revised 2026-10-13) · builds on the project home, [#21572] (merged)+Status: implemented in this PR, with stills in place of D9's animations · 2026-10-12 (revised 2026-10-14) · builds on the project home, [#21572] (merged)A new Cloud workspace opens on a setup wizard that asks for a goal and "who will use Bytebase withyou", then for your name, a workspace name, a first project and a sample-database checkbox. Until@@ -108,29 +108,33 @@ Rejected: today's order (goal and team first, then everything else on one screensecond screen, which invites people into an empty workspace.**D2 · Screen 1 is a confirmation, not a form.** Your name (optional, prefilled from the identity-provider or the email local part, left empty for alias-like local parts such as admin or info) and-the workspace name (required, prefilled from the email domain, "Peter's workspace" for public mail-domains). Continue is enabled on arrival, so the first click is the only click. Nine of the 42+provider or the email local part, left empty for local parts that name no person, such as admin,+it-support or a phone number) and the workspace name (required, prefilled from the email domain,+"Peter's workspace" for public mail domains, "My workspace" when the address names nobody either).+A public mail provider is recognized by its name, so its country domains count (yahoo.co.jp,+hotmail.co.uk). Continue is enabled on arrival, so the first click is the only click. Nine of the 42mandatory-state leavers never clicked anything, consistent with an OAuth redirect returning to atab nobody is looking at; a screen with nothing to decide is the cheapest first screen.-**D3 · Two goals, and a quieter third answer.** "Review and roll out a schema change" and "Query-data with guardrails" are the two cards, each with a one-line finish line under it: a change that-passed SQL review and rolled out to the database, and a query result from it. Under them sits a-lighter third answer, "Not sure yet, just exploring", which commits to neither; the project home and-the guide then put a query first, the quickest first result. Every product in the study that asks an-intent question lets the user decline it: PostHog has "Continue without choosing a goal", Metabase-"I'm not sure yet", and n8n and Greptile make the question optional. Here, 3 of 20 finishers left-the goal blank while it was optional, 2 of the leavers since it became required stalled on it with-Continue disabled, and the forced answer predicts the first action only weakly. An honest "not sure"-also makes the other two answers worth more as signals. It is drawn lighter than the cards so it-does not read as their peer, and its share is a number to watch. "Mark sensitive data" is removed as-a goal: masking guards querying rather than being a destination, and as an Enterprise feature it led-its choosers into a gate (1 of 9 acted). Every finish line is reachable on the free plan. Rejected:-a third equal card, and keeping the forced choice between two.+**D3 · Two goals, and a quieter third answer.** "Plan, review and roll out a database change" (a+schema change or a data fix) and "Query data with guardrails" are the two cards, each with a+one-line finish line under it: a change that passed SQL review and rolled out to the database, and a+query result from it. Under them sits a lighter third answer, "Not sure yet, just exploring", which+commits to neither; the project home and the guide then put a query first, the quickest first+result. Every product in the study that asks an intent question lets the user decline it: PostHog+has "Continue without choosing a goal", Metabase "I'm not sure yet", and n8n and Greptile make the+question optional. Here, 3 of 20 finishers left the goal blank while it was optional, 2 of the+leavers since it became required stalled on it with Continue disabled, and the forced answer+predicts the first action only weakly. An honest "not sure" also makes the other two answers worth+more as signals. It is drawn lighter than the cards so it does not read as their peer, and its share+is a number to watch. "Mark sensitive data" is removed as a goal: masking guards querying rather+than being a destination, and as an Enterprise feature it led its choosers into a gate (1 of 9+acted). Every finish line is reachable on the free plan. Rejected: a third equal card, and keeping+the forced choice between two.**D4 · The project is named where its database is chosen.** Screen 3 opens with the project name-(required, empty with example placeholder; the resource id derived from it, editable, collapsed)+(required on Cloud, optional on self-hosted (D12); empty with example placeholder; the resource id+derived from it, editable, collapsed)and one line of explanation, then "Database for <project>" with the two choices. The project existsto hold databases, so naming it beside them teaches by adjacency and removes the forward reference("the databases you add next...") that the workspace screen needed. Rejected: prefilling the name,@@ -160,7 +164,10 @@ from the Members page. The workspace write is what triggers those emails, so itinvited to a project they cannot open. A failure stays on screen 4 naming the step that failed, with"Try again", which runs Finish again without creating the project twice (D11); when the sample iswhat failed it also offers "Finish without the sample", which finishes as the own-instance choice-does. Today the wizard reports a finish even when the sample request fails and offers no retry.+does. The failure is reported there and nowhere else: Finish's calls do not also raise the product's+error toast. One failure leaves screen 4: a project ID the server will not take goes back to the+field it is about (D11). Today the wizard reports a finish even when the sample request fails and+offers no retry.Rejected: committing on screen 3, as an earlier draft had it. It made the team screen a point of noreturn with no Back, and needed a resume rule for an account that reloaded after the commit.@@ -172,18 +179,23 @@ control, which the UX contract keeps for view switches. It keys the guide's teaminvite field appears once a size above "Just me" is chosen, so "Just me" never comes with inviteesand a solo account, the majority, sees one question and Finish. The size is how many people will useBytebase, not how many are invited today, so the two numbers are not reconciled further. Emails are-chips: type one, press Enter, type the next; a pasted list splits and repeats are dropped; an-invalid entry, or the owner's own address, is shown struck through, is not sent and is not counted-on the button. Inviting is Cloud's: an invitation is an email, and only Cloud has an email service-at first run (Given). On Cloud the field reads "Invite teammates" and the button "Send N invites and-finish". On self-hosted the same field reads "Add members": Finish adds those addresses as workspace-members with the same roles and sends nothing, the line under the field says so and that each person-gets access once they have an account with that address, and the button reads "Add N members and-finish". Calling it an invitation there would promise an email that never arrives. There is no role-picker. An earlier draft offered a "Role in <project>" selector, which names Bytebase's project-roles to a user ten seconds into the product. Invitees are added as Workspace Member, and on the new-project as Project Developer and SQL Editor Read User, which together let them propose changes and-run read-only queries. One sentence says so, and roles are changed later in Members, where the names+chips: type one, press Enter, type the next; a pasted list splits at commas, semicolons and line+breaks, the full-width ones an input method types included, and repeats are dropped; a recipient+pasted from a mail client as `Ann Lee <[email protected]>` is its address, not three entries; a pasted+list takes the place of the text selected in the field, and text typed around it stays an entry of+its own; an invalid entry, or the owner's own address, is shown struck through, is not sent and is+not counted on the button. Text still in the field when the button is pressed is entered first, and+if it is not an address that press stops there, so the struck entry is seen before anything is sent.+Inviting is Cloud's: an invitation is an email, and only Cloud has an email service at first run+(Given). On Cloud the field reads "Invite teammates" and the button "Send N invites and finish".+Self-hosted asks the team size only. There, adding an address creates a member, and a member needs a+password the wizard has no place to set, so people are added afterwards where their account is+created. Calling it an invitation there would promise an email that never arrives. There is no role+picker.+An earlier draft offered a "Role in <project>" selector, which names Bytebase's project roles to a+user ten seconds into the product. Invitees are added as Workspace Member, and on the new project as+Project Developer and SQL Editor Read User, which together let them propose changes and run+read-only queries. One sentence says so, and roles are changed later in Members, where the namesmean something. On the own-instance path that sentence also says the project's databases appear oncethe instance is connected, because those invitees arrive first. Holding their invitations until thenwould need somewhere to hold them, which the 7 of 100 finishers on that path do not justify.@@ -191,7 +203,8 @@ Greptile asks a default role (Admin or Member); Linear, Neon and Metabase ask foRejected: the "Just me / My team" question (it only decided whether this screen appears, and thescreen is now always offered and one click to pass), the role selector, and the free-text email box.-**D8 · Finish lands on the project home, and the home puts the goal's step first.** The project home+**D8 · Finish lands on the project home, and the home puts the goal's step first.** A self-hosted+Finish without a project lands where the skip does (D12). The project home([#21572], on main since Oct 13) makes the project root a page of its own: a "Next step" band chosenfrom the project's state, above the user's open issues and the project's databases. Finish navigatesthere whichever database choice was made, as today's wizard already does. With "Connect my own@@ -211,85 +224,193 @@ no landing of its own. An earlier draft opened the goal's first action straighthighlighted "Connect instance" on the databases page; both are withdrawn, because the project homeis where the next step is chosen.-**D9 · The left panel is a story per screen, from bytebase.com's Rive files.** Screen 1 plays the-homepage hero (requests flowing into review); screen 2 swaps to the chosen goal's feature animation-(Change Review, or Dynamic Data Masking as the picture of a guardrail; the card's finish line does-not depend on it) the moment a card is pressed, and stays on the hero for "just exploring"; screen 3-draws a diagram from what the user typed-(the sample instance and its database flowing into the project name, or the user's own instance-joining after setup); screen 4 plays Access Controls, which is why no role is asked. The files-(`masthead`, `dcm-review`, `data-masking`, `iam`) and the `RivePlayer` wrapper exist in the-bytebase.com repository; the frontend is React, so the wrapper ports as is, with `rive.wasm`-self-hosted and the files lazy-loaded on the setup route only. The files have no state-machine-inputs and play autonomously; under reduced-motion the panel shows one frame. The rocket-illustration stays on sign-in and sign-up. Rejected for now: a constant stage (the panel teaches-nothing) and a live preview of the product being configured (strongest teaching, highest drift;-planned for screen 3 later).+**D9 · The left panel shows what each screen's answer is for.** Screen 1 previews the workspace+being named: a small Bytebase window with the workspace name in its header and the person setting it+up as its Workspace Admin, drawn from the answers as they are typed, so both names have a visible+use. Screen 2 keeps that preview until a goal is chosen, then shows the goal the moment its card is+pressed: the homepage hero (requests flowing through SQL lint, agent review and a reviewer) for the+change goal, a SQL statement above its result for the query goal, and for "just exploring" the+homepage's after-Bytebase diagram (people and agents reaching the databases through Bytebase),+redrawn narrower to fit the panel. The card's finish line does not depend on the picture. Screen 3+draws the workspace by its name holding the project as it is named, beside a dimmed second project,+with lines from the project to its instances: the first is the sample instance holding its database,+or the user's own instance, dashed, connected after setup; two more are dimmed. The sample is one+instance with one database on both deployments, so only one instance is drawn as real. A+self-hosted screen 3 left without a name draws the project dashed and no instances. Screen 4 returns+to screen 1's workspace window, since the team uses the whole workspace and an invitation is to the+workspace: the person setting it up, then each address listed as a Workspace Member, at most five+rows and "+N more"; while the team is bigger than "Just me", dimmed rows fill the rest. The access+the invitees get in the project is the line under the field. Workspace, project and instances are+the three words a new user meets next, and nothing else is drawn. The goal pictures sit on the hero's light background, and the query picture is a+frame of bytebase.com's Dynamic Data Masking file with its masking rows replaced by the statement, so+it shows a query rather than masking. The hero is a still frame of bytebase.com's Rive `masthead`+file, which a follow-up may play with the site's `RivePlayer` (`rive.wasm` self-hosted, the file+lazy-loaded on the setup route only, one frame under reduced motion); the query and exploring+pictures are composed for the panel and stay still. Every picture takes 70% of the panel's column,+never under 512px or over 800px, and never taller than the window; the drawn ones scale as one, so a+wide screen gets the same picture larger. The rocket illustration stays on sign-in and sign-up. Rejected: a constant stage+(the panel teaches nothing); the website's closing slogan, or its brand art alone, on screen 1+(decoration beside a form that already has its heading); for screen 3, a diagram of instance,+database and project as labelled boxes (it read as a lesson in three words at once); for screen 4,+the homepage's Access Controls (per-database access the wizard never sets) and the project's members+(the team spans every project, and self-hosted adds no one to it); the homepage's Change Review+file for the+change goal (its dark parts are made for the blue stage, and the hero tells the same story); and a+live preview of the whole product being configured (highest drift; screen 1's preview draws only the+two names it shows).**D10 · Instrumentation.** Each Continue emits `workspace setup screen continued` on the click, withthe screen number and the answers so far (goal, project named, source). No event carries a name, anemail address or a project name. `workspace setup submitted` still fires when Finish succeeds, nowcarrying the goal, the source, the team size and the invite count, and gains `result=failed` with-`failure_stage` (names, project, sample, invitees). No client event can be the record, though: the-17 lost finishes lost every custom event after the wizard mounted, and 13 accounts since Sep 11 were-never tracked at all. The record stays with the backend, as the Cloud usage dashboard's exporter-already reads it: "finished setup" from the workspace's first project, and "connected an instance"-from its first instance, sample or own. An account that defers its instance therefore shows up as-finished but not yet connected, with no new backend work.+`failure_stage` (names, project, sample, invitees). `sample_enabled` says whether the attempt asked+for the sample, whatever its result, and the source is `none` when no project is made. An attempt that stops (D11) sends neither; the+Finish that completes setup reports. No client event can be the record, though: the 17 lost finishes+lost every custom event after the wizard mounted, and 13 accounts since Sep 11 were never tracked at+all. The record stays with the backend, as the Cloud usage dashboard's exporter already reads it:+"finished setup" from the workspace's first project, and "connected an instance" from its first+instance, sample or own. An account that defers its instance therefore shows up as finished but not+yet connected, with no new backend work.**D11 · Gate, draft and resume.** The gate is unchanged: first login, sole admin, mandatory onCloud, and the flag that sends an unfinished Cloud account back to the wizard clears when Finish-succeeds, as it does on submit today. Until then the answers live in a local draft, keyed by-workspace and user as the guide's stored answers are and removed when Finish succeeds, so Back and a-reload return to the same screen with nothing retyped. On Cloud so does a new login in the same-browser, because that flag sends the account back; on self-hosted, where setup is offered on the-first login only, a new login opens the workspace as it does today. The draft also records that the-project was created, the one step of Finish that cannot be repeated, so a retry, after a reload too,-goes past it instead of failing on a project that already exists. The same has to hold when the-answer to that call was lost: if creating the project reports that its ID already exists, the wizard-reads that project and treats it as created when it is the one this draft describes. A clash with-any other project, the built-in default one included, asks for a different ID under the field. From-then on screen 3 shows the project's name and ID read-only, and the database choice too once the-sample has been prepared: both exist, and are changed in the product, not in the wizard. Every other-step is an overwrite or safe to repeat (saving the names, preparing the sample for the same project,-writing the invitees to the project and then the workspace), so each retry runs them again from the-answers on screen. A checkpoint therefore never outlives the answers it was made with: an invitee-removed after a failed attempt is removed from the project as well. The wizard collects no-credentials, so the draft holds none. No Continue or Finish is disabled without its reason on-screen, and the reason sits with the field or question it is about, as the UX contract requires-(`docs/agents/frontend-ux.md`): under the workspace name, under the goal choices, under the project-name, under the team-size question. Two of the 42 leavers stalled on a disabled button with no-explanation.+succeeds, as it does on submit today. One addition: a workspace admin whose draft is in this browser+may come back to it, as Finish adds the invitees before it ends and the workspace then has other+members. Until then the answers live in a local draft, keyed by workspace and user as the guide's+stored answers are and removed when Finish succeeds, so Back and a reload return to the same screen+with nothing retyped; screen 3 counts as answered without a project name where the name is optional+(D12). On Cloud so does a new login in the same browser, because that flag sends the+account back; on self-hosted, where setup is offered on the first login only, a new login opens the+workspace as it does today. The draft also records that the project was created, the one step of+Finish that cannot be repeated, so a retry, after a reload too, goes past it instead of failing on a+project that already exists. One tab works on setup at a time: the one that saved the draft last.+When another tab saves the draft, this one stops and says setup continued in another tab, with+Continue here, which takes the saved draft up with every screen mounted afresh; when another tab+ends setup, this one says so, with a way to the workspace. Continue here and Finish save the draft+before anything else, and every save is marked as new even when no answer changed, so the other tabs+always hear of it. Work this tab had already started, whether a Finish, an ID check or a skip,+writes nothing more to the server or the draft once another tab saves the draft, setup ends, here or+in another tab, or the wizard is left. A Finish stops before its next write, reports no failure, and+shows the notice once the request it is waiting on returns. A request already sent may still take+effect. The tab that now holds setup finds a created project through the three states below and asks+for the sample again; an invitee's roles may land after its read, so its own roles write makes sure+the earlier one cannot land after it (Project members below). So a stale tab never writes over the+draft or over another tab's answers, a Finish record never meets answers it was not made with, and a+tab whose saves fail keeps its own progress, since without storage no other tab can hear of it.++A create can also be sent and never answered, so the draft holds one of three states for the+project: none, a create sent for an ID with its outcome unknown (recorded before the call), and+created. The unknown state is settled from the server, and only from the server. The project that+holds the ID is the draft's own when it carries the draft's name and its access is still what the+server gives a new project, its creator as owner and nobody else; a project anyone else has been+given access to is never taken over, whatever its ID and name. No such project in this workspace+settles nothing: the create may still be on its way. Two moments settle it. At Finish the create is+sent again, and when it reports that the ID already exists, the draft's own project is taken as+created and anything else is a clash. On screen 3, when it is shown with the outcome still unknown:+the draft's own project puts the screen in its "project exists" state, and another's clears the+record; an answer that arrives after the name or ID was changed is about neither and is dropped. No+project found, or a server that cannot be read, leaves the state unknown, the attempt retryable, and+"I'll do this later" withheld, because a project may exist or still be made; a name or ID changed in+the meantime leaves such a project, if it is made, unused in the workspace. An ID that exists on a+first attempt belongs to someone else, whatever its name. The rule cannot tell the draft's project+from an older one of the same ID and name that the account owns and has shared with nobody; the+wizard takes that one too, as the account named it and nobody else's access is in it, and an ID can+only collide that way if it was typed in by hand.++A clash, and an ID the server refuses for another reason (a reserved one, such as an ID starting+with `default-`), goes back to screen 3 and asks for a different ID under the field, with the+server's reason. The refusal settles that create, and is kept in the draft with its ID, so a reload+still shows the reason until the ID changes. Once the project exists screen 3 shows its name and ID+read-only, and the database choice too once the sample's request has returned: both exist, and are+changed in the product, not in the wizard.++The other steps run again on each retry from the answers on screen, so a checkpoint never outlives+the answers it was made with. Each is written to be safe on state the wizard shares with the rest of+the product:++- **Names.** An overwrite.+- **Sample.** Requested again until its request has returned once, which is safe: a repeated request+ for the same project answers with the same instance (Given). After a reload that cut the request+ short the server already lists the sample under this project, on self-hosted before it is ready.+ That is not a sample another project used, so the sample stays on offer and the stored choice+ decides: the wizard asks again, unless the account chose "Finish without the sample".+- **Project members.** The wizard changes only what it added. For each of the two invitee roles the+ draft records the members a write gives it, which leaves out anyone who held the role already. The+ record is made before the write, because its answer may never arrive, keeps the earlier additions+ until a write is known to have taken them back, and is narrowed once one has. A write the server+ refused changed nothing, so its additions leave the record again; a failure that may have come+ after the write was applied keeps them. A retry gives the two roles to the listed addresses and+ takes them only from recorded members who are no longer listed, so an invitee removed after a+ failed attempt leaves the project too, and a role anyone else gave keeps its members, in their+ order. A draft that never added anyone writes nothing to the project, however long it was left.+ The write replaces the project's whole access policy, the owner's binding included, so it is built+ on the policy read from the server at that moment, with its etag, and is not made when that read+ fails. The copy the page keeps is not used: it would miss an earlier attempt's write whose answer+ was lost. Every attempt that has invitees or recorded members makes the write, even when the+ policy already is what it would make it: an earlier write may still be on its way, after a lost+ answer or from a tab whose Finish stopped (D11), and no read can see it. Both carry an etag, so+ whichever lands second is refused; when the earlier one lands first, the retry that follows reads+ what it did.+- **Workspace members.** Additive: each address gains the member role and keeps any role it already+ holds. It is built on the workspace policy read from the server at that moment, for the same+ reason.++One outcome is accepted, not prevented. An address taken off the list after an attempt whose+workspace write was applied, but whose answer was lost or was still out when its Finish stopped+(D11), stays a workspace member, and on Cloud has its invitation; undoing that would have the wizard+remove workspace members, which it never does.++A failed attempt is reported for the answers it ran with, so its report goes when its screen is+left, and a failure adding the people listed goes when the team size or the addresses change: Back+from screen 4 and a changed answer do not return to the earlier attempt's error. Any other step's+failure still stands after a team answer changes, with "Finish without the sample" when the sample+is what failed. The+wizard collects no credentials, so the draft holds none. No Continue or Finish is disabled without+its reason on screen, and the reason sits with the field or question it is about, as the UX+contract requires (`docs/agents/frontend-ux.md`): under the workspace name, under the goal choices,+under the project name, under the team-size question. That includes the project ID: Continue waits+only on an ID the field has found wrong and says so, not on a check still in flight, because Finish+has the server's answer for an ID that got past it. Two of the 42 leavers stalled on a disabled+button with no explanation.**D12 · Self-hosted keeps its differences.** The same four screens serve self-hosted, where setup isoffered once and screen 3 keeps "I'll do this later". That action saves the two names from screen 1and then leaves for the workspace landing as it does today; if the save fails it stays on screen 3with the error and can be pressed again. No project is created, so nothing else is left behind. The-skip is offered only while that holds: once a Finish attempt has created the project, screen 3 no-longer shows it, and the way out is Finish. Two lines of copy follow the deployment (Given) instead-of repeating Cloud's. The sample choice says the database runs on this server and names no expiry,-as the product's existing self-hosted sample strings do. And screen 4 adds members where Cloud-invites them (D7).+skip is offered only while that holds: once a Finish attempt has created the project, or has sent a+create whose outcome is unknown (D11), screen 3 no longer shows it, and the way out is Finish. Two+lines of copy follow the deployment (Given) instead of repeating Cloud's. The sample choice says the+database runs on this server and names no expiry, as the product's existing self-hosted sample+strings do. The project name is optional there, as in today's wizard: an enterprise server is+often configured through Terraform, and its admin may not want a placeholder project made during+setup. It stays optional while the skip would be offered; once a create has been sent, the name is+needed to finish what it started. Left empty, no project is made, so no database is offered either:+a database belongs to a project, and the sample is bound to one. Finish then saves the names and the+team size and lands where "I'll do this later" leaves for. And screen 4 asks only the team size,+where Cloud also invites (D7).## States| Screen | State | What is on screen | Button ||---|---|---|---|-| 1 Workspace | default | name and workspace name prefilled; hero animation | Continue enabled; disabled if the workspace name is cleared, with "Enter a workspace name" under the field |-| 2 Goal | none chosen | two cards and the lighter "Not sure yet, just exploring"; hero animation | Continue disabled, with "Pick one to continue" under the choices |-| 2 Goal | a card chosen | card pressed, panel swaps to the goal's animation | Continue enabled |-| 2 Goal | just exploring | the third answer pressed, panel stays on the hero | Continue enabled |-| 3 Project | no name | project field empty; the sample choice preselected | Continue disabled, with "Enter a project name" under the field |-| 3 Sample | named, sample chosen | diagram of the sample instance, its database, the project | Continue enabled |-| 3 Own | named, own instance chosen | one line on what happens after setup; diagram of the user's instance joining the project later | Continue enabled |-| 3 · no sample | the server reports the sample unavailable or used | only the own-instance choice, with the reason | Continue enabled once named |+| 1 Workspace | default | name and workspace name prefilled; the panel previews the workspace with both, updating as they are typed | Continue enabled; disabled if the workspace name is cleared, with "Enter a workspace name" under the field |+| 2 Goal | none chosen | two cards and the lighter "Not sure yet, just exploring"; the workspace preview stays | Continue disabled, with "Pick one to continue" under the choices |+| 2 Goal | a card chosen | card pressed; the panel shows the hero for the change goal, and a statement above its result for the query goal | Continue enabled |+| 2 Goal | just exploring | the third answer pressed; the panel shows people and agents reaching the databases through Bytebase | Continue enabled |+| 3 Project | no name | project field empty; the sample choice preselected | on Cloud Continue disabled, with "Enter a project name" under the field |+| 3 · no project | self-hosted, no name | the database choice hidden, with a line that the project can be made later; the panel's project dashed, with no instances | Continue enabled; Finish makes no project |+| 3 Sample | named, sample chosen | the panel's project with the sample instance and its database | Continue enabled |+| 3 Own | named, own instance chosen | one line on what happens after setup; the panel's project with the user's instance, dashed | Continue enabled |+| 3 · no sample | the server reports the sample unavailable, or used by another project | only the own-instance choice, with the reason | Continue enabled once named || 3 · skipped | "I'll do this later", self-hosted only | saves the screen-1 names and leaves for the workspace landing; no project is created; a failed save stays here with the error | n/a |-| 3 · project exists | Back after a Finish attempt that created the project | project name and ID read-only, with a line saying the project exists and is renamed in its settings; the database choice read-only once the sample is prepared; no "I'll do this later" on self-hosted | Continue enabled |+| 3 · project exists | Back after a Finish attempt that created the project, its answer lost included | project name and ID read-only, with a line saying the project exists and is renamed in its settings; the database choice read-only once the sample is prepared; no "I'll do this later" on self-hosted | Continue enabled || 4 Team | size unset | five size options, nothing else | Finish disabled, with "Pick a team size to finish" under the question; Back enabled || 4 Team | "Just me" | the size options only; no invite field | Finish enabled |-| 4 Team | a size above "Just me" | the chips input appears with one line about membership, titled "Invite teammates" on Cloud and "Add members" on self-hosted; the button reads "Finish", or with addresses entered "Send N invites and finish" on Cloud and "Add N members and finish" on self-hosted | Finish enabled |+| 4 Team | a size above "Just me" | on Cloud the chips input appears, titled "Invite teammates", with one line about membership, and the button reads "Finish", or with addresses entered "Send N invites and finish"; on self-hosted the size options only | Finish enabled || 4 · finishing | Finish pressed | the button shows progress; the form is read-only | n/a || 4 · finish failed | a step of the commit failed | the error naming the step, Try again; "Finish without the sample" when the sample failed | Try again enabled |+| any · another tab | another tab saved the draft, or ended setup | in place of the screen: "This setup continued in another tab" with Continue here, or "This setup ended in another tab" with Go to the workspace; a running Finish shows its progress until the request it waits on returns, then sends nothing more | Continue here, or Go to the workspace |+| 3 · ID refused | Finish found the project ID taken, or the server refused it | back on screen 3 with the reason at the ID field, after a reload too | Continue disabled until the ID changes |After Finish the wizard is gone and the account is on the project home (D8). A reload before Finishreturns to the same screen with the draft.@@ -301,35 +422,48 @@ returns to the same screen with the draft.| `frontend/src/routes/auth/WorkspaceSetupPage.tsx` | Rewrite as four screens with the local draft, validation under each field, and the single commit at Finish. Finish navigates to the project home, as the wizard has since [#21572]. || `frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx` | Retire; the goal moves to screen 2 and the team question is removed. || `frontend/src/app/layouts/SplashLayout.tsx` | Setup variant: a panel slot instead of the fixed illustration. |-| `frontend/src/routes/auth/workspace-setup/` (new) | Beside the route that is their only consumer: screen components, the Rive panel (port of bytebase.com `RivePlayer.tsx` with self-hosted `rive.wasm` and the four files), the diagram panel, the chips input. The screens use the shared `StepIndicator`, `RadioGroup` and form primitives, with each validation message under its field. |-| `frontend/src/modules/workspace-setup-guide/` | Take goal, team size and source from the wizard; store "just exploring" as a goal of its own, which uses the query journey; mark "explore database" done on arrival with the sample; start at "Connect instance" on the own-instance path; show the team step only above "Just me". |+| `frontend/src/routes/auth/workspace-setup/` (new) | Beside the route that is their only consumer: screen components, the left panel (the workspace preview, the project with its instances, the project's members, a still frame from bytebase.com's hero Rive file and two pictures composed for the panel), the chips input, whose text field keeps the shared `Input`'s `xs` size, the chips' text size, and only drops its border. The screens use the shared `StepIndicator`, `RadioGroup` and form primitives, with each validation message under its field. |+| `frontend/src/modules/workspace-setup-guide/` | Take the goal and the team size from the wizard; store "just exploring" as a goal of its own, which uses the query journey; mark "explore database" done on arrival with the sample; start at "Connect instance" on the own-instance path; show the team step only above "Just me". || `frontend/src/routes/project/projectHomeNextSteps.ts` | Take the goal as an input. With a database present, "Query a database" comes before "Change a database" for the query goal and for "just exploring"; the order is unchanged otherwise. |-| `frontend/src/routes/project/ProjectHomePage.tsx` | Read the stored goal through the guide module and pass it to the next-step function. |+| `frontend/src/routes/project/ProjectHomePage.tsx`, `ProjectDatabasesPage.tsx` | Read the stored goal through the guide module: the home passes it to the next-step function, and the databases page leads with a query for the same two goals. |+| `frontend/src/app/router/guard.ts` | The setup route also admits a workspace admin whose unfinished draft is in this browser, after the wizard's own invitees have joined (D11). |+| `frontend/src/components/ui/step-indicator.tsx` | Shared step indicator: an opt-in `fitOneRow`, so when the titles do not fit one row (a narrow screen, or a long locale such as Spanish) only the current step keeps its title in sight and the others stay for screen readers. Without the prop it behaves as before. |+| `frontend/src/components/ResourceIdField.tsx` | Shared ID field: an opt-in `keepInitialValue`, so the wizard's field keeps a settled ID when screen 3 is shown again. Without the prop it behaves as before. |+| `frontend/src/stores/app/` | An optional argument on five writes (`updateUser`, `updateWorkspace`, `createProject`, `updateProjectIamPolicy`, `patchWorkspaceIamPolicy`) and on `fetchWorkspaceIamPolicy` for a caller that reports the failure itself, so Finish's errors are not also raised as the product's toast. Other callers are unchanged. |+| `frontend/src/utils/storage-keys.ts`, `frontend/src/app/analytics/behavior.ts`, `frontend/scripts/check-i18n.mjs` | The draft's and the team size's storage keys, the per-screen event's name, and the retired string prefixes. |+| `frontend/tests/e2e/` | A second, first-run server for the wizard's spec, started through the same functions as the shared one. || `frontend/src/locales/en-US.json` (and the other locales) | New strings for the four screens; retire `setup-scenario.mark-sensitive-data` and `setup-scenario.workspace-usage`. |No backend, proto or instance-form change.Tests to write: vitest for each screen's validation message and its place under the field, for thechips parser, for the draft restoring every screen and staying with its workspace and user, and for-the project home's step order under each goal and with none stored; an e2e spec under-`frontend/tests/e2e` that walks the sample path onto the project home with the goal's step first-("Change a database" for the change goal, "Query a database" for the query goal and for "just-exploring"), the own-instance path onto it with "Connect an instance", Back from the team screen-keeping every answer, a failed Finish retried after the invite list changed, and the self-hosted-skip, sample wording and "Add members" field; and event tests that each Continue and the submitted+the project home's step order under each goal and with none stored ("Change a database" first for+the change goal, "Query a database" first for the query goal and for "just exploring"); an e2e spec+under `frontend/tests/e2e`, on a server of its own because the sample is single-use, that walks the+own-instance path onto the project home with "Connect an instance", Back from the team screen+keeping every answer, the sample path once, with the query goal, onto the project home with "Query a+database" first, a Finish retried after the create's answer was lost, and the self-hosted skip,+sample wording and screen 4 without a list of people; vitest for the invite list changing between+retries whose answers were lost, which the self-hosted e2e server cannot reach; vitest for a second tab+taking setup up while a Finish step, an ID check or a skip is out, which then writes nothing more,+for a roles write still on its way, after a lost answer or from a stopped tab, which cannot land+after the next attempt's write, and for a create still on its way when screen 3 finds no project,+which the retry then takes as the draft's own; and event tests that each Continue and the submittedresult carry the properties in D10.## Not in this PR-The implementation, which follows separately. The project home beyond the order of those two steps:-when a step leaves the band, and everything else on the page. The guide bar beyond the answers the-wizard hands it. Connection-failure recovery on the instance page (naming a private address before-the test, showing the Cloud egress address, cause-specific fixes): that is where the 62 failed tests-happen, and it is separate work on that page. The live-preview panel for screen 3. Persisting the-goal or the team size on the server; both travel as event properties and in the browser's local-storage until a consumer needs them elsewhere. Any change to the sample itself, such as a test and-prod pair, which would reopen ADR-0004. Making setup mandatory on self-hosted. Enforcing mandatory-setup across browsers: the flag is per-browser today, so an unfinished account can still enter from-another one, as 3 accounts have since Sep 20, and closing that needs server-side state.+The Rive player of D9, which follows separately. The project home beyond the order of those two+steps: when a step leaves the band, and everything else on the page. The guide bar beyond the+answers the wizard hands it. Connection-failure recovery on the instance page (naming a private+address before the test, showing the Cloud egress address, cause-specific fixes): that is where the+62 failed tests happen, and it is separate work on that page. The live-preview panel for screen 3.+Persisting the goal or the team size on the server; both travel as event properties and in the+browser's local storage until a consumer needs them elsewhere. Any change to the sample itself, such+as a test and prod pair, which would reopen ADR-0004. Making setup mandatory on self-hosted.+Enforcing mandatory setup across browsers: the flag is per-browser today, so an unfinished account+can still enter from another one, as 3 accounts have since Sep 20, and closing that needs+server-side state.[#21572]: https://github.com/bytebase/bytebase/pull/21572diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjsindex 97bf417884..7d5fd3b6cd 100644--- a/frontend/scripts/check-i18n.mjs+++ b/frontend/scripts/check-i18n.mjs@@ -60,13 +60,6 @@ const DYNAMIC_PREFIXES = [// Role-grant expiration presets, rendered via t(preset.labelKey) in// MembersPage.tsx (EXPIRATION_PRESETS), not as literal t("…") calls."project.members.expiration-presets.",- // Scenario option, sample, and guide outcome keys are stored in typed- // definitions and translated through those definitions at render time.- "settings.profile.enable-sample-databases",- "settings.profile.setup-scenario.create-database-change.",- "settings.profile.setup-scenario.mark-sensitive-data.",- "settings.profile.setup-scenario.query-data.",- "settings.profile.setup-scenario.workspace-usage.",// Workspace setup guide step definitions store label and description keys;// the presentation translates them via t(step.definition.<key>)."workspace-setup-guide.descriptions.",diff --git a/frontend/src/app/analytics/behavior.ts b/frontend/src/app/analytics/behavior.tsindex f7399a6365..265ba55a37 100644--- a/frontend/src/app/analytics/behavior.ts+++ b/frontend/src/app/analytics/behavior.ts@@ -27,6 +27,7 @@ export type BehaviorMetricName =| "locked feature clicked"| "sample instance requested"| "workspace setup page entered"+ | "workspace setup screen continued"| "workspace setup submitted"| "workspace setup guide opened"| "workspace setup guide progress observed"diff --git a/frontend/src/app/layouts/SplashLayout.test.tsx b/frontend/src/app/layouts/SplashLayout.test.tsxindex 039740b9cc..8d384ed5a0 100644--- a/frontend/src/app/layouts/SplashLayout.test.tsx+++ b/frontend/src/app/layouts/SplashLayout.test.tsx@@ -1,17 +1,25 @@import { render } from "@testing-library/react";import { beforeEach, describe, expect, test, vi } from "vitest";-import { AUTH_SIGNIN_MODULE } from "@/app/router/handles";+import { AUTH_SETUP_MODULE, AUTH_SIGNIN_MODULE } from "@/app/router/handles";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-import { SplashLayout } from "./SplashLayout";+import { SplashLayout, SplashPanel } from "./SplashLayout";const storeState = vi.hoisted(() => ({currentPlan: 0,isTrialing: false,+ routeName: "",}));+// The routed page, which may put a panel of its own in the left column.vi.mock("react-router", () => ({- Outlet: () => <div data-testid="auth-page" />,- useMatches: () => [{ handle: { name: AUTH_SIGNIN_MODULE } }],+ Outlet: () => (+ <div data-testid="auth-page">+ <SplashPanel>+ <p>the page's own panel</p>+ </SplashPanel>+ </div>+ ),+ useMatches: () => [{ handle: { name: storeState.routeName } }],}));vi.mock("@/stores/app", () => {@@ -33,6 +41,7 @@ describe("SplashLayout", () => {beforeEach(() => {storeState.currentPlan = PlanType.FREE;storeState.isTrialing = false;+ storeState.routeName = AUTH_SIGNIN_MODULE;});test("keeps the mounted auth layout stable when subscription loads during login", () => {@@ -45,4 +54,29 @@ describe("SplashLayout", () => {expect(container.querySelector("img")).toBeInTheDocument();});++ test("keeps the illustration on sign-in, whatever panel the page offers", () => {+ const { container, queryByText } = render(<SplashLayout />);++ expect(container.querySelector("img")).toBeInTheDocument();+ expect(queryByText("the page's own panel")).not.toBeInTheDocument();+ });++ test.each([+ { plan: "the free plan", currentPlan: PlanType.FREE },+ { plan: "a paid plan", currentPlan: PlanType.ENTERPRISE },+ ])("gives the left column to the setup wizard's panel on $plan", ({+ currentPlan,+ }) => {+ storeState.routeName = AUTH_SETUP_MODULE;+ storeState.currentPlan = currentPlan;+ const { container, getByText, getByTestId } = render(<SplashLayout />);++ const panel = getByText("the page's own panel");+ const [leftColumn, rightColumn] = container.firstElementChild?.children ?? [];+ expect(container.querySelector("img")).not.toBeInTheDocument();+ expect(leftColumn).toContainElement(panel);+ expect(rightColumn).toContainElement(getByTestId("auth-page"));+ expect(rightColumn).not.toContainElement(panel);+ });});diff --git a/frontend/src/app/layouts/SplashLayout.tsx b/frontend/src/app/layouts/SplashLayout.tsxindex b2668a6f2a..d38df0e3c8 100644--- a/frontend/src/app/layouts/SplashLayout.tsx+++ b/frontend/src/app/layouts/SplashLayout.tsx@@ -1,14 +1,25 @@-import { useState } from "react";+import { createContext, type ReactNode, useContext, useState } from "react";+import { createPortal } from "react-dom";import { Outlet, useMatches } from "react-router";-import { AUTH_SIGNUP_MODULE } from "@/app/router/handles";+import { AUTH_SETUP_MODULE, AUTH_SIGNUP_MODULE } from "@/app/router/handles";import signinImage from "@/assets/illustration/signin.webp";import signupImage from "@/assets/illustration/signup.webp";import { useAppStore } from "@/stores/app";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-// Two-column auth chrome: an optional branding illustration on the left (shown-// unless the workspace is on a non-trialing enterprise plan) and the routed-// auth page on the right.+// The left column's element on a route that hands that column to its page.+export const SplashPanelContext = createContext<HTMLElement | null>(null);++// Renders `children` in the layout's left column. On a route that keeps the+// branding illustration there, it renders nothing.+export function SplashPanel({ children }: { readonly children: ReactNode }) {+ const slot = useContext(SplashPanelContext);+ return slot ? createPortal(children, slot) : null;+}++// Two-column auth chrome: the left column holds the branding illustration+// (shown unless the workspace is on a non-trialing enterprise plan), or on the+// setup route the wizard's own panel; the routed auth page is on the right.//// The right column owns the gutter and the page's share of the viewport (all// of it below lg, half from lg). A routed page fills the column up to its own@@ -19,6 +30,8 @@ export function SplashLayout() {const currentRouteName = (matches.at(-1)?.handle as { name?: string } | undefined)?.name;+ const pageOwnsPanel = currentRouteName === AUTH_SETUP_MODULE;+ const [panelSlot, setPanelSlot] = useState<HTMLElement | null>(null);const [showBrandingImage] = useState(() => {const store = useAppStore.getState();@@ -28,7 +41,12 @@ export function SplashLayout() {return (<div className="min-h-screen overflow-hidden flex">- {showBrandingImage ? (+ {pageOwnsPanel ? (+ <div+ ref={setPanelSlot}+ className="hidden bg-control-bg lg:flex relative w-0 flex-1 items-center justify-center p-12"+ />+ ) : showBrandingImage ? (<div className="hidden bg-background lg:block relative w-0 flex-1"><imgclassName="absolute inset-0 h-full w-full object-cover"@@ -42,7 +60,9 @@ export function SplashLayout() {</div>) : null}<div className="relative mx-auto flex-1 flex flex-col justify-center py-12 pb-24 px-4 sm:px-6 lg:flex-none lg:px-20 lg:w-1/2 xl:px-24">- <Outlet />+ <SplashPanelContext.Provider value={pageOwnsPanel ? panelSlot : null}>+ <Outlet />+ </SplashPanelContext.Provider></div></div>);diff --git a/frontend/src/app/router/guard.test.ts b/frontend/src/app/router/guard.test.tsindex 4092a97102..7f0973b5dc 100644--- a/frontend/src/app/router/guard.test.ts+++ b/frontend/src/app/router/guard.test.ts@@ -12,8 +12,10 @@ const session = {isSaaSMode: false,disallowSignup: false,enableOnboarding: false,- currentUser: undefined as { mfaEnabled: boolean } | undefined,+ currentUser: undefined as { mfaEnabled: boolean; name?: string } | undefined,+ workspaceAdmin: false,workspaceSetupFinished: undefined as boolean | undefined,+ workspaceSetupDraft: false,// Mirrors the store default: PIPELINE until the workspace profile loads.databaseChangeMode: DatabaseChangeMode.PIPELINE,};@@ -39,6 +41,8 @@ vi.mock("@/stores/app", () => ({hasFeature: () => session.hasTwoFa,isSaaSMode: () => session.isSaaSMode,enableOnboarding: () => session.enableOnboarding,+ getWorkspaceRolesByName: () =>+ new Set(session.workspaceAdmin ? ["roles/workspaceAdmin"] : []),fetchServerInfo: workspaceSetup.fetchServerInfo,fetchWorkspaceIamPolicy: workspaceSetup.fetchWorkspaceIamPolicy,authenticationInfo: {@@ -62,6 +66,10 @@ vi.mock("@/modules/workspace-setup-guide/setup", () => ({readWorkspaceSetupFinished: () => session.workspaceSetupFinished,}));+vi.mock("@/modules/workspace-setup-guide/selection", () => ({+ hasWorkspaceSetupDraft: () => session.workspaceSetupDraft,+}));+import { buildSigninRedirectQuery, rootGuard } from "./guard";import {ACCOUNT_ROUTE,@@ -91,7 +99,9 @@ beforeEach(() => {session.disallowSignup = false;session.enableOnboarding = false;session.currentUser = undefined;+ session.workspaceAdmin = false;session.workspaceSetupFinished = undefined;+ session.workspaceSetupDraft = false;session.databaseChangeMode = DatabaseChangeMode.PIPELINE;vi.clearAllMocks();workspaceSetup.fetchServerInfo.mockResolvedValue({});@@ -231,6 +241,31 @@ describe("rootGuard", () => {expect(await runWorkspaceSetupLoader()).toBeNull();});+ test("lets a workspace admin back into the setup draft this browser holds once others have joined", async () => {+ session.isLoggedIn = true;+ session.currentUser = { mfaEnabled: false, name: "users/[email protected]" };+ session.workspaceAdmin = true;+ session.workspaceSetupDraft = true;++ expect(await runWorkspaceSetupLoader()).toBeNull();+ });++ test("keeps a workspace admin with no setup draft out once others have joined", async () => {+ session.isLoggedIn = true;+ session.currentUser = { mfaEnabled: false, name: "users/[email protected]" };+ session.workspaceAdmin = true;++ expect(location(await runWorkspaceSetupLoader())).toBe("/landing");+ });++ test("keeps an account that is not a workspace admin out of a setup draft", async () => {+ session.isLoggedIn = true;+ session.currentUser = { mfaEnabled: false, name: "users/[email protected]" };+ session.workspaceSetupDraft = true;++ expect(location(await runWorkspaceSetupLoader())).toBe("/landing");+ });+test("redirects an ineligible user away from workspace setup", async () => {session.isLoggedIn = true;diff --git a/frontend/src/app/router/guard.ts b/frontend/src/app/router/guard.tsindex 079f9f4282..c0f3d5d3ac 100644--- a/frontend/src/app/router/guard.ts+++ b/frontend/src/app/router/guard.ts@@ -1,6 +1,8 @@import { redirect } from "react-router";+import { hasWorkspaceSetupDraft } from "@/modules/workspace-setup-guide/selection";import { readWorkspaceSetupFinished } from "@/modules/workspace-setup-guide/setup";import { useAppStore } from "@/stores/app";+import { PresetRoleType } from "@/types/iam/role";import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {@@ -96,9 +98,19 @@ export async function workspaceSetupGuard(url: URL): Promise<Response | null> {if (store.isSaaSMode() && setupFinished === false) {return null;}+ // Finish adds its invitees before it ends, so an admin whose setup is+ // still in this browser comes back to it though others have joined.+ const resumesSetup = () => {+ const name = store.currentUser?.name;+ return (+ !!name &&+ store.getWorkspaceRolesByName(name).has(PresetRoleType.WORKSPACE_ADMIN) &&+ hasWorkspaceSetupDraft()+ );+ };if ((!store.isSaaSMode() || setupFinished === undefined) &&- store.enableOnboarding()+ (store.enableOnboarding() || resumesSetup())) {return null;}diff --git a/frontend/src/assets/illustration/setup-explore.webp b/frontend/src/assets/illustration/setup-explore.webpnew file mode 100644index 0000000000..5c073a76c0Binary files /dev/null and b/frontend/src/assets/illustration/setup-explore.webp differdiff --git a/frontend/src/assets/illustration/setup-hero.webp b/frontend/src/assets/illustration/setup-hero.webpnew file mode 100644index 0000000000..a8de876ad6Binary files /dev/null and b/frontend/src/assets/illustration/setup-hero.webp differdiff --git a/frontend/src/assets/illustration/setup-query.webp b/frontend/src/assets/illustration/setup-query.webpnew file mode 100644index 0000000000..f5eaa286b9Binary files /dev/null and b/frontend/src/assets/illustration/setup-query.webp differdiff --git a/frontend/src/components/ResourceIdField.test.tsx b/frontend/src/components/ResourceIdField.test.tsxindex 11c2abd850..93a6850825 100644--- a/frontend/src/components/ResourceIdField.test.tsx+++ b/frontend/src/components/ResourceIdField.test.tsx@@ -1,11 +1,16 @@-import { cleanup, fireEvent, render } from "@testing-library/react";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";import { afterEach, describe, expect, test, vi } from "vitest";import { ResourceIdField } from "./ResourceIdField";-vi.mock("react-i18next", () => ({- initReactI18next: { type: "3rdParty", init: () => {} },- useTranslation: () => ({ t: (key: string) => key }),-}));+vi.mock("react-i18next", () => {+ // One function for every render, as the real hook returns: the field's+ // effects depend on it.+ const t = (key: string) => key;+ return {+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t }),+ };+});describe("ResourceIdField", () => {afterEach(cleanup);@@ -25,4 +30,91 @@ describe("ResourceIdField", () => {"off");});++ test("regenerates the ID when it is mounted again, unless asked to keep it", async () => {+ const onChange = vi.fn();+ render(+ <ResourceIdField+ suffix+ value="payments-ab12"+ resourceName="Project"+ resourceTitle="Payments"+ onChange={onChange}+ />+ );++ await waitFor(() => expect(onChange).toHaveBeenCalled());+ expect(onChange).not.toHaveBeenCalledWith("payments-ab12");+ });++ test("keeps the ID it is mounted with until the title changes", async () => {+ const onChange = vi.fn();+ const onValidationChange = vi.fn();+ const field = (title: string) => (+ <ResourceIdField+ suffix+ keepInitialValue+ value="payments-ab12"+ resourceName="Project"+ resourceTitle={title}+ onChange={onChange}+ onValidationChange={onValidationChange}+ />+ );+ const { rerender } = render(field("Payments"));++ await waitFor(() => expect(onValidationChange).toHaveBeenCalledWith(true));+ expect(onChange).not.toHaveBeenCalled();++ rerender(field("Billing"));++ await waitFor(() =>+ expect(onChange).toHaveBeenLastCalledWith(+ expect.stringMatching(/^billing-[a-z0-9]{4}$/)+ )+ );+ });++ test("checks the ID it kept, and reports one that is no longer valid", async () => {+ const onChange = vi.fn();+ const onValidationChange = vi.fn();+ const { findByText } = render(+ <ResourceIdField+ suffix+ keepInitialValue+ value="payments-ab12"+ resourceName="Project"+ resourceTitle="Payments"+ validate={async (id) => [+ { type: "error", message: `${id} is taken` },+ ]}+ onChange={onChange}+ onValidationChange={onValidationChange}+ />+ );++ expect(await findByText("payments-ab12 is taken")).toBeInTheDocument();+ expect(onValidationChange).toHaveBeenLastCalledWith(false);+ expect(onChange).not.toHaveBeenCalled();+ });++ test("generates an ID when there is none to keep", async () => {+ const onChange = vi.fn();+ render(+ <ResourceIdField+ suffix+ keepInitialValue+ value=""+ resourceName="Project"+ resourceTitle="Payments"+ onChange={onChange}+ />+ );++ await waitFor(() =>+ expect(onChange).toHaveBeenLastCalledWith(+ expect.stringMatching(/^payments-[a-z0-9]{4}$/)+ )+ );+ });});diff --git a/frontend/src/components/ResourceIdField.tsx b/frontend/src/components/ResourceIdField.tsxindex 4d00abb35e..a41dcf7e94 100644--- a/frontend/src/components/ResourceIdField.tsx+++ b/frontend/src/components/ResourceIdField.tsx@@ -33,6 +33,9 @@ interface ResourceIdFieldProps {autoComplete?: ComponentProps<"input">["autoComplete"];suffix?: boolean;readonly?: boolean;+ // Keep the value the field is mounted with until the title changes, for a+ // caller that mounts it again with an ID the user has already settled on.+ keepInitialValue?: boolean;validate?: (resourceId: string) => Promise<ValidatedMessage[]>;onChange?: (value: string) => void;onValidationChange?: (isValid: boolean) => void;@@ -70,6 +73,7 @@ export const ResourceIdField = forwardRef<autoComplete,suffix = false,readonly = false,+ keepInitialValue = false,validate,onChange,onValidationChange,@@ -81,6 +85,9 @@ export const ResourceIdField = forwardRef<const [messages, setMessages] = useState<ValidatedMessage[]>([]);const randomSuffixRef = useRef(randomString(4).toLowerCase());const initializedRef = useRef(false);+ const keptRef = useRef(+ keepInitialValue && value ? { value, title: resourceTitle } : undefined+ );// Use refs for callbacks to avoid re-triggering the auto-generate effectconst onChangeRef = useRef(onChange);onChangeRef.current = onChange;@@ -136,6 +143,12 @@ export const ResourceIdField = forwardRef<// Auto-generate from titleuseEffect(() => {if (readonly || manualEdit) return;+ if (keptRef.current && keptRef.current.title === resourceTitle) {+ validateId(keptRef.current.value).then(updateMessages);+ initializedRef.current = true;+ return;+ }+ keptRef.current = undefined;const parts: string[] = [];if (resourceTitle) {diff --git a/frontend/src/components/ui/step-indicator.test.tsx b/frontend/src/components/ui/step-indicator.test.tsxindex ef23de7305..323ab84d7a 100644--- a/frontend/src/components/ui/step-indicator.test.tsx+++ b/frontend/src/components/ui/step-indicator.test.tsx@@ -1,7 +1,7 @@import type { ReactElement } from "react";import { act } from "react";import { createRoot } from "react-dom/client";-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import { StepIndicator } from "./step-indicator";(@@ -55,4 +55,84 @@ describe("StepIndicator", () => {unmount();});++ describe("with fitOneRow", () => {+ // jsdom lays nothing out, so the widths are given: the one row the steps+ // need, and the list they sit in.+ const withWidths = (row: number, list: number, run: () => void) => {+ const observer = globalThis.ResizeObserver;+ globalThis.ResizeObserver = class {+ constructor(private readonly callback: () => void) {}+ observe() {+ this.callback();+ }+ disconnect() {}+ unobserve() {}+ } as unknown as typeof ResizeObserver;+ const scroll = vi+ .spyOn(HTMLElement.prototype, "scrollWidth", "get")+ .mockReturnValue(row);+ const client = vi+ .spyOn(HTMLElement.prototype, "clientWidth", "get")+ .mockReturnValue(list);+ try {+ run();+ } finally {+ scroll.mockRestore();+ client.mockRestore();+ globalThis.ResizeObserver = observer;+ }+ };+ const titlesIn = (container: HTMLElement) =>+ [+ ...container.querySelectorAll(+ '[data-slot="step-indicator"] li span'+ ),+ ].map((title) => ({+ text: title.textContent,+ shown: !title.className.includes("sr-only"),+ }));++ test("keeps only the current step's title in sight when the steps do not fit one row", () => {+ withWidths(500, 300, () => {+ const { container, unmount } = renderIntoContainer(+ <StepIndicator+ fitOneRow+ currentIndex={1}+ steps={[+ { title: "First" },+ { title: "Second" },+ { title: "Third" },+ ]}+ />+ );++ expect(titlesIn(container)).toEqual([+ { text: "First", shown: false },+ { text: "Second", shown: true },+ { text: "Third", shown: false },+ ]);+ unmount();+ });+ });++ test("keeps every title in sight when the steps fit one row", () => {+ withWidths(500, 600, () => {+ const { container, unmount } = renderIntoContainer(+ <StepIndicator+ fitOneRow+ currentIndex={1}+ steps={[+ { title: "First" },+ { title: "Second" },+ { title: "Third" },+ ]}+ />+ );++ expect(titlesIn(container).every(({ shown }) => shown)).toBe(true);+ unmount();+ });+ });+ });});diff --git a/frontend/src/components/ui/step-indicator.tsx b/frontend/src/components/ui/step-indicator.tsxindex 882a1c5797..c68f81b4d7 100644--- a/frontend/src/components/ui/step-indicator.tsx+++ b/frontend/src/components/ui/step-indicator.tsx@@ -1,5 +1,5 @@import { Check } from "lucide-react";-import type { ReactNode } from "react";+import { type ReactNode, useLayoutEffect, useRef, useState } from "react";import { cn } from "@/lib/utils";export type StepIndicatorStep = {@@ -12,11 +12,15 @@ export function StepIndicator({currentIndex,currentKey,className,+ fitOneRow = false,}: {readonly steps: StepIndicatorStep[];readonly currentIndex?: number;readonly currentKey?: string | number;readonly className?: string;+ // When the titles do not fit one row, only the current step keeps its title+ // in sight; the others stay for screen readers.+ readonly fitOneRow?: boolean;}) {const activeIndex =currentIndex ??@@ -24,43 +28,84 @@ export function StepIndicator({? 0: steps.findIndex((step) => step.key === currentKey));- return (+ const listRef = useRef<HTMLOListElement>(null);+ // The steps laid out in full on one row, out of sight, to measure.+ const rowRef = useRef<HTMLOListElement>(null);+ const [narrow, setNarrow] = useState(false);+ useLayoutEffect(() => {+ const list = listRef.current;+ const row = rowRef.current;+ if (!fitOneRow || !list || !row || typeof ResizeObserver === "undefined") {+ return;+ }+ const observer = new ResizeObserver(() =>+ setNarrow(row.scrollWidth > list.clientWidth)+ );+ observer.observe(list);+ observer.observe(row);+ return () => observer.disconnect();+ }, [fitOneRow]);++ const items = (compact: boolean) =>+ steps.map((step, index) => {+ const isReached = activeIndex >= 0 && index <= activeIndex;+ const isCompleted = activeIndex >= 0 && index < activeIndex;+ return (+ <li key={step.key ?? index} className="flex items-center gap-x-2">+ {index > 0 && (+ <div+ className={cn("h-px bg-control-border", compact ? "w-4" : "w-8")}+ />+ )}+ <div className="flex items-center gap-x-2">+ <div+ className={cn(+ "flex size-6 items-center justify-center rounded-full text-xs font-medium",+ isReached+ ? "bg-accent text-accent-text"+ : "bg-control-bg-hover text-control-light"+ )}+ >+ {isCompleted ? <Check className="size-3.5" /> : index + 1}+ </div>+ <span+ className={cn(+ "text-sm",+ isReached ? "text-accent font-medium" : "text-control-light",+ compact && index !== activeIndex && "sr-only"+ )}+ >+ {step.title}+ </span>+ </div>+ </li>+ );+ });++ const list = (<ol+ ref={listRef}data-slot="step-indicator"className={cn("flex flex-wrap items-center gap-x-2 gap-y-1 px-0.5",className)}>- {steps.map((step, index) => {- const isReached = activeIndex >= 0 && index <= activeIndex;- const isCompleted = activeIndex >= 0 && index < activeIndex;- return (- <li key={step.key ?? index} className="flex items-center gap-x-2">- {index > 0 && <div className="w-8 h-px bg-control-border" />}- <div className="flex items-center gap-x-2">- <div- className={cn(- "flex size-6 items-center justify-center rounded-full text-xs font-medium",- isReached- ? "bg-accent text-accent-text"- : "bg-control-bg-hover text-control-light"- )}- >- {isCompleted ? <Check className="size-3.5" /> : index + 1}- </div>- <span- className={cn(- "text-sm",- isReached ? "text-accent font-medium" : "text-control-light"- )}- >- {step.title}- </span>- </div>- </li>- );- })}+ {items(narrow)}</ol>);+ if (!fitOneRow) return list;++ return (+ <div className="relative">+ {list}+ <ol+ ref={rowRef}+ aria-hidden="true"+ className="pointer-events-none invisible absolute top-0 left-0 flex w-max items-center gap-x-2 px-0.5"+ >+ {items(false)}+ </ol>+ </div>+ );}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 1b6dcc2e6f..642c4f78cf 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2979,59 +2979,16 @@"workload-identity-tag-hint": "Leave empty to allow all tags"},"profile": {- "default-project-name": "New project","display-name": "Your name","display-name-placeholder": "Enter your name","email": "Email",- "enable-sample-databases": "Enable sample databases",- "enable-sample-databases-create-change": "Enable sample databases as a safe database change target",- "enable-sample-databases-mark-sensitive-data": "Enable sample databases to try data masking immediately",- "enable-sample-databases-query-data": "Enable sample databases to start querying immediately","password": "Password","password-confirm": "Password Confirm","password-confirm-placeholder": "Confirm new password","password-hint": "Password should follow restriction setting","password-mismatch": "New password mismatch","phone": "Phone",- "phone-tips": "Be sure to include the country code +1xxxxxx",- "setup-failed": "Failed to update profile.",- "setup-first-project": "Setup 1st project",- "setup-scenario": {- "continue": "Continue",- "create-database-change": {- "description": "Define a change and create a traceable issue.",- "title": "Create a database change"- },- "mark-sensitive-data": {- "description": "Identify sensitive columns and apply masking.",- "title": "Mark sensitive data"- },- "outcome-title": "What would you like to do with Bytebase?",- "query-data": {- "description": "Open SQL Editor and run a statement against a database.",- "title": "Query data"- },- "workspace-usage": {- "solo": {- "description": "I will use Bytebase on my own.",- "title": "Just me"- },- "team": {- "description": "I will work with other people.",- "title": "My team"- },- "title": "Who will use Bytebase with you?"- }- },- "setup-skip": "I'll do this later",- "setup-steps": {- "scenario": "Choose a goal",- "workspace": "Set up workspace"- },- "setup-submit": "Setup my workspace",- "setup-success": "Profile updated.",- "workspace-name": "Workspace name",- "workspace-name-placeholder": "Enter workspace name"+ "phone-tips": "Be sure to include the country code +1xxxxxx"},"sensitive-data": {"algorithms": {@@ -3884,6 +3841,123 @@"self": "Your two-factor secret"}},+ "workspace-setup": {+ "continue": "Continue",+ "elsewhere": {+ "continue": "Continue here",+ "ended": "This setup ended in another tab",+ "saved": "This setup continued in another tab",+ "workspace": "Go to the workspace"+ },+ "goal": {+ "change": {+ "description": "Write a schema change or a data fix, let SQL review check it, and roll it out to the database.",+ "finish-line": "Finish line: a change that passed SQL review and rolled out",+ "title": "Plan, review and roll out a database change"+ },+ "description": "Pick what brought you here. We suggest it first once setup ends.",+ "explore": {+ "description": "We'll suggest a quick query to start. Pick a direction later.",+ "title": "Not sure yet, just exploring"+ },+ "query": {+ "description": "Run SQL on the database from the editor, with every statement recorded in query history.",+ "finish-line": "Finish line: a query result from the database",+ "title": "Query data with guardrails"+ },+ "required": "Pick one to continue",+ "title": "What do you want to do first?"+ },+ "optional": "optional",+ "panel": {+ "connected-after-setup": "Connected after setup",+ "own-databases": "Its databases",+ "own-instance": "Your instance",+ "sample-database": "Sample database",+ "sample-instance": "Sample Project Instance",+ "workspace": "Workspace"+ },+ "project": {+ "database-title": "Database for {{project}}",+ "description": "Bytebase needs a database to do anything. Name the project that will hold it, then choose where the first one comes from.",+ "exists": "This project already exists. Rename it in its settings.",+ "name": "Project name",+ "name-hint": "A project groups the databases a team works on, with its members and policies. Every change and query happens inside one.",+ "name-optional-note": "Leave it empty to create a project later.",+ "name-placeholder": "Payments, Data platform, Internal tools",+ "name-required": "Enter a project name",+ "own": {+ "description": "An instance is your database server. Setup finishes first; you connect it from {{project}} afterwards.",+ "title": "Connect my own instance after setup"+ },+ "sample": {+ "description": "One PostgreSQL database with employee sample data, hosted by Bytebase Cloud. Nothing to install; available for 7 days.",+ "description-self-host": "One PostgreSQL database with employee sample data, running on this server. Nothing to install.",+ "prepared": "The sample database is ready in this project.",+ "recommended": "Recommended",+ "title": "Start with the sample database",+ "unavailable": "The sample database is not available on this server.",+ "used": "This workspace has already used its sample database."+ },+ "skip": "I'll do this later",+ "title": "Create a project and choose its database",+ "your-project": "your project"+ },+ "steps": {+ "goal": "Goal",+ "project": "Project",+ "team": "Team",+ "workspace": "Workspace"+ },+ "team": {+ "address-invalid": "Not an email address",+ "address-own": "Your own address",+ "address-placeholder": "[email protected]",+ "address-placeholder-more": "Another address",+ "description": "One question before you finish.",+ "failed": {+ "invitees": "Could not add the people you listed.",+ "names": "Could not save your name and the workspace name.",+ "project": "Could not create {{project}}.",+ "sample": "Could not prepare the sample database."+ },+ "finish": "Finish",+ "finish-invite_one": "Send {{count}} invite and finish",+ "finish-invite_other": "Send {{count}} invites and finish",+ "finish-without-sample": "Finish without the sample",+ "finishing": "Setting up…",+ "invite-teammates": "Invite teammates",+ "members-enter": "Press Enter after each address.",+ "members-own": "Its databases appear once your instance is connected.",+ "members-role": "They join as members who can query and propose changes in {{project}}.",+ "members-roles-later": "Change roles any time in Members.",+ "progress": "Creating {{project}}…",+ "progress-sample": "Creating {{project}} and its sample database…",+ "remove-address": "Remove {{email}}",+ "size": "How many people will use Bytebase?",+ "size-required": "Pick a team size to finish",+ "sizes": {+ "11-50": "11–50",+ "2-10": "2–10",+ "200-plus": "200+",+ "51-200": "51–200",+ "just-me": "Just me"+ },+ "title": "Your team",+ "try-again": "Try again"+ },+ "workspace": {+ "default-name": "{{name}}'s workspace",+ "default-name-anonymous": "My workspace",+ "description": "Bytebase is ready once it has a workspace, a project and a database.",+ "name-placeholder": "Enter your name",+ "title": "Set up your workspace",+ "workspace-name": "Workspace name",+ "workspace-name-hint": "Everyone you add joins this workspace.",+ "workspace-name-placeholder": "Usually your company",+ "workspace-name-required": "Enter a workspace name"+ }+ },"workspace-setup-guide": {"actions": {"query": "Go to SQL Editor"diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex cdd5a85d97..fe6a169a85 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2979,59 +2979,16 @@"workload-identity-tag-hint": "Dejar vacío para permitir todas las etiquetas"},"profile": {- "default-project-name": "Nuevo proyecto","display-name": "Su nombre","display-name-placeholder": "Ingrese su nombre","email": "Correo electrónico",- "enable-sample-databases": "Habilitar bases de datos de ejemplo",- "enable-sample-databases-create-change": "Habilitar bases de datos de ejemplo como destino seguro para el cambio",- "enable-sample-databases-mark-sensitive-data": "Habilitar bases de datos de ejemplo para probar el enmascaramiento de datos de inmediato",- "enable-sample-databases-query-data": "Habilitar bases de datos de ejemplo para empezar a consultar de inmediato","password": "Contraseña","password-confirm": "Confirmar contraseña","password-confirm-placeholder": "Confirmar nueva contraseña","password-hint": "La contraseña debe seguir la configuración de restricción","password-mismatch": "Nueva contraseña no coincide","phone": "Número de móvil",- "phone-tips": "Asegúrese de incluir el código del país +1xxxxxx",- "setup-failed": "Error al actualizar el perfil.",- "setup-first-project": "Configurar el primer proyecto",- "setup-scenario": {- "continue": "Continuar",- "create-database-change": {- "description": "Defina un cambio y cree una incidencia rastreable.",- "title": "Crear un cambio de base de datos"- },- "mark-sensitive-data": {- "description": "Identifica columnas sensibles y aplica enmascaramiento de datos.",- "title": "Marcar datos sensibles"- },- "outcome-title": "¿Qué le gustaría hacer con Bytebase?",- "query-data": {- "description": "Abra SQL Editor y ejecute una sentencia en una base de datos.",- "title": "Consultar datos"- },- "workspace-usage": {- "solo": {- "description": "Usaré Bytebase por mi cuenta.",- "title": "Solo yo"- },- "team": {- "description": "Trabajaré con otras personas.",- "title": "Mi equipo"- },- "title": "¿Quién usará Bytebase con usted?"- }- },- "setup-skip": "Lo haré después",- "setup-steps": {- "scenario": "Elegir un objetivo",- "workspace": "Configurar espacio de trabajo"- },- "setup-submit": "Configurar mi espacio de trabajo",- "setup-success": "Perfil actualizado.",- "workspace-name": "Nombre del espacio de trabajo",- "workspace-name-placeholder": "Ingrese el nombre del espacio de trabajo"+ "phone-tips": "Asegúrese de incluir el código del país +1xxxxxx"},"sensitive-data": {"algorithms": {@@ -3884,6 +3841,123 @@"self": "Su secreto de dos factores"}},+ "workspace-setup": {+ "continue": "Continuar",+ "elsewhere": {+ "continue": "Continuar aquí",+ "ended": "Esta configuración terminó en otra pestaña",+ "saved": "Esta configuración continuó en otra pestaña",+ "workspace": "Ir al espacio de trabajo"+ },+ "goal": {+ "change": {+ "description": "Escriba un cambio de esquema o una corrección de datos, deje que la revisión de SQL lo compruebe y despliéguelo en la base de datos.",+ "finish-line": "Meta: un cambio que superó la revisión de SQL y se desplegó",+ "title": "Planificar, revisar y desplegar un cambio de base de datos"+ },+ "description": "Elija lo que le trajo aquí. Se lo sugeriremos primero al terminar la configuración.",+ "explore": {+ "description": "Le sugeriremos una consulta rápida para empezar. Elija un rumbo más adelante.",+ "title": "Aún no lo sé, solo estoy explorando"+ },+ "query": {+ "description": "Ejecute SQL en la base de datos desde el editor, con cada sentencia registrada en el historial de consultas.",+ "finish-line": "Meta: un resultado de consulta de la base de datos",+ "title": "Consultar datos con protecciones"+ },+ "required": "Elija una opción para continuar",+ "title": "¿Qué quiere hacer primero?"+ },+ "optional": "opcional",+ "panel": {+ "connected-after-setup": "Se conecta tras la configuración",+ "own-databases": "Sus bases de datos",+ "own-instance": "Su instancia",+ "sample-database": "Base de datos de ejemplo",+ "sample-instance": "Instancia de proyecto de muestra",+ "workspace": "Espacio de trabajo"+ },+ "project": {+ "database-title": "Base de datos para {{project}}",+ "description": "Bytebase necesita una base de datos para funcionar. Dé nombre al proyecto que la contendrá y elija de dónde viene la primera.",+ "exists": "Este proyecto ya existe. Cámbiele el nombre en su configuración.",+ "name": "Nombre del proyecto",+ "name-hint": "Un proyecto agrupa las bases de datos en las que trabaja un equipo, con sus miembros y políticas. Cada cambio y cada consulta ocurre dentro de uno.",+ "name-optional-note": "Déjelo vacío para crear un proyecto más tarde.",+ "name-placeholder": "Pagos, Plataforma de datos, Herramientas internas",+ "name-required": "Introduzca un nombre de proyecto",+ "own": {+ "description": "Una instancia es su servidor de base de datos. La configuración termina primero; después la conecta desde {{project}}.",+ "title": "Conectar mi propia instancia después de la configuración"+ },+ "sample": {+ "description": "Una base de datos PostgreSQL con datos de ejemplo de empleados, alojada por Bytebase Cloud. Sin instalar nada; disponible durante 7 días.",+ "description-self-host": "Una base de datos PostgreSQL con datos de ejemplo de empleados, que se ejecuta en este servidor. Sin instalar nada.",+ "prepared": "La base de datos de ejemplo está lista en este proyecto.",+ "recommended": "Recomendado",+ "title": "Empezar con la base de datos de ejemplo",+ "unavailable": "La base de datos de ejemplo no está disponible en este servidor.",+ "used": "Este espacio de trabajo ya ha usado su base de datos de ejemplo."+ },+ "skip": "Lo haré después",+ "title": "Cree un proyecto y elija su base de datos",+ "your-project": "su proyecto"+ },+ "steps": {+ "goal": "Objetivo",+ "project": "Proyecto",+ "team": "Equipo",+ "workspace": "Espacio de trabajo"+ },+ "team": {+ "address-invalid": "No es una dirección de correo",+ "address-own": "Su propia dirección",+ "address-placeholder": "[email protected]",+ "address-placeholder-more": "Otra dirección",+ "description": "Una pregunta antes de terminar.",+ "failed": {+ "invitees": "No se pudo añadir a las personas indicadas.",+ "names": "No se pudieron guardar su nombre y el nombre del espacio de trabajo.",+ "project": "No se pudo crear {{project}}.",+ "sample": "No se pudo preparar la base de datos de ejemplo."+ },+ "finish": "Finalizar",+ "finish-invite_one": "Enviar {{count}} invitación y finalizar",+ "finish-invite_other": "Enviar {{count}} invitaciones y finalizar",+ "finish-without-sample": "Finalizar sin la base de datos de ejemplo",+ "finishing": "Configurando…",+ "invite-teammates": "Invitar a compañeros",+ "members-enter": "Pulse Intro después de cada dirección.",+ "members-own": "Sus bases de datos aparecerán cuando conecte su instancia.",+ "members-role": "Se unen como miembros que pueden consultar y proponer cambios en {{project}}.",+ "members-roles-later": "Cambie los roles cuando quiera en Miembros.",+ "progress": "Creando {{project}}…",+ "progress-sample": "Creando {{project}} y su base de datos de ejemplo…",+ "remove-address": "Quitar {{email}}",+ "size": "¿Cuántas personas usarán Bytebase?",+ "size-required": "Elija un tamaño de equipo para finalizar",+ "sizes": {+ "11-50": "11–50",+ "2-10": "2–10",+ "200-plus": "200+",+ "51-200": "51–200",+ "just-me": "Solo yo"+ },+ "title": "Su equipo",+ "try-again": "Reintentar"+ },+ "workspace": {+ "default-name": "Espacio de trabajo de {{name}}",+ "default-name-anonymous": "Mi espacio de trabajo",+ "description": "Bytebase está listo cuando tiene un espacio de trabajo, un proyecto y una base de datos.",+ "name-placeholder": "Introduzca su nombre",+ "title": "Configure su espacio de trabajo",+ "workspace-name": "Nombre del espacio de trabajo",+ "workspace-name-hint": "Todas las personas que añada se unirán a este espacio de trabajo.",+ "workspace-name-placeholder": "Normalmente su empresa",+ "workspace-name-required": "Introduzca un nombre para el espacio de trabajo"+ }+ },"workspace-setup-guide": {"actions": {"query": "Ir a SQL Editor"diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e96702a2e5..baeb6545ca 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2979,59 +2979,16 @@"workload-identity-tag-hint": "すべてのタグを許可する場合は空欄にしてください"},"profile": {- "default-project-name": "新しいプロジェクト","display-name": "あなたの名前","display-name-placeholder": "名前を入力してください","email": "メールアドレス",- "enable-sample-databases": "サンプルデータベースを有効にする",- "enable-sample-databases-create-change": "安全な変更対象としてサンプルデータベースを有効にする",- "enable-sample-databases-mark-sensitive-data": "データマスキングをすぐに試せるようサンプルデータベースを有効にする",- "enable-sample-databases-query-data": "すぐにクエリを試せるようサンプルデータベースを有効にする","password": "パスワード","password-confirm": "パスワードの確認","password-confirm-placeholder": "新しいパスワードを確認します","password-hint": "パスワードは制限設定に従う必要があります","password-mismatch": "新しいパスワードが一致しません","phone": "電話番号",- "phone-tips": "国コードを必ず含めてください +81xxxxxx",- "setup-failed": "プロフィールの更新に失敗しました。",- "setup-first-project": "最初のプロジェクトを設定",- "setup-scenario": {- "continue": "続行",- "create-database-change": {- "description": "変更を定義し、追跡可能なイシューを作成します。",- "title": "データベース変更を作成"- },- "mark-sensitive-data": {- "description": "機密カラムを特定してデータマスキングを適用します。",- "title": "機密データをマーク"- },- "outcome-title": "Bytebase で何をしたいですか?",- "query-data": {- "description": "SQL Editor を開き、データベースでステートメントを実行します。",- "title": "データをクエリ"- },- "workspace-usage": {- "solo": {- "description": "自分だけで Bytebase を使用します。",- "title": "自分だけ"- },- "team": {- "description": "他のメンバーと一緒に使用します。",- "title": "チームで使用"- },- "title": "Bytebase を誰と使用しますか?"- }- },- "setup-skip": "後で設定する",- "setup-steps": {- "scenario": "目標を選択",- "workspace": "ワークスペースを設定"- },- "setup-submit": "ワークスペースをセットアップ",- "setup-success": "プロフィールが更新されました。",- "workspace-name": "ワークスペース名",- "workspace-name-placeholder": "ワークスペース名を入力"+ "phone-tips": "国コードを必ず含めてください +81xxxxxx"},"sensitive-data": {"algorithms": {@@ -3884,6 +3841,123 @@"self": "二要素認証キー"}},+ "workspace-setup": {+ "continue": "続行",+ "elsewhere": {+ "continue": "ここで続行",+ "ended": "このセットアップは別のタブで終了しました",+ "saved": "このセットアップは別のタブで続行されました",+ "workspace": "ワークスペースへ移動"+ },+ "goal": {+ "change": {+ "description": "スキーマ変更またはデータ修正を作成し、SQLレビューでチェックしてからデータベースにロールアウトします。",+ "finish-line": "ゴール:SQLレビューを通過してロールアウトされた変更",+ "title": "データベース変更を計画・レビューしてロールアウトする"+ },+ "description": "ここに来た目的を選択してください。セットアップ完了後、最初にそれを提案します。",+ "explore": {+ "description": "まず簡単なクエリを提案します。方向は後で選べます。",+ "title": "まだ決めていない、試してみたい"+ },+ "query": {+ "description": "エディタからデータベースに対してSQLを実行します。すべてのステートメントがクエリ履歴に記録されます。",+ "finish-line": "ゴール:データベースからのクエリ結果",+ "title": "ガードレール付きでデータをクエリする"+ },+ "required": "続行するには1つ選択してください",+ "title": "最初に何をしますか?"+ },+ "optional": "任意",+ "panel": {+ "connected-after-setup": "セットアップ後に接続",+ "own-databases": "そのデータベース",+ "own-instance": "あなたのインスタンス",+ "sample-database": "サンプルデータベース",+ "sample-instance": "サンプルプロジェクトインスタンス",+ "workspace": "ワークスペース"+ },+ "project": {+ "database-title": "{{project}} のデータベース",+ "description": "Bytebase を使うにはデータベースが必要です。それを保持するプロジェクトに名前を付け、最初のデータベースの入手元を選択してください。",+ "exists": "このプロジェクトはすでに存在します。名前はプロジェクト設定で変更できます。",+ "name": "プロジェクト名",+ "name-hint": "プロジェクトは、チームが扱うデータベースをメンバーやポリシーとともにまとめます。すべての変更とクエリはプロジェクト内で行われます。",+ "name-optional-note": "空欄のままにすると、プロジェクトは後で作成できます。",+ "name-placeholder": "決済、データ基盤、社内ツール",+ "name-required": "プロジェクト名を入力してください",+ "own": {+ "description": "インスタンスとはお使いのデータベースサーバーです。先にセットアップを完了し、その後 {{project}} から接続します。",+ "title": "セットアップ後に自分のインスタンスを接続する"+ },+ "sample": {+ "description": "従業員のサンプルデータを含む PostgreSQL データベース1つ。Bytebase Cloud がホストします。インストール不要、7日間利用可能です。",+ "description-self-host": "従業員のサンプルデータを含む PostgreSQL データベース1つ。このサーバー上で動作します。インストール不要です。",+ "prepared": "サンプルデータベースはこのプロジェクトで利用できます。",+ "recommended": "おすすめ",+ "title": "サンプルデータベースで始める",+ "unavailable": "このサーバーではサンプルデータベースを利用できません。",+ "used": "このワークスペースはすでにサンプルデータベースを使用しています。"+ },+ "skip": "後で設定する",+ "title": "プロジェクトを作成してデータベースを選択",+ "your-project": "あなたのプロジェクト"+ },+ "steps": {+ "goal": "目的",+ "project": "プロジェクト",+ "team": "チーム",+ "workspace": "ワークスペース"+ },+ "team": {+ "address-invalid": "メールアドレスではありません",+ "address-own": "あなた自身のアドレスです",+ "address-placeholder": "[email protected]",+ "address-placeholder-more": "別のアドレス",+ "description": "完了前の最後の質問です。",+ "failed": {+ "invitees": "指定したメンバーを追加できませんでした。",+ "names": "名前とワークスペース名を保存できませんでした。",+ "project": "{{project}} を作成できませんでした。",+ "sample": "サンプルデータベースを準備できませんでした。"+ },+ "finish": "完了",+ "finish-invite_one": "{{count}} 件の招待を送信して完了",+ "finish-invite_other": "{{count}} 件の招待を送信して完了",+ "finish-without-sample": "サンプルなしで完了",+ "finishing": "セットアップ中…",+ "invite-teammates": "チームメンバーを招待",+ "members-enter": "アドレスごとに Enter キーを押してください。",+ "members-own": "データベースはインスタンスの接続後に表示されます。",+ "members-role": "{{project}} でクエリと変更の提案ができるメンバーとして参加します。",+ "members-roles-later": "ロールは「メンバー」でいつでも変更できます。",+ "progress": "{{project}} を作成中…",+ "progress-sample": "{{project}} とサンプルデータベースを作成中…",+ "remove-address": "{{email}} を削除",+ "size": "Bytebase を何人で使いますか?",+ "size-required": "完了するにはチームの人数を選択してください",+ "sizes": {+ "11-50": "11–50",+ "2-10": "2–10",+ "200-plus": "200+",+ "51-200": "51–200",+ "just-me": "自分だけ"+ },+ "title": "あなたのチーム",+ "try-again": "再試行"+ },+ "workspace": {+ "default-name": "{{name}} のワークスペース",+ "default-name-anonymous": "マイワークスペース",+ "description": "ワークスペース、プロジェクト、データベースがそろえば Bytebase を使い始められます。",+ "name-placeholder": "名前を入力",+ "title": "ワークスペースをセットアップ",+ "workspace-name": "ワークスペース名",+ "workspace-name-hint": "追加したメンバーは全員このワークスペースに参加します。",+ "workspace-name-placeholder": "通常は会社名",+ "workspace-name-required": "ワークスペース名を入力してください"+ }+ },"workspace-setup-guide": {"actions": {"query": "SQL Editor に移動"diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 0d7fa0fc12..9ad504db27 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2979,59 +2979,16 @@"workload-identity-tag-hint": "Để trống để cho phép tất cả tag"},"profile": {- "default-project-name": "Dự án mới","display-name": "Tên của bạn","display-name-placeholder": "Nhập tên của bạn","email": "Email",- "enable-sample-databases": "Bật cơ sở dữ liệu mẫu",- "enable-sample-databases-create-change": "Bật cơ sở dữ liệu mẫu làm đích thay đổi an toàn",- "enable-sample-databases-mark-sensitive-data": "Bật cơ sở dữ liệu mẫu để thử che dữ liệu ngay",- "enable-sample-databases-query-data": "Bật cơ sở dữ liệu mẫu để bắt đầu truy vấn ngay","password": "Mật khẩu","password-confirm": "Xác nhận mật khẩu","password-confirm-placeholder": "Xác nhận mật khẩu mới","password-hint": "Mật khẩu phải theo quy định hạn chế","password-mismatch": "Mật khẩu mới không khớp","phone": "Điện thoại",- "phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx",- "setup-failed": "Cập nhật hồ sơ thất bại.",- "setup-first-project": "Thiết lập dự án đầu tiên",- "setup-scenario": {- "continue": "Tiếp tục",- "create-database-change": {- "description": "Xác định thay đổi và tạo issue có thể theo dõi.",- "title": "Tạo thay đổi cơ sở dữ liệu"- },- "mark-sensitive-data": {- "description": "Xác định các cột nhạy cảm và áp dụng che dữ liệu.",- "title": "Đánh dấu dữ liệu nhạy cảm"- },- "outcome-title": "Bạn muốn làm gì với Bytebase?",- "query-data": {- "description": "Mở SQL Editor và chạy một câu lệnh trên cơ sở dữ liệu.",- "title": "Truy vấn dữ liệu"- },- "workspace-usage": {- "solo": {- "description": "Tôi sẽ tự sử dụng Bytebase.",- "title": "Chỉ mình tôi"- },- "team": {- "description": "Tôi sẽ làm việc cùng những người khác.",- "title": "Nhóm của tôi"- },- "title": "Ai sẽ sử dụng Bytebase cùng bạn?"- }- },- "setup-skip": "Để sau",- "setup-steps": {- "scenario": "Chọn mục tiêu",- "workspace": "Thiết lập không gian làm việc"- },- "setup-submit": "Thiết lập không gian làm việc của tôi",- "setup-success": "Hồ sơ đã được cập nhật.",- "workspace-name": "Tên không gian làm việc",- "workspace-name-placeholder": "Nhập tên không gian làm việc"+ "phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx"},"sensitive-data": {"algorithms": {@@ -3884,6 +3841,123 @@"self": "Bí mật hai yếu tố của bạn"}},+ "workspace-setup": {+ "continue": "Tiếp tục",+ "elsewhere": {+ "continue": "Tiếp tục tại đây",+ "ended": "Thiết lập này đã kết thúc ở một tab khác",+ "saved": "Thiết lập này đã được tiếp tục ở một tab khác",+ "workspace": "Đi tới không gian làm việc"+ },+ "goal": {+ "change": {+ "description": "Viết một thay đổi schema hoặc một bản sửa dữ liệu, để SQL review kiểm tra, rồi triển khai lên cơ sở dữ liệu.",+ "finish-line": "Đích đến: một thay đổi đã qua SQL review và được triển khai",+ "title": "Lập kế hoạch, review và triển khai một thay đổi cơ sở dữ liệu"+ },+ "description": "Chọn điều đã đưa bạn đến đây. Chúng tôi sẽ gợi ý nó đầu tiên khi thiết lập xong.",+ "explore": {+ "description": "Chúng tôi sẽ gợi ý một truy vấn nhanh để bắt đầu. Bạn có thể chọn hướng đi sau.",+ "title": "Chưa chắc, chỉ đang khám phá"+ },+ "query": {+ "description": "Chạy SQL trên cơ sở dữ liệu từ trình soạn thảo, mọi câu lệnh đều được ghi vào lịch sử truy vấn.",+ "finish-line": "Đích đến: một kết quả truy vấn từ cơ sở dữ liệu",+ "title": "Truy vấn dữ liệu có kiểm soát"+ },+ "required": "Chọn một mục để tiếp tục",+ "title": "Bạn muốn làm gì trước?"+ },+ "optional": "tùy chọn",+ "panel": {+ "connected-after-setup": "Kết nối sau khi thiết lập",+ "own-databases": "Các cơ sở dữ liệu của nó",+ "own-instance": "Phiên bản của bạn",+ "sample-database": "Cơ sở dữ liệu mẫu",+ "sample-instance": "Phiên bản dự án mẫu",+ "workspace": "Không gian làm việc"+ },+ "project": {+ "database-title": "Cơ sở dữ liệu cho {{project}}",+ "description": "Bytebase cần một cơ sở dữ liệu để hoạt động. Đặt tên cho dự án sẽ chứa nó, rồi chọn nguồn của cơ sở dữ liệu đầu tiên.",+ "exists": "Dự án này đã tồn tại. Đổi tên trong phần cài đặt của dự án.",+ "name": "Tên dự án",+ "name-hint": "Dự án nhóm các cơ sở dữ liệu mà một nhóm làm việc cùng, kèm thành viên và chính sách. Mọi thay đổi và truy vấn đều diễn ra trong một dự án.",+ "name-optional-note": "Để trống để tạo dự án sau.",+ "name-placeholder": "Thanh toán, Nền tảng dữ liệu, Công cụ nội bộ",+ "name-required": "Nhập tên dự án",+ "own": {+ "description": "Phiên bản là máy chủ cơ sở dữ liệu của bạn. Thiết lập hoàn tất trước; sau đó bạn kết nối nó từ {{project}}.",+ "title": "Kết nối phiên bản của tôi sau khi thiết lập"+ },+ "sample": {+ "description": "Một cơ sở dữ liệu PostgreSQL với dữ liệu mẫu về nhân viên, do Bytebase Cloud lưu trữ. Không cần cài đặt; có sẵn trong 7 ngày.",+ "description-self-host": "Một cơ sở dữ liệu PostgreSQL với dữ liệu mẫu về nhân viên, chạy trên máy chủ này. Không cần cài đặt.",+ "prepared": "Cơ sở dữ liệu mẫu đã sẵn sàng trong dự án này.",+ "recommended": "Khuyến nghị",+ "title": "Bắt đầu với cơ sở dữ liệu mẫu",+ "unavailable": "Cơ sở dữ liệu mẫu không có sẵn trên máy chủ này.",+ "used": "Không gian làm việc này đã dùng cơ sở dữ liệu mẫu của mình."+ },+ "skip": "Để sau",+ "title": "Tạo dự án và chọn cơ sở dữ liệu",+ "your-project": "dự án của bạn"+ },+ "steps": {+ "goal": "Mục tiêu",+ "project": "Dự án",+ "team": "Nhóm",+ "workspace": "Không gian làm việc"+ },+ "team": {+ "address-invalid": "Không phải địa chỉ email",+ "address-own": "Địa chỉ của chính bạn",+ "address-placeholder": "[email protected]",+ "address-placeholder-more": "Địa chỉ khác",+ "description": "Một câu hỏi trước khi hoàn tất.",+ "failed": {+ "invitees": "Không thể thêm những người bạn đã liệt kê.",+ "names": "Không thể lưu tên của bạn và tên không gian làm việc.",+ "project": "Không thể tạo {{project}}.",+ "sample": "Không thể chuẩn bị cơ sở dữ liệu mẫu."+ },+ "finish": "Hoàn tất",+ "finish-invite_one": "Gửi {{count}} lời mời và hoàn tất",+ "finish-invite_other": "Gửi {{count}} lời mời và hoàn tất",+ "finish-without-sample": "Hoàn tất mà không dùng mẫu",+ "finishing": "Đang thiết lập…",+ "invite-teammates": "Mời đồng đội",+ "members-enter": "Nhấn Enter sau mỗi địa chỉ.",+ "members-own": "Các cơ sở dữ liệu sẽ xuất hiện khi phiên bản của bạn được kết nối.",+ "members-role": "Họ tham gia với tư cách thành viên có thể truy vấn và đề xuất thay đổi trong {{project}}.",+ "members-roles-later": "Đổi vai trò bất cứ lúc nào trong Thành viên.",+ "progress": "Đang tạo {{project}}…",+ "progress-sample": "Đang tạo {{project}} và cơ sở dữ liệu mẫu…",+ "remove-address": "Xóa {{email}}",+ "size": "Bao nhiêu người sẽ dùng Bytebase?",+ "size-required": "Chọn quy mô nhóm để hoàn tất",+ "sizes": {+ "11-50": "11–50",+ "2-10": "2–10",+ "200-plus": "200+",+ "51-200": "51–200",+ "just-me": "Chỉ mình tôi"+ },+ "title": "Nhóm của bạn",+ "try-again": "Thử lại"+ },+ "workspace": {+ "default-name": "Không gian làm việc của {{name}}",+ "default-name-anonymous": "Không gian làm việc của tôi",+ "description": "Bytebase sẵn sàng khi có một không gian làm việc, một dự án và một cơ sở dữ liệu.",+ "name-placeholder": "Nhập tên của bạn",+ "title": "Thiết lập không gian làm việc",+ "workspace-name": "Tên không gian làm việc",+ "workspace-name-hint": "Mọi người bạn thêm đều tham gia không gian làm việc này.",+ "workspace-name-placeholder": "Thường là công ty của bạn",+ "workspace-name-required": "Nhập tên không gian làm việc"+ }+ },"workspace-setup-guide": {"actions": {"query": "Đi tới SQL Editor"diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex ca4e40d551..d10a8f5e67 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2979,59 +2979,16 @@"workload-identity-tag-hint": "留空则允许所有标签"},"profile": {- "default-project-name": "新项目","display-name": "您的姓名","display-name-placeholder": "输入您的姓名","email": "邮箱",- "enable-sample-databases": "启用示例数据库",- "enable-sample-databases-create-change": "启用示例数据库作为安全的变更目标",- "enable-sample-databases-mark-sensitive-data": "启用示例数据库以立即试用数据脱敏",- "enable-sample-databases-query-data": "启用示例数据库以立即开始查询","password": "密码","password-confirm": "确认密码","password-confirm-placeholder": "确认新密码","password-hint": "密码应遵循限制设置","password-mismatch": "新密码不匹配","phone": "手机号",- "phone-tips": "请包含国家代码前缀 +86xxxxxx",- "setup-failed": "更新个人资料失败。",- "setup-first-project": "设置第一个项目",- "setup-scenario": {- "continue": "继续",- "create-database-change": {- "description": "定义变更并创建可追踪的工单。",- "title": "创建数据库变更"- },- "mark-sensitive-data": {- "description": "识别敏感列并应用数据脱敏。",- "title": "标记敏感数据"- },- "outcome-title": "您想使用 Bytebase 做什么?",- "query-data": {- "description": "打开 SQL Editor 并对数据库运行一条语句。",- "title": "查询数据"- },- "workspace-usage": {- "solo": {- "description": "我会独自使用 Bytebase。",- "title": "仅我自己"- },- "team": {- "description": "我会和其他成员一起使用。",- "title": "我的团队"- },- "title": "谁会和您一起使用 Bytebase?"- }- },- "setup-skip": "稍后再说",- "setup-steps": {- "scenario": "选择目标",- "workspace": "设置工作空间"- },- "setup-submit": "设置我的工作空间",- "setup-success": "个人资料已更新。",- "workspace-name": "工作空间名称",- "workspace-name-placeholder": "输入工作空间名称"+ "phone-tips": "请包含国家代码前缀 +86xxxxxx"},"sensitive-data": {"algorithms": {@@ -3884,6 +3841,123 @@"self": "双重认证密钥"}},+ "workspace-setup": {+ "continue": "继续",+ "elsewhere": {+ "continue": "在此继续",+ "ended": "此设置已在另一个标签页中结束",+ "saved": "此设置已在另一个标签页中继续",+ "workspace": "前往工作空间"+ },+ "goal": {+ "change": {+ "description": "编写一个 Schema 变更或数据修复,由 SQL 审核检查后部署到数据库。",+ "finish-line": "终点:一个通过 SQL 审核并完成部署的变更",+ "title": "规划、审核并部署数据库变更"+ },+ "description": "选择您来这里想做的事。设置完成后,我们会优先推荐它。",+ "explore": {+ "description": "我们会先推荐一条简单的查询,方向可以之后再选。",+ "title": "还不确定,先看看"+ },+ "query": {+ "description": "在编辑器中对数据库执行 SQL,每条语句都会记录在查询历史中。",+ "finish-line": "终点:一条来自数据库的查询结果",+ "title": "在安全防护下查询数据"+ },+ "required": "请选择一项以继续",+ "title": "您想先做什么?"+ },+ "optional": "可选",+ "panel": {+ "connected-after-setup": "设置完成后连接",+ "own-databases": "其中的数据库",+ "own-instance": "您的实例",+ "sample-database": "示例数据库",+ "sample-instance": "示例项目实例",+ "workspace": "工作空间"+ },+ "project": {+ "database-title": "{{project}} 的数据库",+ "description": "Bytebase 需要数据库才能工作。请先为承载它的项目命名,再选择第一个数据库的来源。",+ "exists": "该项目已存在,可在项目设置中重命名。",+ "name": "项目名称",+ "name-hint": "项目把一个团队使用的数据库与其成员和策略组织在一起。每次变更和查询都发生在某个项目中。",+ "name-optional-note": "留空则稍后再创建项目。",+ "name-placeholder": "支付、数据平台、内部工具",+ "name-required": "请输入项目名称",+ "own": {+ "description": "实例即您的数据库服务器。设置会先完成,之后您在 {{project}} 中连接它。",+ "title": "设置完成后连接我自己的实例"+ },+ "sample": {+ "description": "一个包含员工示例数据的 PostgreSQL 数据库,由 Bytebase Cloud 托管。无需安装,可用 7 天。",+ "description-self-host": "一个包含员工示例数据的 PostgreSQL 数据库,运行在本服务器上。无需安装。",+ "prepared": "示例数据库已在该项目中就绪。",+ "recommended": "推荐",+ "title": "从示例数据库开始",+ "unavailable": "本服务器不提供示例数据库。",+ "used": "该工作空间已使用过示例数据库。"+ },+ "skip": "稍后再说",+ "title": "创建项目并选择其数据库",+ "your-project": "您的项目"+ },+ "steps": {+ "goal": "目标",+ "project": "项目",+ "team": "团队",+ "workspace": "工作空间"+ },+ "team": {+ "address-invalid": "不是邮箱地址",+ "address-own": "这是您自己的地址",+ "address-placeholder": "[email protected]",+ "address-placeholder-more": "再添加一个地址",+ "description": "完成前的最后一个问题。",+ "failed": {+ "invitees": "无法添加您列出的人员。",+ "names": "无法保存您的姓名和工作空间名称。",+ "project": "无法创建 {{project}}。",+ "sample": "无法准备示例数据库。"+ },+ "finish": "完成",+ "finish-invite_one": "发送 {{count}} 份邀请并完成",+ "finish-invite_other": "发送 {{count}} 份邀请并完成",+ "finish-without-sample": "不使用示例数据库并完成",+ "finishing": "正在设置…",+ "invite-teammates": "邀请团队成员",+ "members-enter": "每输入一个地址后按回车。",+ "members-own": "连接实例后,其中的数据库才会出现。",+ "members-role": "他们将作为成员加入,可在 {{project}} 中查询并提交变更。",+ "members-roles-later": "可随时在“成员”中更改角色。",+ "progress": "正在创建 {{project}}…",+ "progress-sample": "正在创建 {{project}} 及其示例数据库…",+ "remove-address": "移除 {{email}}",+ "size": "有多少人会使用 Bytebase?",+ "size-required": "请选择团队规模以完成",+ "sizes": {+ "11-50": "11–50",+ "2-10": "2–10",+ "200-plus": "200+",+ "51-200": "51–200",+ "just-me": "仅我自己"+ },+ "title": "您的团队",+ "try-again": "重试"+ },+ "workspace": {+ "default-name": "{{name}} 的工作空间",+ "default-name-anonymous": "我的工作空间",+ "description": "有了工作空间、项目和数据库,Bytebase 即可使用。",+ "name-placeholder": "输入您的姓名",+ "title": "设置您的工作空间",+ "workspace-name": "工作空间名称",+ "workspace-name-hint": "您添加的所有人都会加入该工作空间。",+ "workspace-name-placeholder": "通常是您的公司名称",+ "workspace-name-required": "请输入工作空间名称"+ }+ },"workspace-setup-guide": {"actions": {"query": "前往 SQL Editor"diff --git a/frontend/src/modules/workspace-setup-guide/scenarios.test.ts b/frontend/src/modules/workspace-setup-guide/scenarios.test.tsindex f28bb397a5..601e00cadb 100644--- a/frontend/src/modules/workspace-setup-guide/scenarios.test.ts+++ b/frontend/src/modules/workspace-setup-guide/scenarios.test.ts@@ -5,6 +5,8 @@ import {CREATE_DATABASE_CHANGE_SCENARIO,GUIDE_SCENARIO_REGISTRY,getGuideJourney,+ JUST_EXPLORING_SCENARIO,+ leadsWithQuery,MARK_SENSITIVE_DATA_SCENARIO,QUERY_DATA_SCENARIO,WORKSPACE_SETUP_JOURNEY,@@ -17,6 +19,7 @@ describe("workspace setup guide journeys", () => {"query-data","create-database-change","mark-sensitive-data",+ "just-exploring",]);});@@ -116,6 +119,18 @@ describe("workspace setup guide journeys", () => {]);});+ test("guides just exploring through the Query Data steps", () => {+ const journey = getGuideJourney("just-exploring");++ expect(journey.id).toBe("just-exploring");+ expect(journey.steps.map(({ stepId }) => stepId)).toEqual([+ "create-project",+ "connect-instance",+ "explore-database",+ "query-data",+ ]);+ });+test("uses workspace setup as visible database-change prerequisites", () => {expect(CREATE_DATABASE_CHANGE_SCENARIO.steps).toEqual([{ stepId: "create-project", kind: "prerequisite" },@@ -199,9 +214,23 @@ describe("workspace setup guide journeys", () => {QUERY_DATA_SCENARIO,CREATE_DATABASE_CHANGE_SCENARIO,MARK_SENSITIVE_DATA_SCENARIO,+ JUST_EXPLORING_SCENARIO,])("validates $id", (journey) => {expect(() =>validateGuideJourney(journey, GUIDE_STEP_DEFINITIONS)).not.toThrow();});++ test.each([+ ["query-data", true],+ ["just-exploring", true],+ ["create-database-change", false],+ ["mark-sensitive-data", false],+ [undefined, false],+ ] as const)(+ "says whether the goal %s leads with a query: %s",+ (goal, leads) => {+ expect(leadsWithQuery(goal)).toBe(leads);+ }+ );});diff --git a/frontend/src/modules/workspace-setup-guide/scenarios.ts b/frontend/src/modules/workspace-setup-guide/scenarios.tsindex 079f7c40d3..afe76cfb02 100644--- a/frontend/src/modules/workspace-setup-guide/scenarios.ts+++ b/frontend/src/modules/workspace-setup-guide/scenarios.ts@@ -54,14 +54,27 @@ export const MARK_SENSITIVE_DATA_SCENARIO: GuideJourney = {],};+// An undecided account gets the quickest first result, a query, under its own+// id so its share stays measurable.+export const JUST_EXPLORING_SCENARIO: GuideJourney = {+ id: "just-exploring",+ scenarioId: "just-exploring",+ steps: QUERY_DATA_SCENARIO.steps,+};+export const GUIDE_SCENARIO_REGISTRY: Readonly<Record<GuideScenarioId, GuideJourney>> = {"query-data": QUERY_DATA_SCENARIO,"create-database-change": CREATE_DATABASE_CHANGE_SCENARIO,"mark-sensitive-data": MARK_SENSITIVE_DATA_SCENARIO,+ "just-exploring": JUST_EXPLORING_SCENARIO,};+// The goals whose first step after setup is a query.+export const leadsWithQuery = (scenarioId: GuideScenarioId | undefined) =>+ scenarioId === "query-data" || scenarioId === "just-exploring";+export const isGuideScenarioId = (value: unknown): value is GuideScenarioId =>typeof value === "string" && Object.hasOwn(GUIDE_SCENARIO_REGISTRY, value);diff --git a/frontend/src/modules/workspace-setup-guide/selection.test.ts b/frontend/src/modules/workspace-setup-guide/selection.test.tsindex 7a6b45869b..587cc219df 100644--- a/frontend/src/modules/workspace-setup-guide/selection.test.ts+++ b/frontend/src/modules/workspace-setup-guide/selection.test.ts@@ -1,17 +1,19 @@import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import {+ storageKeyWorkspaceSetupDraft,storageKeyWorkspaceSetupFinished,storageKeyWorkspaceSetupGuideScenario,+ storageKeyWorkspaceSetupGuideTeamSize,storageKeyWorkspaceSetupGuideWorkspaceUsage,} from "@/utils/storage-keys";import { isGuideScenarioId } from "./scenarios";import {- clearGuideWorkspaceUsage,- clearSelectedGuideScenarioId,+ hasWorkspaceSetupDraft,isGuideWorkspaceUsage,+ readGuideTeamSize,readGuideWorkspaceUsage,readSelectedGuideScenarioId,- saveGuideWorkspaceUsage,+ saveGuideTeamSize,saveSelectedGuideScenarioId,} from "./selection";import {@@ -109,11 +111,10 @@ describe("workspace setup guide scenario selection", () => {);});- test("clears a previous selection", () => {- expect(saveSelectedGuideScenarioId("query-data")).toBe(true);+ test("stores just exploring as a goal of its own", () => {+ expect(saveSelectedGuideScenarioId("just-exploring")).toBe(true);- expect(clearSelectedGuideScenarioId()).toBe(true);- expect(readSelectedGuideScenarioId()).toBeUndefined();+ expect(readSelectedGuideScenarioId()).toBe("just-exploring");});test("isolates selections by workspace", () => {@@ -155,14 +156,54 @@ describe("workspace setup guide workspace usage", () => {});- test.each(["team", "solo"] as const)("stores %s workspace usage", (value) => {- expect(saveGuideWorkspaceUsage(value)).toBe(true);- expect(readGuideWorkspaceUsage()).toBe(value);+ test.each(["team", "solo"] as const)(+ "reads the %s answer an earlier setup stored",+ (value) => {+ seedWorkspaceUsage(value);++ expect(readGuideWorkspaceUsage()).toBe(value);+ }+ );++ test.each(["2-10", "11-50", "51-200", "200+"] as const)(+ "reads a team of %s as team usage",+ (size) => {+ expect(saveGuideTeamSize(size)).toBe(true);++ expect(readGuideTeamSize()).toBe(size);+ expect(readGuideWorkspaceUsage()).toBe("team");+ }+ );++ test("reads Just me as solo usage, over an earlier stored answer", () => {+ seedWorkspaceUsage("team");+ expect(saveGuideTeamSize("just-me")).toBe(true);++ expect(readGuideWorkspaceUsage()).toBe("solo");});- test("clears a previous workspace usage", () => {- expect(saveGuideWorkspaceUsage("team")).toBe(true);- expect(clearGuideWorkspaceUsage()).toBe(true);+ const teamSizeStorageKey = () =>+ storageKeyWorkspaceSetupGuideTeamSize(+ mocks.state.currentUser.workspace,+ mocks.state.currentUser.email+ );++ test("keeps the team size under its own key, per workspace and user", () => {+ expect(saveGuideTeamSize("11-50")).toBe(true);++ expect(teamSizeStorageKey()).toBe(+ "bb.workspace-setup-guide.team-size.workspaces/[email protected]"+ );+ expect(localStorage.getItem(teamSizeStorageKey())).toBe('"11-50"');++ mocks.state.currentUser.workspace = "workspaces/ws2";+ expect(readGuideTeamSize()).toBeUndefined();+ });++ test("ignores a team size it does not know", () => {+ localStorage.setItem(teamSizeStorageKey(), JSON.stringify("1000+"));++ expect(readGuideTeamSize()).toBeUndefined();expect(readGuideWorkspaceUsage()).toBeUndefined();});});@@ -199,3 +240,28 @@ describe("workspace setup completion", () => {expect(readWorkspaceSetupFinished("workspaces/ws1")).toBeUndefined();});});++describe("workspace setup draft", () => {+ beforeEach(() => {+ localStorage.clear();+ });++ test("is found only for this workspace and user", () => {+ localStorage.setItem(+ storageKeyWorkspaceSetupDraft("workspaces/ws2", "[email protected]"),+ "{}"+ );+ localStorage.setItem(+ storageKeyWorkspaceSetupDraft("workspaces/ws1", "[email protected]"),+ "{}"+ );+ expect(hasWorkspaceSetupDraft()).toBe(false);++ localStorage.setItem(+ storageKeyWorkspaceSetupDraft("workspaces/ws1", "[email protected]"),+ "{}"+ );++ expect(hasWorkspaceSetupDraft()).toBe(true);+ });+});diff --git a/frontend/src/modules/workspace-setup-guide/selection.ts b/frontend/src/modules/workspace-setup-guide/selection.tsindex eb110a75f2..ae624cc408 100644--- a/frontend/src/modules/workspace-setup-guide/selection.ts+++ b/frontend/src/modules/workspace-setup-guide/selection.ts@@ -6,90 +6,95 @@ import {writeJson,} from "@/stores/app/utils";import {+ storageKeyWorkspaceSetupDraft,storageKeyWorkspaceSetupGuideScenario,+ storageKeyWorkspaceSetupGuideTeamSize,storageKeyWorkspaceSetupGuideWorkspaceUsage,} from "@/utils/storage-keys";import { isGuideScenarioId } from "./scenarios";-import type { GuideScenarioId, GuideWorkspaceUsage } from "./types";--export { isGuideScenarioId };+import {+ GUIDE_TEAM_SIZES,+ type GuideScenarioId,+ type GuideTeamSize,+ type GuideWorkspaceUsage,+} from "./types";export const isGuideWorkspaceUsage = (value: unknown): value is GuideWorkspaceUsage => value === "team" || value === "solo";-const selectionStorageKey = () => {- const get = useAppStore.getState;- const email = getCurrentUserEmail(get);- const scope = getWorkspaceResourceScope(get);- if (!email || !scope) return undefined;- return storageKeyWorkspaceSetupGuideScenario(scope, email);-};+export const isGuideTeamSize = (value: unknown): value is GuideTeamSize =>+ (GUIDE_TEAM_SIZES as readonly unknown[]).includes(value);-const workspaceUsageStorageKey = () => {+// Setup's answers are kept per workspace and per user, in this browser only.+// Undefined until both are known.+export const setupStorageKey = (+ build: (scope: string, email: string) => string+): string | undefined => {const get = useAppStore.getState;const email = getCurrentUserEmail(get);const scope = getWorkspaceResourceScope(get);if (!email || !scope) return undefined;- return storageKeyWorkspaceSetupGuideWorkspaceUsage(scope, email);+ return build(scope, email);};-export const readSelectedGuideScenarioId = (): GuideScenarioId | undefined => {- const key = selectionStorageKey();+const readSetupAnswer = <T>(+ build: (scope: string, email: string) => string,+ isValid: (value: unknown) => value is T+): T | undefined => {+ const key = setupStorageKey(build);if (!key) return undefined;const value = readJson<unknown>(key, undefined);- return isGuideScenarioId(value) ? value : undefined;+ return isValid(value) ? value : undefined;};-export const saveSelectedGuideScenarioId = (id: GuideScenarioId): boolean => {- const key = selectionStorageKey();+// False when the answer was not stored: storage that is full or blocked must+// not stop setup.+export const saveSetupAnswer = (+ build: (scope: string, email: string) => string,+ value: unknown+): boolean => {+ const key = setupStorageKey(build);if (!key) return false;try {- writeJson(key, id);+ writeJson(key, value);return true;} catch {return false;}};-export const clearSelectedGuideScenarioId = (): boolean => {- const key = selectionStorageKey();+// True while setup this account began in this browser has neither finished+// nor been skipped.+export const hasWorkspaceSetupDraft = () => {+ const key = setupStorageKey(storageKeyWorkspaceSetupDraft);if (!key) return false;try {- localStorage.removeItem(key);- return true;+ return localStorage.getItem(key) !== null;} catch {return false;}};-export const readGuideWorkspaceUsage = (): GuideWorkspaceUsage | undefined => {- const key = workspaceUsageStorageKey();- if (!key) return undefined;- const value = readJson<unknown>(key, undefined);- return isGuideWorkspaceUsage(value) ? value : undefined;-};+export const readSelectedGuideScenarioId = () =>+ readSetupAnswer(storageKeyWorkspaceSetupGuideScenario, isGuideScenarioId);-export const saveGuideWorkspaceUsage = (- value: GuideWorkspaceUsage-): boolean => {- const key = workspaceUsageStorageKey();- if (!key) return false;- try {- writeJson(key, value);- return true;- } catch {- return false;- }-};+export const saveSelectedGuideScenarioId = (id: GuideScenarioId) =>+ saveSetupAnswer(storageKeyWorkspaceSetupGuideScenario, id);-export const clearGuideWorkspaceUsage = (): boolean => {- const key = workspaceUsageStorageKey();- if (!key) return false;- try {- localStorage.removeItem(key);- return true;- } catch {- return false;- }+export const readGuideTeamSize = () =>+ readSetupAnswer(storageKeyWorkspaceSetupGuideTeamSize, isGuideTeamSize);++export const saveGuideTeamSize = (value: GuideTeamSize) =>+ saveSetupAnswer(storageKeyWorkspaceSetupGuideTeamSize, value);++// The team size answers this for accounts set up since the wizard asked for+// it; the stored usage is what earlier accounts answered.+export const readGuideWorkspaceUsage = (): GuideWorkspaceUsage | undefined => {+ const teamSize = readGuideTeamSize();+ if (teamSize) return teamSize === "just-me" ? "solo" : "team";+ return readSetupAnswer(+ storageKeyWorkspaceSetupGuideWorkspaceUsage,+ isGuideWorkspaceUsage+ );};diff --git a/frontend/src/modules/workspace-setup-guide/types.ts b/frontend/src/modules/workspace-setup-guide/types.tsindex 264a608100..98a76f0b47 100644--- a/frontend/src/modules/workspace-setup-guide/types.ts+++ b/frontend/src/modules/workspace-setup-guide/types.ts@@ -12,10 +12,21 @@ export type GuideStepId =export type GuideScenarioId =| "query-data"| "create-database-change"- | "mark-sensitive-data";+ | "mark-sensitive-data"+ | "just-exploring";export type GuideWorkspaceUsage = "team" | "solo";+export const GUIDE_TEAM_SIZES = [+ "just-me",+ "2-10",+ "11-50",+ "51-200",+ "200+",+] as const;++export type GuideTeamSize = (typeof GUIDE_TEAM_SIZES)[number];+export type GuideQueryTarget = {schema: string;table: string;diff --git a/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx b/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsxindex f7f477bbef..e942dd8b1f 100644--- a/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx+++ b/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import {PROJECT_V1_ROUTE_DATABASES,PROJECT_V1_ROUTE_DATABASE_DETAIL,+ PROJECT_V1_ROUTE_DETAIL,SQL_EDITOR_DATABASE_MODULE,} from "@/app/router/handles";import { planEvents } from "@/lib/plan/events";@@ -293,7 +294,10 @@ describe("useGuideContext", () => {expect(result.current.context.hasMarkedSensitiveData).toBe(true);});- test("resolves the first table for the query-data action", async () => {+ test.each([+ "query-data",+ "just-exploring",+ ] as const)("resolves the first table for the %s query action", async (scenarioId) => {mockDiscoveredDatabase();const database = "instances/sample/databases/employee";mocks.metadataByDatabase[database] = create(DatabaseMetadataSchema, {@@ -309,7 +313,7 @@ describe("useGuideContext", () => {enabled: true,dismissed: false,route: home,- scenarioId: "query-data",+ scenarioId,});await waitFor(() =>@@ -324,6 +328,22 @@ describe("useGuideContext", () => {});});+ test.each([+ undefined,+ "create-database-change",+ ] as const)("reads no table for the goal %s, which has no query step", async (scenarioId) => {+ mockDiscoveredDatabase();+ const { result } = renderGuideContext({+ enabled: true,+ dismissed: false,+ route: home,+ scenarioId,+ });++ await waitFor(() => expect(result.current.contextReady).toBe(true));+ expect(mocks.getOrFetchDatabaseMetadata).not.toHaveBeenCalled();+ });+test("resolves the marked table for the masking verification action", async () => {mockDiscoveredDatabase();const database = "instances/sample/databases/employee";@@ -703,6 +723,58 @@ describe("useGuideContext", () => {});});+ test("records arriving on a project home that lists a database as exploration", async () => {+ mockDiscoveredDatabase();+ const { result } = renderGuideContext({+ enabled: true,+ dismissed: false,+ route: {+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "app" },+ },+ });++ await waitFor(() =>+ expect(result.current.context.hasExploredDatabase).toBe(true)+ );+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({+ key: GUIDE_PROGRESS_KEYS.databaseExplored,+ newState: true,+ });+ });++ test("does not record another project's home as exploration", async () => {+ mockDiscoveredDatabase();+ const { result } = renderGuideContext({+ enabled: true,+ dismissed: false,+ route: {+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "other" },+ },+ });++ await waitFor(() => expect(result.current.contextReady).toBe(true));+ expect(result.current.context.hasExploredDatabase).toBe(false);+ expect(mocks.saveIntroStateByKey).not.toHaveBeenCalledWith(+ expect.objectContaining({ key: GUIDE_PROGRESS_KEYS.databaseExplored })+ );+ });++ test("does not record an empty project home as exploration", async () => {+ const { result } = renderGuideContext({+ enabled: true,+ dismissed: false,+ route: {+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "app" },+ },+ });++ await waitFor(() => expect(result.current.contextReady).toBe(true));+ expect(result.current.context.hasExploredDatabase).toBe(false);+ });+test("does not record an empty project database page as exploration", async () => {const { result } = renderGuideContext({enabled: true,diff --git a/frontend/src/modules/workspace-setup-guide/useGuideContext.ts b/frontend/src/modules/workspace-setup-guide/useGuideContext.tsindex e637a2f383..a7622dc687 100644--- a/frontend/src/modules/workspace-setup-guide/useGuideContext.ts+++ b/frontend/src/modules/workspace-setup-guide/useGuideContext.ts@@ -3,6 +3,7 @@ import {INSTANCE_ROUTE_DATABASE_DETAIL,PROJECT_V1_ROUTE_DATABASE_DETAIL,PROJECT_V1_ROUTE_DATABASES,+ PROJECT_V1_ROUTE_DETAIL,SQL_EDITOR_DATABASE_MODULE,} from "@/app/router/handles";import { useIntroStateByKey } from "@/hooks/useAppState";@@ -20,6 +21,7 @@ import {findGuideQueryTarget,tableHasMarkedSensitiveData,} from "./queryTarget";+import { getGuideJourney } from "./scenarios";import type {GuideContext,GuideRoute,@@ -107,13 +109,15 @@ const isConcreteDatabaseRoute = (}};+// The project home lists the project's databases too, so setup that ends+// there with the sample has already shown one.const isPopulatedProjectDatabaseRoute = (name: string | undefined,params: Record<string, string | string[] | undefined>,databaseProjectName: string,databaseName: string) =>- name === PROJECT_V1_ROUTE_DATABASES &&+ (name === PROJECT_V1_ROUTE_DATABASES || name === PROJECT_V1_ROUTE_DETAIL) &&!!databaseName &¶ms.projectId === extractProjectResourceName(databaseProjectName);@@ -370,8 +374,9 @@ export const useGuideContext = ({const database = databases?.databases.find(({ name, project }) => !!name && !!project);- const shouldPrepareQuery =- scenarioId === "query-data" || scenarioId === "mark-sensitive-data";+ const shouldPrepareQuery = getGuideJourney(scenarioId).steps.some(+ ({ stepId }) => stepId === "query-data"+ );const [metadata, catalog] = database? await Promise.all([shouldPrepareQuerydiff --git a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsxindex 549650b9a0..967e2354e6 100644--- a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx@@ -1,1138 +1,3696 @@-import { fireEvent } from "@testing-library/react";-import type { ReactElement } from "react";-import { act } from "react";-import { createRoot } from "react-dom/client";-import { beforeEach, describe, expect, test, vi } from "vitest";+import { Code, ConnectError } from "@connectrpc/connect";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { useState } from "react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { skipErrorNotificationContextKey } from "@/api/context-key";+import { SplashPanelContext } from "@/app/layouts/SplashLayout";+import {+ PROJECT_V1_ROUTE_DASHBOARD,+ PROJECT_V1_ROUTE_DETAIL,+} from "@/app/router/handles";+import "@/lib/i18n";+import {+ CREATE_PROJECT_PRODUCT_INTRO,+ PRODUCT_INTRO_QUERY_KEY,+} from "@/lib/productIntro";+import {+ readGuideTeamSize,+ readSelectedGuideScenarioId,+} from "@/modules/workspace-setup-guide/selection";+import { readWorkspaceSetupFinished } from "@/modules/workspace-setup-guide/setup";import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";import type { Workspace } from "@/types/proto-es/v1/workspace_service_pb";--(- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }-).IS_REACT_ACT_ENVIRONMENT = true;+import { storageKeyWorkspaceSetupDraft } from "@/utils/storage-keys";const mocks = vi.hoisted(() => ({+ currentUser: {} as User,+ workspace: {} as Workspace,+ workspacePolicy: {} as IamPolicy,canUpdateWorkspace: true,- currentUser: {- name: "users/[email protected]",- email: "[email protected]",- title: "Ed",- } as User,- workspace: {- name: "workspaces/ws1",- title: "Workspace One",- } as Workspace,- workspacePolicy: {- bindings: [- {- role: "roles/workspaceAdmin",- members: ["users/[email protected]"],- },- ],- } as IamPolicy,+ isSaaSMode: true,+ sample: { available: true, instances: [] as Array<{ instance: string }> },+ introState: {} as Record<string, boolean>,+ saveIntroStateByKey: vi.fn(),updateUser: vi.fn(),updateWorkspace: vi.fn(),createProject: vi.fn(),- prepareSampleProjectInstance: vi.fn(),setRecentProject: vi.fn(),+ fetchProject: vi.fn(),+ getProject: vi.fn(),+ fetchWorkspaceIamPolicy: vi.fn(),+ prepareSampleProjectInstance: vi.fn(),+ getProjectIamPolicy: vi.fn(),+ updateProjectIamPolicy: vi.fn(),+ patchWorkspaceIamPolicy: vi.fn(),routerReplace: vi.fn(),captureMetric: vi.fn(),- introState: {} as Record<string, boolean>,- saveIntroStateByKey: vi.fn(),- clearGuideWorkspaceUsage: vi.fn(),- clearSelectedGuideScenarioId: vi.fn(),- saveGuideWorkspaceUsage: vi.fn(),- saveSelectedGuideScenarioId: vi.fn(),- saveWorkspaceSetupFinished: vi.fn(() => true),- pushNotification: vi.fn(),- hasWorkspacePermissionV2: vi.fn(() => false),- canCreateProject: true,- sampleAvailable: true,- sampleInstances: [] as Array<{ instance: string }>,- isSaaSMode: false,}));vi.mock("@/app/analytics/provider", () => ({- behaviorAnalytics: {- captureMetric: mocks.captureMetric,- },-}));--vi.mock("@/modules/workspace-setup-guide/selection", () => ({- clearGuideWorkspaceUsage: mocks.clearGuideWorkspaceUsage,- clearSelectedGuideScenarioId: mocks.clearSelectedGuideScenarioId,- isGuideWorkspaceUsage: (value: unknown) =>- value === "team" || value === "solo",- isGuideScenarioId: (value: unknown) =>- value === "query-data" || value === "create-database-change",- saveGuideWorkspaceUsage: mocks.saveGuideWorkspaceUsage,- saveSelectedGuideScenarioId: mocks.saveSelectedGuideScenarioId,-}));--vi.mock("@/modules/workspace-setup-guide/setup", () => ({- saveWorkspaceSetupFinished: mocks.saveWorkspaceSetupFinished,+ behaviorAnalytics: { captureMetric: mocks.captureMetric },}));vi.mock("@/hooks/useAppState", () => ({useCurrentUser: () => mocks.currentUser,useWorkspace: () => mocks.workspace,useWorkspacePermission: (permission: string) =>- permission === "bb.projects.create"- ? mocks.canCreateProject- : mocks.canUpdateWorkspace,- useCreateProject: () => ({- createProject: mocks.createProject,- setRecentProject: mocks.setRecentProject,- }),+ permission === "bb.workspaces.update" && mocks.canUpdateWorkspace,useIntroStateByKey: (key: string) => mocks.introState[key] ?? false,}));-vi.mock("@/stores/app", () => {+// The two reads Finish makes of the server itself, past the store's cache.+vi.mock("@/api", () => ({+ projectServiceClientConnect: {+ getProject: mocks.getProject,+ getIamPolicy: mocks.getProjectIamPolicy,+ },+}));++vi.mock("@/stores/app", async () => {+ const { useSyncExternalStore } = await import("react");+ const state = () => ({+ currentUser: mocks.currentUser,+ workspacePolicy: mocks.workspacePolicy,+ serverInfo: { sample: mocks.sample },+ isSaaSMode: () => mocks.isSaaSMode,+ updateUser: mocks.updateUser,+ updateWorkspace: mocks.updateWorkspace,+ createProject: mocks.createProject,+ setRecentProject: mocks.setRecentProject,+ fetchProject: mocks.fetchProject,+ prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,+ updateProjectIamPolicy: mocks.updateProjectIamPolicy,+ fetchWorkspaceIamPolicy: mocks.fetchWorkspaceIamPolicy,+ patchWorkspaceIamPolicy: mocks.patchWorkspaceIamPolicy,+ // As the real store: the roles `member` holds in the workspace policy.+ findWorkspaceRolesByMember: (member: string) =>+ mocks.workspacePolicy.bindings+ .filter((binding) => binding.members.includes(member))+ .map((binding) => binding.role),+ saveIntroStateByKey: mocks.saveIntroStateByKey,+ });+ // Read as the real store's hook reads, so a selector that returns a new+ // value on every call fails here as it would crash the page.const useAppStore = Object.assign(- (- selector: (state: {- workspacePolicy: IamPolicy;- updateUser: typeof mocks.updateUser;- updateWorkspace: typeof mocks.updateWorkspace;- prepareSampleProjectInstance: typeof mocks.prepareSampleProjectInstance;- serverInfo: {- sample: { available: boolean; instances: Array<{ instance: string }> };- };- isSaaSMode: () => boolean;- }) => unknown- ) =>- selector({- workspacePolicy: mocks.workspacePolicy,- updateUser: mocks.updateUser,- updateWorkspace: mocks.updateWorkspace,- prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,- serverInfo: {- sample: {- available: mocks.sampleAvailable,- instances: mocks.sampleInstances,- },- },- isSaaSMode: () => mocks.isSaaSMode,- }),- {- getState: () => ({- saveIntroStateByKey: mocks.saveIntroStateByKey,- }),- }+ (selector: (value: ReturnType<typeof state>) => unknown) =>+ useSyncExternalStore(+ () => () => {},+ () => selector(state())+ ),+ { getState: state });return { useAppStore };});vi.mock("@/app/router", async (importOriginal) => ({...(await importOriginal<typeof import("@/app/router")>()),- router: {- replace: mocks.routerReplace,- },-}));--vi.mock("@/components/ResourceIdField", async () => {- const React = await import("react");- return {- ResourceIdField: ({- value,- resourceTitle,- autoComplete,- onChange,- onValidationChange,- }: {- value: string;- resourceTitle?: string;- autoComplete?: string;- onChange?: (value: string) => void;- onValidationChange?: (valid: boolean) => void;- }) => {- React.useEffect(() => {- if (!resourceTitle) return;- onChange?.("new-project");- onValidationChange?.(true);- }, [onChange, onValidationChange, resourceTitle]);- return (- <input- data-testid="project-resource-id"- value={value}- autoComplete={autoComplete}- onChange={(event) => {- onChange?.(event.target.value);- onValidationChange?.(event.target.value.length > 0);- }}- />- );- },- };-});--vi.mock("@/stores", () => ({- pushNotification: mocks.pushNotification,-}));--vi.mock("@/utils", () => ({- extractInstanceResourceName: (name: string) =>- name.match(/(?:^|\/)instances\/([^/]+)/)?.[1] ?? "",- extractProjectResourceName: (name: string) => name.split("/").pop() ?? "",- hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,+ router: { replace: mocks.routerReplace },}));-vi.mock("@/components/UserAvatar", () => ({- UserAvatar: () => <div data-testid="user-avatar" />,+// The real project ID field, with its random suffix pinned: "Payments" gets+// the ID "payments-ab12".+vi.mock("@/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/utils")>()),+ randomString: () => "ab12",}));-vi.mock("react-i18next", () => ({- initReactI18next: { type: "3rdParty", init: () => {} },- useTranslation: () => ({- t: (key: string) =>- (- ({- "common.back": "Back",- "settings.profile.setup-scenario.outcome-title":- "What would you like to do with Bytebase?",- "settings.profile.setup-scenario.create-database-change.title":- "Create a database change",- "settings.profile.setup-scenario.create-database-change.description":- "Define a change and create its issue.",- "settings.profile.setup-scenario.query-data.title":- "Query data",- "settings.profile.setup-scenario.query-data.description":- "Open SQL Editor and run a statement.",- "settings.profile.setup-scenario.mark-sensitive-data.title":- "Mark sensitive data",- "settings.profile.setup-scenario.mark-sensitive-data.description":- "Identify sensitive columns and apply masking.",- "settings.profile.setup-scenario.workspace-usage.title":- "Who will use Bytebase with you?",- "settings.profile.setup-scenario.workspace-usage.team.title":- "My team",- "settings.profile.setup-scenario.workspace-usage.team.description":- "I will work with other people.",- "settings.profile.setup-scenario.workspace-usage.solo.title":- "Just me",- "settings.profile.setup-scenario.workspace-usage.solo.description":- "I will use Bytebase on my own.",- "settings.profile.setup-scenario.continue": "Continue",- "settings.profile.setup-steps.scenario": "Choose a goal",- "settings.profile.setup-steps.workspace": "Set up workspace",- "settings.profile.setup-first-project": "Setup 1st project",- "settings.profile.setup-skip": "I'll do this later",- "settings.profile.enable-sample-databases":- "Enable sample databases",- "settings.profile.enable-sample-databases-query-data":- "Enable sample databases to start querying immediately",- "settings.profile.enable-sample-databases-create-change":- "Enable sample databases as a safe change target",- "settings.profile.enable-sample-databases-mark-sensitive-data":- "Enable sample databases to try data masking immediately",- "settings.profile.setup-submit": "Setup my workspace",- "instance.prepare-sample-instance-failed":- "Failed to prepare Sample Project Instance.",- "settings.profile.default-project-name": "New project",- "settings.profile.create-project-description":- "Optional. If you create a project here, we will take you to its database page next.",- }) as Record<string, string>- )[key] ?? key,- }),-}));+import { WorkspaceSetupPage } from "./WorkspaceSetupPage";-let WorkspaceSetupPage: typeof import("./WorkspaceSetupPage").WorkspaceSetupPage;+// What the server holds. The stand-ins for its calls read and write this, so+// a project a create made is there for every later read, as on a real server.+const server = {+ projects: new Map<string, { name: string; title: string }>(),+ projectPolicy: {} as IamPolicy,+};+// Makes the next call of `write` take effect and then lose its answer.+const loseAnswerOf = (write: ReturnType<typeof vi.fn>) => {+ const run = write.getMockImplementation() as+ | ((...args: unknown[]) => unknown)+ | undefined;+ write.mockImplementationOnce(async (...args: unknown[]) => {+ await run?.(...args);+ throw unavailable();+ });+};+// Makes the next call of `write` lose its answer at once and take effect only+// when the returned function is called, as a request held up on its way.+const delayLostWrite = (write: ReturnType<typeof vi.fn>) => {+ const run = write.getMockImplementation() as (+ ...args: unknown[]+ ) => Promise<unknown>;+ let land = () => {};+ write.mockImplementationOnce(async (...args: unknown[]) => {+ land = () => void run(...args).catch(() => {});+ throw unavailable();+ });+ return () => land();+};+// Holds the next call of `call` until the returned function is called: the+// call then runs as usual, or fails with the error passed. Queue it while no+// one-time behavior of `call` waits, or the held call runs that behavior.+const holdNextCall = (call: ReturnType<typeof vi.fn>) => {+ const run = call.getMockImplementation() as+ | ((...args: unknown[]) => unknown)+ | undefined;+ let release: (error?: unknown) => void = () => {};+ const held = new Promise<unknown>((resolve) => {+ release = resolve;+ });+ call.mockImplementationOnce(async (...args: unknown[]) => {+ const error = await held;+ if (error) throw error;+ return run?.(...args);+ });+ return release;+};+// Lets every answer already given reach the page.+const settle = () =>+ act(() => new Promise((resolve) => setTimeout(resolve, 0)));++const CHANGE_GOAL = "Plan, review and roll out a database change";+const QUERY_GOAL = "Query data with guardrails";+const EXPLORING = "Not sure yet, just exploring";+const SAMPLE = "Start with the sample database";+const OWN_INSTANCE = "Connect my own instance after setup";+const ID_EXISTS = "The Project ID already exists. Please choose another one.";+const REPORT = { byCaller: true };++const continueButton = () => screen.getByRole("button", { name: "Continue" });+const backButton = () => screen.getByRole("button", { name: "Back" });+const finishButton = () => screen.getByRole("button", { name: /^Finish$/ });+const type = (field: HTMLElement, value: string) =>+ fireEvent.change(field, { target: { value } });++const choice = (title: string) => {+ const label = screen.getByText(title).closest("label");+ if (!label) throw new Error(`no choice titled ${title}`);+ return within(label).getByRole("radio");+};-const renderIntoContainer = (element: ReactElement) => {- const container = document.createElement("div");- const root = createRoot(container);- return {- container,- render: () => {- act(() => {- root.render(element);- });- },- unmount: () =>- act(() => {- root.unmount();- }),- };+// Finish's writes to the server, by name, in the order they were made.+const WRITES = {+ updateUser: mocks.updateUser,+ updateWorkspace: mocks.updateWorkspace,+ createProject: mocks.createProject,+ prepareSample: mocks.prepareSampleProjectInstance,+ projectMembers: mocks.updateProjectIamPolicy,+ workspaceMembers: mocks.patchWorkspaceIamPolicy,+};+const writes = () =>+ Object.entries(WRITES)+ .flatMap(([name, write]) =>+ write.mock.invocationCallOrder.map((at) => ({ name, at }))+ )+ .sort((a, b) => a.at - b.at)+ .map(({ name }) => name);++// The project policy Finish last wrote, binding by binding: a role listed+// twice would mean an earlier attempt's members were left in place.+const projectBindings = () => {+ const [, policy] = mocks.updateProjectIamPolicy.mock.calls.at(-1) as [+ string,+ IamPolicy,+ ];+ return policy.bindings.map((binding) => [binding.role, binding.members]);+};+const OWNER_BINDING = ["roles/projectOwner", ["user:[email protected]"]];+const DRAFT_KEY = storageKeyWorkspaceSetupDraft(+ "workspaces/ws1",+);+// What the browser tells this tab when another tab saves the draft, or+// removes it.+const anotherTab = (newValue: string | null) =>+ act(() => {+ window.dispatchEvent(+ new StorageEvent("storage", { key: DRAFT_KEY, newValue })+ );+ });+const anotherTabSaved = () => anotherTab(localStorage.getItem(DRAFT_KEY));+// A role given on the project from somewhere other than the wizard.+const grantElsewhere = (role: string, member: string) => {+ server.projectPolicy = {+ ...server.projectPolicy,+ bindings: server.projectPolicy.bindings.map((binding) =>+ binding.role === role+ ? { ...binding, members: [...binding.members, member] }+ : binding+ ),+ } as IamPolicy;+};+// The project policy as the server holds it, whoever wrote it last.+const serverBindings = () =>+ server.projectPolicy.bindings.map((binding) => [+ binding.role,+ binding.members,+ ]);++const eventsNamed = (event: string) =>+ mocks.captureMetric.mock.calls+ .map(([metric]) => metric as { event: string; properties: unknown })+ .filter((metric) => metric.event === event)+ .map((metric) => metric.properties);++const nameProject = async (name = "Payments") => {+ type(screen.getByLabelText(/^Project name/), name);+ await waitFor(() => expect(continueButton()).toBeEnabled());+};+const editProjectId = (id: string) => {+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));+ type(screen.getByPlaceholderText("Project ID"), id);};-const renderWorkspaceForm = () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- if (mocks.isSaaSMode) {- const labels = [...page.container.querySelectorAll("label")];- act(() => {- fireEvent.click(- labels.find((label) => label.textContent?.includes("Query data"))!- );- fireEvent.click(- labels.find((label) => label.textContent?.includes("Just me"))!- );- });- }- const continueWithoutSelection = [- ...page.container.querySelectorAll("button"),- ].find((button) => button.textContent === "Continue");- if (!continueWithoutSelection) throw new Error("Continue not found");- act(() => fireEvent.click(continueWithoutSelection));- return page;+const goToGoal = () => fireEvent.click(continueButton());+const goToProject = (goal = QUERY_GOAL) => {+ goToGoal();+ fireEvent.click(screen.getByText(goal));+ fireEvent.click(continueButton());+};+const goToTeam = async ({+ goal,+ database,+}: {+ goal?: string;+ database?: string;+} = {}) => {+ goToProject(goal);+ await nameProject();+ if (database) fireEvent.click(screen.getByText(database));+ fireEvent.click(continueButton());+};+const startAtProject = (goal?: string) => {+ const view = render(<WorkspaceSetupPage />);+ goToProject(goal);+ return view;+};+const startAtTeam = async (options?: { goal?: string; database?: string }) => {+ const view = render(<WorkspaceSetupPage />);+ await goToTeam(options);+ return view;};-beforeEach(async () => {- vi.clearAllMocks();+const invitees = (field = "Invite teammates") =>+ screen.getByRole("textbox", { name: new RegExp(`^${field}`) });+const enterAddress = (address: string, field?: string) => {+ type(invitees(field), address);+ fireEvent.keyDown(invitees(field), { key: "Enter" });+};+const finishAlone = () => {+ fireEvent.click(screen.getByText("Just me"));+ fireEvent.click(finishButton());+};+const finishInviting = (...addresses: string[]) => {+ fireEvent.click(screen.getByText("2–10"));+ for (const address of addresses) enterAddress(address);+ fireEvent.click(screen.getByRole("button", { name: /and finish$/ }));+};+const storeDraft = (draft: Record<string, unknown>) =>+ localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));+const landed = () =>+ waitFor(() => expect(mocks.routerReplace).toHaveBeenCalled());+const failed = () => screen.findByRole("alert");+const tryAgain = () =>+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+const finishAgain = () =>+ fireEvent.click(screen.getByRole("button", { name: /^Finish$|and finish$/ }));+function unavailable(message = "offline") {+ return new ConnectError(message, Code.Unavailable);+}+function alreadyExists() {+ return new ConnectError("already exists", Code.AlreadyExists);+}++beforeEach(() => {+ // Reset, not clear: a failure queued with `...Once` by a test that never+ // reached it must not fail the next test's first call.+ vi.resetAllMocks();+ localStorage.clear();+ mocks.currentUser = {+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Ed",+ workspace: "workspaces/ws1",+ } as User;+ mocks.workspace = {+ name: "workspaces/ws1",+ title: "Workspace One",+ } as Workspace;+ mocks.workspacePolicy = {+ bindings: [+ { role: "roles/workspaceAdmin", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;mocks.canUpdateWorkspace = true;- mocks.canCreateProject = true;- mocks.sampleAvailable = true;- mocks.sampleInstances = [];- mocks.isSaaSMode = false;+ mocks.isSaaSMode = true;+ mocks.sample = { available: true, instances: [] };mocks.introState = {};mocks.saveIntroStateByKey.mockImplementation(({ key, newState }) => {mocks.introState[key] = newState;});- mocks.workspacePolicy = {+ mocks.updateUser.mockResolvedValue({});+ mocks.updateWorkspace.mockResolvedValue({});+ server.projects.clear();+ server.projectPolicy = {+ etag: "1",bindings: [- {- role: "roles/workspaceAdmin",- members: ["users/[email protected]"],- },+ { role: "roles/projectOwner", members: ["user:[email protected]"] },],} as IamPolicy;- mocks.createProject.mockResolvedValue({- name: "projects/new-project",- title: "New Project",+ mocks.createProject.mockImplementation(async (title: string, id: string) => {+ const name = `projects/${id}`;+ if (server.projects.has(name)) {+ throw alreadyExists();+ }+ server.projects.set(name, { name, title });+ return { name, title };});- mocks.prepareSampleProjectInstance.mockResolvedValue({- name: "projects/new-project/instances/sample",+ // As the real store: undefined for a project that is not there.+ mocks.fetchProject.mockImplementation(async (name: string) =>+ server.projects.get(name)+ );+ mocks.getProject.mockImplementation(async ({ name }: { name: string }) => {+ const project = server.projects.get(name);+ if (!project) throw new ConnectError("not found", Code.NotFound);+ return project;});- ({ WorkspaceSetupPage } = await import("./WorkspaceSetupPage"));+ mocks.prepareSampleProjectInstance.mockResolvedValue({});+ mocks.getProjectIamPolicy.mockImplementation(+ async () => server.projectPolicy+ );+ // As the server: a write built on a policy it no longer holds is refused.+ mocks.updateProjectIamPolicy.mockImplementation(+ async (_project: string, policy: IamPolicy) => {+ if (policy.etag !== server.projectPolicy.etag) {+ throw new ConnectError("concurrent update", Code.Aborted);+ }+ server.projectPolicy = {+ ...policy,+ etag: String(Number(policy.etag) + 1),+ };+ return server.projectPolicy;+ }+ );+ mocks.fetchWorkspaceIamPolicy.mockImplementation(+ async () => mocks.workspacePolicy+ );+});++afterEach(() => {+ vi.restoreAllMocks();});describe("WorkspaceSetupPage", () => {- test("records setup page entry only once per lifecycle", () => {- const first = renderIntoContainer(<WorkspaceSetupPage />);- first.render();+ describe("screen 1, workspace", () => {+ test("arrives with both names filled in, Continue ready, and the keyboard in the first field", () => {+ render(<WorkspaceSetupPage />);- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup page entered",- properties: { setup_version: "v1" },- });- expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({- key: "workspace-setup.page-entered.v1",- newState: true,+ expect(+ screen.getByRole("heading", { name: "Set up your workspace" })+ ).toBeInTheDocument();+ expect(screen.getByLabelText(/^Your name/)).toHaveValue("Ed");+ expect(screen.getByLabelText(/^Your name/)).toHaveFocus();+ expect(screen.getByLabelText("Workspace name")).toHaveValue(+ "Workspace One"+ );+ expect(continueButton()).toBeEnabled();});- first.render();- first.unmount();+ test.each([+ {+ from: "a work address",+ email: "[email protected]",+ title: "[email protected]",+ name: "Peter Zhu",+ workspace: "Acme",+ },+ {+ from: "a tagged address at a hyphenated company",+ email: "[email protected]",+ title: "",+ name: "Peter Zhu",+ workspace: "Blue Sky",+ },+ {+ from: "a mail subdomain of the company",+ email: "[email protected]",+ title: "",+ name: "Peter",+ workspace: "Acme",+ },+ {+ from: "a shared mailbox, which names nobody",+ email: "[email protected]",+ title: "admin",+ name: "",+ workspace: "Acme",+ },+ {+ from: "a mailbox named for a team",+ email: "[email protected]",+ title: "",+ name: "",+ workspace: "Acme",+ },+ {+ from: "a mailbox that takes no replies",+ email: "[email protected]",+ title: "",+ name: "",+ workspace: "Acme",+ },+ {+ from: "a public mail domain, which names no company",+ email: "[email protected]",+ title: "",+ name: "Peter",+ workspace: "Peter's workspace",+ },+ {+ from: "a public mail provider's country domain",+ email: "[email protected]",+ title: "",+ name: "Taro",+ workspace: "Taro's workspace",+ },+ {+ from: "a public mail provider's subdomain",+ email: "[email protected]",+ title: "",+ name: "Wang",+ workspace: "Wang's workspace",+ },+ {+ from: "a number on a public mail domain, which names nobody",+ email: "[email protected]",+ title: "",+ name: "",+ workspace: "My workspace",+ },+ {+ from: "a shared mailbox on a public mail domain",+ email: "[email protected]",+ title: "",+ name: "",+ workspace: "My workspace",+ },+ ])("guesses the names of a new account from $from", (account) => {+ mocks.currentUser = {+ ...mocks.currentUser,+ name: `users/${account.email}`,+ email: account.email,+ title: account.title,+ } as User;+ mocks.workspace = {+ ...mocks.workspace,+ title: "Default workspace",+ } as Workspace;+ mocks.workspacePolicy = {+ bindings: [+ { role: "roles/workspaceAdmin", members: [`user:${account.email}`] },+ ],+ } as IamPolicy;++ render(<WorkspaceSetupPage />);++ expect(screen.getByLabelText(/^Your name/)).toHaveValue(account.name);+ expect(screen.getByLabelText("Workspace name")).toHaveValue(+ account.workspace+ );+ });- const second = renderIntoContainer(<WorkspaceSetupPage />);- second.render();+ test("takes the title an identity-provider signup gets for an unnamed workspace too", () => {+ mocks.currentUser = {+ ...mocks.currentUser,+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Peter Zhu",+ } as User;+ mocks.workspace = {+ ...mocks.workspace,+ title: "Default Workspace",+ } as Workspace;++ render(<WorkspaceSetupPage />);++ expect(screen.getByLabelText("Workspace name")).toHaveValue("Acme");+ });- expect(mocks.captureMetric).toHaveBeenCalledTimes(1);- second.unmount();- });+ test.each([+ "",+ " ",+ ])("explains under the field why a workspace name of %j blocks Continue", (emptied) => {+ render(<WorkspaceSetupPage />);+ const workspaceName = screen.getByLabelText("Workspace name");- test("records setup page entry when its marker cannot be saved", () => {- mocks.saveIntroStateByKey.mockImplementation(() => {- throw new Error("localStorage unavailable");- });- const page = renderIntoContainer(<WorkspaceSetupPage />);+ type(workspaceName, emptied);- expect(() => page.render()).not.toThrow();- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup page entered",- properties: { setup_version: "v1" },+ expect(workspaceName).toHaveValue(emptied);+ expect(continueButton()).toBeDisabled();+ expect(workspaceName).toHaveAccessibleDescription(+ "Enter a workspace name"+ );});- page.unmount();- });-- test("uses the shared step indicator for both setup steps", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();+ test("lets the name be emptied without the guess coming back", () => {+ render(<WorkspaceSetupPage />);- const initialIndicator = page.container.querySelector(- "[data-slot='step-indicator']"- );- expect(initialIndicator).not.toBeNull();- expect(- [...initialIndicator!.querySelectorAll("li span")].map(- (label) => label.textContent- )- ).toEqual(["Choose a goal", "Set up workspace"]);- expect(initialIndicator!.querySelector("svg")).toBeNull();-- const queryOption = [...page.container.querySelectorAll("label")].find(- (label) => label.textContent?.includes("Query data")- )!;- await act(async () => {- fireEvent.click(queryOption);- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });-- const workspaceIndicator = page.container.querySelector(- "[data-slot='step-indicator']"- );- expect(workspaceIndicator).not.toBeNull();- expect(workspaceIndicator!.querySelector("svg")).not.toBeNull();- page.unmount();- });+ type(screen.getByLabelText(/^Your name/), "");- test("uses stable wizard footer actions for workspace setup", () => {- const page = renderWorkspaceForm();- const buttons = [...page.container.querySelectorAll("button")];- const back = buttons.find((button) => button.textContent === "Back")!;- const skip = buttons.find(- (button) => button.textContent === "I'll do this later"- )!;- const submit = buttons.find(- (button) => button.textContent === "Setup my workspace"- )!;- const footer = back.parentElement!;-- expect(footer.className).toContain("justify-between");- expect(footer.className).toContain("gap-x-2");- expect(footer.firstElementChild).toBe(back);- expect(footer.lastElementChild).toContainElement(skip);- expect(footer.lastElementChild).toContainElement(submit);- expect(footer.lastElementChild?.textContent).toBe(- "I'll do this laterSetup my workspace"- );- expect(footer.querySelector(".w-full")).toBeNull();- page.unmount();- });+ expect(screen.getByLabelText(/^Your name/)).toHaveValue("");+ expect(continueButton()).toBeEnabled();+ });- test("starts with two unanswered questionnaire groups", () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);+ test("shows nothing until the account is known, and records no entry before the workspace is", () => {+ mocks.currentUser = { ...mocks.currentUser, email: "" } as User;+ const view = render(<WorkspaceSetupPage />);+ expect(view.container).toBeEmptyDOMElement();- page.render();+ mocks.currentUser = {+ ...mocks.currentUser,+ email: "[email protected]",+ } as User;+ mocks.workspace = { name: "", title: "" } as Workspace;+ view.rerender(<WorkspaceSetupPage />);- expect(page.container.textContent).toContain(- "What would you like to do with Bytebase?"- );- expect(page.container.querySelectorAll("[role='radio']")).toHaveLength(5);- expect(page.container.textContent).toContain("Create a database change");- expect(page.container.textContent).toContain("Mark sensitive data");- expect(page.container.textContent).toContain("Who will use Bytebase with you?");- expect(page.container.textContent).toContain("My team");- expect(page.container.textContent).toContain("Just me");- expect(page.container.textContent).not.toContain("Learn Bytebase Basics");- expect(page.container.textContent).not.toContain("Setup 1st project");- expect(page.container.textContent).not.toContain("Skip");-- page.unmount();+ expect(screen.getByLabelText(/^Your name/)).toHaveValue("Ed");+ expect(eventsNamed("workspace setup page entered")).toEqual([]);+ });});- test("requires both questionnaire answers in SaaS", async () => {- mocks.isSaaSMode = true;- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const continueButton = page.container.querySelector("button")!;+ describe("every screen", () => {+ const steps = () =>+ within(screen.getByRole("list"))+ .getAllByRole("listitem")+ .map((step) => step.textContent);- expect(continueButton).toBeDisabled();+ test("shows the same four steps, with the ones behind it checked off", () => {+ startAtProject();- const labels = [...page.container.querySelectorAll("label")];- await act(async () => {- fireEvent.click(- labels.find((label) => label.textContent?.includes("Query data"))!- );- await Promise.resolve();+ expect(steps()).toEqual(["Workspace", "Goal", "3Project", "4Team"]);});- expect(continueButton).toBeDisabled();- await act(async () => {- fireEvent.click(- labels.find((label) => label.textContent?.includes("Just me"))!- );- await Promise.resolve();- });- expect(continueButton).toBeEnabled();- page.unmount();- });+ test("moves the keyboard to the new screen's first answer", async () => {+ render(<WorkspaceSetupPage />);+ goToGoal();+ expect(choice(CHANGE_GOAL)).toHaveFocus();- test("removes the skip action from SaaS workspace setup", () => {- mocks.isSaaSMode = true;- const page = renderWorkspaceForm();+ fireEvent.click(screen.getByText(QUERY_GOAL));+ fireEvent.click(continueButton());+ expect(screen.getByLabelText(/^Project name/)).toHaveFocus();- expect(page.container.textContent).not.toContain("I'll do this later");- expect(page.container.textContent).toContain("Setup my workspace");- page.unmount();- });+ await nameProject();+ fireEvent.click(continueButton());+ expect(choice("Just me")).toHaveFocus();- test("persists Create a database change when the questionnaire continues", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const changeOption = [...page.container.querySelectorAll("label")].find(- (label) => label.textContent?.includes("Create a database change")- )!;-- await act(async () => {- fireEvent.click(changeOption);- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });- expect(page.container.textContent).toContain(- "Enable sample databases as a safe change target"- );- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "create-database-change"- );- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup page entered",- properties: { setup_version: "v1" },+ fireEvent.click(screen.getByText("11–50"));+ fireEvent.click(backButton());+ fireEvent.click(backButton());+ expect(choice(QUERY_GOAL)).toHaveFocus();});- page.unmount();- });- test("persists both answers without recording before setup ends", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const labels = [...page.container.querySelectorAll("label")];+ test("continues on Enter without the browser submitting the form", () => {+ render(<WorkspaceSetupPage />);+ const form = screen.getByLabelText(/^Your name/).closest("form");- await act(async () => {- fireEvent.click(- labels.find((label) => label.textContent?.includes("Query data"))!- );- fireEvent.click(- labels.find((label) => label.textContent?.includes("My team"))!- );- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });+ // False: the submit's default action was prevented.+ expect(fireEvent.submit(form as HTMLFormElement)).toBe(false);- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "query-data"- );- expect(mocks.saveGuideWorkspaceUsage).toHaveBeenCalledWith("team");- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup page entered",- properties: { setup_version: "v1" },- });-- const submit = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent?.includes("Setup my workspace")- )!;- await act(async () => {- fireEvent.click(submit);- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "query-data",- collaboration_type: "team",- result: "finished",- sample_enabled: true,- },+ expect(+ screen.getByRole("heading", { name: "What do you want to do first?" })+ ).toBeInTheDocument();});- page.unmount();- });- test("persists Query Data before optional workspace setup", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const queryOption = [...page.container.querySelectorAll("label")].find(- (label) => label.textContent?.includes("Query data")- )!;-- await act(async () => {- fireEvent.click(queryOption);- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "query-data"- );- expect(page.container.textContent).toContain(- "Enable sample databases to start querying immediately"- );+ test("keeps the browser from offering saved values in any of its fields", async () => {+ render(<WorkspaceSetupPage />);+ const offersNothing = () => {+ const fields = screen.getAllByRole("textbox");+ for (const field of fields) {+ expect(field).toHaveAttribute("autocomplete", "off");+ }+ return fields.length;+ };+ expect(offersNothing()).toBe(2);- const submit = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent?.includes("Setup my workspace")- )!;- await act(async () => {- fireEvent.click(submit);- await Promise.resolve();- await Promise.resolve();- });+ goToProject();+ await nameProject();+ editProjectId("pay");+ expect(offersNothing()).toBe(2);- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "query-data"- );- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "query-data",- collaboration_type: "unselected",- result: "finished",- sample_enabled: true,- },+ fireEvent.click(continueButton());+ fireEvent.click(screen.getByText("2–10"));+ expect(offersNothing()).toBe(1);});- page.unmount();- });-- test("preserves an explicit selection when optional setup fails", async () => {- mocks.updateUser.mockRejectedValueOnce(new Error("update failed"));- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const changeOption = [...page.container.querySelectorAll("label")].find(- (label) => label.textContent?.includes("Create a database change")- )!;- await act(async () => {- fireEvent.click(changeOption);- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });- const submit = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent?.includes("Setup my workspace")- )!;-- await act(async () => {- fireEvent.click(submit);- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "create-database-change"- );- expect(mocks.captureMetric).toHaveBeenCalled();- page.unmount();});- test("preserves the selected scenario when workspace setup is skipped", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const queryOption = [...page.container.querySelectorAll("label")].find(- (label) => label.textContent?.includes("Query data")- )!;-- await act(async () => {- fireEvent.click(queryOption);- await Promise.resolve();- });- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });- const skipSetupButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "I'll do this later"- )!;- await act(async () => {- fireEvent.click(skipSetupButton);- await Promise.resolve();- });-- expect(mocks.saveSelectedGuideScenarioId).toHaveBeenCalledWith(- "query-data"- );- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "query-data",- collaboration_type: "unselected",- result: "skipped",- sample_enabled: false,+ describe.each([+ {+ account: "an account that joined someone else's workspace",+ arrange: () => {+ mocks.workspacePolicy = {+ bindings: [+ {+ role: "roles/workspaceAdmin",+ members: ["user:[email protected]", "user:[email protected]"],+ },+ ],+ } as IamPolicy;},- });- expect(mocks.routerReplace).toHaveBeenCalled();- page.unmount();- });-- test("continuing without a scenario keeps scenario storage empty", async () => {- const page = renderIntoContainer(<WorkspaceSetupPage />);- page.render();- const continueButton = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent === "Continue"- )!;-- await act(async () => {- fireEvent.click(continueButton);- await Promise.resolve();- });- const submit = [...page.container.querySelectorAll("button")].find(- (button) => button.textContent?.includes("Setup my workspace")- )!;- await act(async () => {- fireEvent.click(submit);- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.clearSelectedGuideScenarioId).toHaveBeenCalledOnce();- expect(mocks.clearGuideWorkspaceUsage).toHaveBeenCalledOnce();- expect(mocks.saveSelectedGuideScenarioId).not.toHaveBeenCalled();- expect(mocks.saveGuideWorkspaceUsage).not.toHaveBeenCalled();- expect(mocks.captureMetric).toHaveBeenCalledTimes(3);- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "unselected",- collaboration_type: "unselected",- result: "finished",- sample_enabled: true,+ },+ {+ account: "an account that may not update the workspace",+ arrange: () => {+ mocks.canUpdateWorkspace = false;},- });- page.unmount();- });-- test("shows workspace name when the sole member can update the workspace", () => {- const page = renderWorkspaceForm();-- expect(page.container.textContent).not.toContain(- "Welcome! Set up your workspace"- );- expect(page.container.querySelector("[data-testid='user-avatar']")).toBeNull();- const heading = page.container.querySelector("h1");- expect(heading).toHaveTextContent("Set up workspace");- expect(heading).toHaveClass("sr-only");- expect(page.container.textContent).toContain(- "settings.profile.workspace-name"- );- const displayNameInput = page.container.querySelector(- "[data-testid='profile-display-name']"- );- const workspaceNameInput = page.container.querySelector(- "[data-testid='profile-workspace-title']"- );- expect(displayNameInput).toBeTruthy();- expect(workspaceNameInput).toBeTruthy();- expect(displayNameInput?.closest("[data-slot='form-field']")).toBeTruthy();- expect(- workspaceNameInput?.closest("[data-slot='form-field']")- ).toBeTruthy();- expect(mocks.hasWorkspacePermissionV2).not.toHaveBeenCalled();-- page.unmount();- });+ },+ ])("$account", ({ arrange }) => {+ test("is not asked to name it, and Finish leaves its name alone", async () => {+ arrange();+ render(<WorkspaceSetupPage />);- test("disables browser autocomplete for setup inputs", () => {- const page = renderWorkspaceForm();+ expect(screen.queryByLabelText("Workspace name")).not.toBeInTheDocument();+ expect(continueButton()).toBeEnabled();- for (const testId of [- "profile-display-name",- "profile-workspace-title",- "profile-project-title",- "project-resource-id",- ]) {- expect(- page.container.querySelector(`[data-testid='${testId}']`)- ).toHaveAttribute("autocomplete", "off");- }+ await goToTeam();+ finishAlone();- page.unmount();+ await landed();+ expect(writes()).toEqual(["updateUser", "createProject", "prepareSample"]);+ });});- test("hides workspace name for users joining an existing workspace", () => {- mocks.workspacePolicy = {- bindings: [- {- role: "roles/workspaceAdmin",- members: ["users/[email protected]"],- },- {- role: "roles/workspaceMember",- members: ["users/[email protected]"],- },- ],- } as IamPolicy;- const page = renderWorkspaceForm();+ describe("screen 2, goal", () => {+ const goalChoices = () =>+ screen.getByRole("radiogroup", { name: "What do you want to do first?" });- expect(page.container.textContent).not.toContain(- "settings.profile.workspace-name"- );+ test("blocks Continue until a goal is picked, with the reason under the choices", () => {+ render(<WorkspaceSetupPage />);+ goToGoal();- page.unmount();- });+ expect(within(goalChoices()).getAllByRole("radio")).toHaveLength(3);+ expect(continueButton()).toBeDisabled();+ expect(goalChoices()).toHaveAccessibleDescription("Pick one to continue");- test("can optionally create a project and continue to its Home", async () => {- const page = renderWorkspaceForm();+ fireEvent.click(screen.getByText(QUERY_GOAL));- expect(page.container.textContent).toContain("Setup 1st project");- expect(page.container.textContent).not.toContain(- "settings.profile.create-project-description"- );- expect(page.container.textContent).not.toContain(- "Optional. If you create a project here, we will take you to its database page next."- );- expect(- page.container.querySelector("[data-testid='create-project-toggle']")- ).toBeNull();-- const projectNameInput = page.container.querySelector(- "[data-testid='profile-project-title']"- ) as HTMLInputElement;- expect(projectNameInput.value).toBe("New project");- expect(- page.container.querySelector("[data-testid='project-resource-id']")- ).toBeTruthy();- expect(- projectNameInput.closest("[data-slot='form-field']")?.className- ).not.toContain("border-control-border");- expect(- [...page.container.querySelectorAll("[data-slot='form-field']")].some(- (field) => field.className.includes("border-control-border")- )- ).toBe(false);-- const sampleCheckbox = page.container.querySelector(- "[data-testid='enable-sample-databases']"- ) as HTMLButtonElement;- expect(sampleCheckbox).toBeChecked();- expect(sampleCheckbox).toBeEnabled();- expect(page.container.textContent).toContain("Enable sample databases");-- const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- await act(async () => {- save.click();- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.createProject).toHaveBeenCalledWith(- "New project",- "new-project"- );- expect(mocks.setRecentProject).toHaveBeenCalledWith("projects/new-project");- expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(- "projects/new-project"- );- expect(mocks.createProject.mock.invocationCallOrder[0]).toBeLessThan(- mocks.prepareSampleProjectInstance.mock.invocationCallOrder[0]- );- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "sample instance requested",- properties: { source: "workspace_setup" },- });- const sampleMetricCall = mocks.captureMetric.mock.calls.find(- ([metric]) => metric.event === "sample instance requested"- );- expect(sampleMetricCall).toBeDefined();- expect(sampleMetricCall![0]).toEqual({- event: "sample instance requested",- properties: { source: "workspace_setup" },+ expect(continueButton()).toBeEnabled();+ expect(goalChoices()).not.toHaveAccessibleDescription();});- expect(mocks.captureMetric.mock.invocationCallOrder[0]).toBeLessThan(- mocks.prepareSampleProjectInstance.mock.invocationCallOrder[0]- );- expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project.detail",- params: { projectId: "new-project" },- });-- page.unmount();});- test("allows setup without creating a project when its title is cleared", async () => {- const page = renderWorkspaceForm();-- const projectNameInput = page.container.querySelector(- "[data-testid='profile-project-title']"- ) as HTMLInputElement;- expect(projectNameInput).not.toBeRequired();- expect(- page.container.querySelector("[data-testid='project-required-indicator']")- ).toBeNull();- await act(async () => {- fireEvent.change(projectNameInput, { target: { value: "" } });- await Promise.resolve();- await Promise.resolve();- });-- expect(- page.container.querySelector("[data-testid='project-resource-id']")- ).toBeNull();- const sampleCheckbox = page.container.querySelector(- "[data-testid='enable-sample-databases']"- ) as HTMLButtonElement;- expect(sampleCheckbox).not.toBeChecked();- expect(sampleCheckbox).toHaveAttribute("aria-disabled", "true");-- const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- await act(async () => {- save.click();- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.createProject).not.toHaveBeenCalled();- expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();- expect(mocks.captureMetric).not.toHaveBeenCalledWith({- event: "sample instance requested",- properties: expect.anything(),- });- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "unselected",- collaboration_type: "unselected",- result: "finished",- sample_enabled: false,- },- });- expect(mocks.setRecentProject).not.toHaveBeenCalled();- expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project",- query: { intro: "create-project" },- });+ describe("screen 3, project", () => {+ test("asks for a project name before Continue, with the sample database preselected", async () => {+ startAtProject();+ const projectName = screen.getByLabelText(/^Project name/);- page.unmount();- });+ expect(projectName).toHaveValue("");+ expect(continueButton()).toBeDisabled();+ expect(projectName).toHaveAccessibleDescription(+ expect.stringContaining("Enter a project name")+ );+ expect(choice(SAMPLE)).toBeChecked();+ expect(choice(OWN_INSTANCE)).not.toBeChecked();- test("requires the first project in SaaS", async () => {- mocks.isSaaSMode = true;- const page = renderWorkspaceForm();+ await nameProject();- const projectNameInput = page.container.querySelector(- "[data-testid='profile-project-title']"- ) as HTMLInputElement;- expect(projectNameInput).toBeRequired();- expect(- page.container.querySelector("[data-testid='project-required-indicator']")- ).toHaveClass("ml-1");- await act(async () => {- fireEvent.change(projectNameInput, { target: { value: "" } });- await Promise.resolve();+ expect(screen.getByText("payments-ab12")).toBeInTheDocument();+ expect(projectName).not.toHaveAccessibleDescription(+ expect.stringContaining("Enter a project name")+ );+ expect(+ screen.getByRole("radiogroup", { name: "Database for Payments" })+ ).toBeInTheDocument();});- const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- expect(save).toBeDisabled();+ test("lets self-hosted leave the project for later, offering no database and making no project", async () => {+ mocks.isSaaSMode = false;+ startAtProject(CHANGE_GOAL);+ const projectName = screen.getByLabelText(/^Project name/);- page.unmount();- });+ expect(projectName).toHaveAccessibleName(+ expect.stringContaining("optional")+ );+ expect(projectName).toHaveAccessibleDescription(+ expect.stringContaining("Leave it empty to create a project later.")+ );+ expect(screen.queryByText(SAMPLE)).not.toBeInTheDocument();+ expect(screen.queryByText(OWN_INSTANCE)).not.toBeInTheDocument();- test("requires a project ID while the project title is present", async () => {- const page = renderWorkspaceForm();+ fireEvent.click(continueButton());+ fireEvent.click(screen.getByText("2–10"));+ fireEvent.click(finishButton());- const projectResourceIdInput = page.container.querySelector(- "[data-testid='project-resource-id']"- ) as HTMLInputElement;- await act(async () => {- fireEvent.change(projectResourceIdInput, { target: { value: "" } });- await Promise.resolve();+ await landed();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DASHBOARD,+ query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ });+ expect(writes()).toEqual(["updateUser", "updateWorkspace"]);+ expect(readSelectedGuideScenarioId()).toBe("create-database-change");+ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({+ result: "finished",+ source: "none",+ sample_enabled: false,+ }),+ ]);});- const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- expect(save).toBeDisabled();+ test("offers the database again once a self-hosted project is named", async () => {+ mocks.isSaaSMode = false;+ startAtProject();- page.unmount();- });+ await nameProject();- test("does not prepare sample databases when the user opts out", async () => {- const page = renderWorkspaceForm();-- const sampleCheckbox = page.container.querySelector(- "[data-testid='enable-sample-databases']"- ) as HTMLButtonElement;- await act(async () => {- sampleCheckbox.click();- });- expect(sampleCheckbox).not.toBeChecked();-- const submit = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- await act(async () => {- submit.click();- await Promise.resolve();- await Promise.resolve();- });-- expect(mocks.createProject).toHaveBeenCalled();- expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();- expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project.detail",- params: { projectId: "new-project" },- });- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "unselected",- collaboration_type: "unselected",- result: "finished",- sample_enabled: false,- },+ expect(choice(SAMPLE)).toBeChecked();+ expect(choice(OWN_INSTANCE)).not.toBeChecked();});- page.unmount();- });+ test("needs the project name on self-hosted once a create has been sent", () => {+ mocks.isSaaSMode = false;+ storeDraft({+ screen: "project",+ goal: "query-data",+ projectTitle: "",+ projectId: "",+ attemptedProjectId: "payments-ab12",+ });+ render(<WorkspaceSetupPage />);- test("finishes setup when sample database preparation fails", async () => {- mocks.prepareSampleProjectInstance.mockRejectedValue(- new Error("sample target unavailable")- );- const page = renderWorkspaceForm();-- const submit = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- await act(async () => {- submit.click();- await Promise.resolve();- await Promise.resolve();- });-- const errorNotifications = mocks.pushNotification.mock.calls- .map(([notification]) => notification)- .filter((notification) => notification.style === "CRITICAL");- expect(errorNotifications).toEqual([- expect.objectContaining({- title: "Failed to prepare Sample Project Instance.",- }),- ]);- expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project.detail",- params: { projectId: "new-project" },- });- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "unselected",- collaboration_type: "unselected",- result: "finished",- sample_enabled: true,- },+ expect(screen.getByLabelText(/^Project name/)).toHaveAccessibleDescription(+ expect.stringContaining("Enter a project name")+ );+ expect(continueButton()).toBeDisabled();});- page.unmount();- });+ test("blocks Continue on an emptied project ID, with the field's reason", async () => {+ startAtProject();+ await nameProject();- test("hides sample database setup when the target is unavailable", () => {- mocks.sampleAvailable = false;- const page = renderWorkspaceForm();+ editProjectId("");- expect(- page.container.querySelector(- "[data-testid='enable-sample-databases']"- )- ).toBeNull();+ expect(+ await screen.findByText("The Project ID cannot be empty")+ ).toBeInTheDocument();+ expect(continueButton()).toBeDisabled();+ });- page.unmount();- });+ test("blocks Continue on a project ID another project holds, with the field's reason", async () => {+ server.projects.set("projects/billing", {+ name: "projects/billing",+ title: "Someone else's project",+ });+ startAtProject();+ await nameProject();- test("hides sample database setup when the workspace already provisioned a sample", () => {- mocks.sampleInstances = [{ instance: "instances/sample" }];- const page = renderWorkspaceForm();+ editProjectId("billing");- expect(- page.container.querySelector(- "[data-testid='enable-sample-databases']"- )- ).toBeNull();+ expect(await screen.findByText(ID_EXISTS)).toBeInTheDocument();+ expect(continueButton()).toBeDisabled();+ });- page.unmount();- });+ test("does not hold Continue back while the ID check is still out", async () => {+ mocks.fetchProject.mockReturnValue(new Promise(() => {}));+ startAtProject();- test("skips workspace setup to the projects page with create project highlighted", async () => {- const page = renderWorkspaceForm();+ type(screen.getByLabelText(/^Project name/), "Payments");- const skip = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent === "I'll do this later"- ) as HTMLButtonElement;- await act(async () => {- skip.click();- await Promise.resolve();+ await waitFor(() => expect(continueButton()).toBeEnabled());+ expect(mocks.fetchProject).toHaveBeenCalledWith(+ "projects/payments-ab12",+ true+ );});- expect(mocks.createProject).not.toHaveBeenCalled();- expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project",- query: { intro: "create-project" },+ test("derives a new ID for a name entered after the first was cleared", async () => {+ startAtProject();+ await nameProject("Payments");++ type(screen.getByLabelText(/^Project name/), "");+ expect(continueButton()).toBeDisabled();+ expect(screen.getByText("Enter a project name")).toBeInTheDocument();++ await nameProject("Orders");++ expect(screen.getByText("orders-ab12")).toBeInTheDocument();+ expect(screen.queryByText("payments-ab12")).not.toBeInTheDocument();});- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: "unselected",- collaboration_type: "unselected",- result: "skipped",- sample_enabled: false,++ test.each([+ {+ when: "the server offers no sample",+ available: false,+ instances: [],+ reason: "The sample database is not available on this server.",+ },+ {+ when: "the workspace already used its sample",+ available: true,+ instances: [{ instance: "projects/earlier/instances/sample" }],+ reason: "This workspace has already used its sample database.",},+ ])("offers only the own-instance choice, with the reason, when $when", async (sample) => {+ mocks.sample = sample;+ startAtProject();++ expect(screen.queryByText(SAMPLE)).not.toBeInTheDocument();+ expect(choice(OWN_INSTANCE)).toBeChecked();+ expect(screen.getByText(sample.reason)).toBeInTheDocument();++ await nameProject();+ fireEvent.click(continueButton());+ finishAlone();++ await landed();+ expect(writes()).toEqual(["updateUser", "updateWorkspace", "createProject"]);+ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({ source: "own", sample_enabled: false }),+ ]);});- page.unmount();- });-- test.each([- { isSaaSMode: false, deployment: "self-host" },- { isSaaSMode: true, deployment: "cloud" },- ])(- "records a completed setup for the $deployment deployment",- async ({ isSaaSMode }) => {+ test.each([+ {+ deployment: "Bytebase Cloud, for seven days",+ isSaaSMode: true,+ says: /hosted by Bytebase Cloud.*available for 7 days/,+ omits: /on this server/,+ },+ {+ deployment: "this server, with no expiry",+ isSaaSMode: false,+ says: /running on this server/,+ omits: /7 days/,+ },+ ])("says the sample runs on $deployment", async ({+ isSaaSMode,+ says,+ omits,+ }) => {mocks.isSaaSMode = isSaaSMode;- const page = renderWorkspaceForm();-- const submit = Array.from(- page.container.querySelectorAll("button")- ).find((button) =>- button.textContent?.includes("Setup my workspace")- ) as HTMLButtonElement;- await act(async () => {- submit.click();- await Promise.resolve();- await Promise.resolve();- });+ startAtProject();+ await nameProject();- expect(mocks.captureMetric).toHaveBeenCalledWith({- event: "workspace setup submitted",- properties: {- scenario: isSaaSMode ? "query-data" : "unselected",- collaboration_type: isSaaSMode ? "solo" : "unselected",- result: "finished",- sample_enabled: true,+ expect(screen.getByText(says)).toBeInTheDocument();+ expect(screen.queryByText(omits)).not.toBeInTheDocument();+ });+ });++ describe("screen 3, after a Finish attempt created the project", () => {+ // One invitee, so every step of the commit has work to do.+ const failFinish = async () => {+ await startAtTeam();+ finishInviting("[email protected]");+ await failed();+ };++ test("shows the project and its prepared sample read-only", async () => {+ mocks.updateProjectIamPolicy.mockRejectedValueOnce(unavailable());+ await failFinish();+ // Whatever the server offers now, the prepared sample is the project's.+ mocks.sample = { available: false, instances: [] };+ fireEvent.click(backButton());++ expect(screen.getByLabelText(/^Project name/)).toBeDisabled();+ expect(screen.getByLabelText(/^Project name/)).toHaveValue("Payments");+ expect(screen.getByText("payments-ab12")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Edit" })+ ).not.toBeInTheDocument();+ expect(+ screen.getByText(+ "This project already exists. Rename it in its settings."+ )+ ).toBeInTheDocument();+ expect(choice(SAMPLE)).toBeChecked();+ expect(choice(SAMPLE)).toHaveAttribute("aria-disabled", "true");+ expect(+ screen.getByText("The sample database is ready in this project.")+ ).toBeInTheDocument();+ expect(continueButton()).toBeEnabled();+ });++ test("still lets the database choice change while the sample is not prepared", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await failFinish();+ fireEvent.click(backButton());++ expect(screen.getByLabelText(/^Project name/)).toBeDisabled();+ fireEvent.click(screen.getByText(OWN_INSTANCE));++ expect(choice(OWN_INSTANCE)).toBeChecked();+ expect(continueButton()).toBeEnabled();+ });+ });++ describe("I'll do this later", () => {+ const skipButton = () =>+ screen.getByRole("button", { name: "I'll do this later" });+ const skipOffered = () =>+ screen.queryByRole("button", { name: "I'll do this later" }) !== null;++ test("is not offered on Cloud, where setup is mandatory", () => {+ startAtProject();++ expect(skipOffered()).toBe(false);+ });++ test("saves the two names on self-hosted and leaves without creating a project", async () => {+ mocks.isSaaSMode = false;+ const view = startAtProject(CHANGE_GOAL);++ fireEvent.click(skipButton());++ await landed();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DASHBOARD,+ query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ });+ expect(writes()).toEqual(["updateUser", "updateWorkspace"]);+ expect(readSelectedGuideScenarioId()).toBe("create-database-change");+ expect(eventsNamed("workspace setup submitted")).toEqual([+ {+ setup_version: "v2",+ result: "skipped",+ scenario: "create-database-change",+ sample_enabled: false,},+ ]);++ view.unmount();+ render(<WorkspaceSetupPage />);+ expect(+ screen.getByRole("heading", { name: "Set up your workspace" })+ ).toBeInTheDocument();+ });++ test("stays on the screen with the error when the names cannot be saved, and can be pressed again", async () => {+ mocks.isSaaSMode = false;+ mocks.updateUser.mockRejectedValueOnce(unavailable("database is down"));+ startAtProject();++ fireEvent.click(skipButton());++ const alert = await failed();+ expect(alert).toHaveTextContent(+ "Could not save your name and the workspace name."+ );+ expect(alert).toHaveTextContent("database is down");+ expect(screen.getByLabelText(/^Project name/)).toBeInTheDocument();+ expect(mocks.routerReplace).not.toHaveBeenCalled();++ fireEvent.click(skipButton());++ await landed();+ });++ test("drops its failure's report once the screen is left", async () => {+ mocks.isSaaSMode = false;+ mocks.updateUser.mockRejectedValueOnce(unavailable());+ startAtProject();+ fireEvent.click(skipButton());+ await failed();++ fireEvent.click(backButton());+ fireEvent.click(continueButton());++ expect(screen.getByLabelText(/^Project name/)).toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("is withheld while a create got no answer and the server cannot be read", async () => {+ mocks.isSaaSMode = false;+ mocks.createProject.mockRejectedValueOnce(unavailable());+ mocks.getProject.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishAlone();+ await failed();++ fireEvent.click(backButton());++ await waitFor(() => expect(mocks.getProject).toHaveBeenCalledTimes(1));+ expect(skipOffered()).toBe(false);+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ });++ test("is withdrawn once a Finish attempt has created the project", async () => {+ mocks.isSaaSMode = false;+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishAlone();+ await failed();++ fireEvent.click(backButton());++ expect(screen.getByLabelText(/^Project name/)).toBeDisabled();+ expect(skipOffered()).toBe(false);+ });+ });++ describe("screen 4, team", () => {+ const teamSizes = () =>+ screen.getByRole("radiogroup", {+ name: "How many people will use Bytebase?",+ });++ test("asks only for a team size, and blocks Finish until one is picked", async () => {+ await startAtTeam();++ expect(+ within(teamSizes())+ .getAllByRole("radio")+ .map((radio) => radio.closest("label")?.textContent)+ ).toEqual(["Just me", "2–10", "11–50", "51–200", "200+"]);+ expect(finishButton()).toBeDisabled();+ expect(teamSizes()).toHaveAccessibleDescription(+ "Pick a team size to finish"+ );+ expect(backButton()).toBeEnabled();+ expect(screen.queryByText("Invite teammates")).not.toBeInTheDocument();++ fireEvent.click(screen.getByText("Just me"));++ expect(finishButton()).toBeEnabled();+ expect(teamSizes()).not.toHaveAccessibleDescription();+ expect(screen.queryByText("Invite teammates")).not.toBeInTheDocument();+ });++ test("invites teammates on Cloud, and the button counts them", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ expect(invitees()).toHaveAccessibleDescription(+ /^Press Enter after each address\./+ );++ expect(+ screen.getByText(+ /They join as members who can query and propose changes in Payments\./+ )+ ).toBeInTheDocument();+ expect(finishButton()).toBeEnabled();++ enterAddress("[email protected]");+ expect(+ screen.getByRole("button", { name: "Send 1 invite and finish" })+ ).toBeEnabled();++ enterAddress("[email protected]");+ expect(+ screen.getByRole("button", { name: "Send 2 invites and finish" })+ ).toBeEnabled();+ });++ test.each([+ {+ where: "in place of the text selected in the field",+ typed: "[email protected]",+ selection: [0, 12],+ entries: ["[email protected]", "[email protected]"],+ },+ {+ where: "before the text typed after the cursor, which stays an entry",+ typed: "[email protected]",+ selection: [0, 0],+ },+ ])("puts a pasted list $where", async ({ typed, selection, entries }) => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ type(invitees(), typed);+ (invitees() as HTMLInputElement).setSelectionRange(+ selection[0],+ selection[1]+ );++ fireEvent.paste(invitees(), {+ clipboardData: { getData: () => "[email protected], [email protected]" },});- if (isSaaSMode) {- expect(mocks.saveWorkspaceSetupFinished).toHaveBeenCalledWith(- "workspaces/ws1",- true++ expect(+ screen+ .getAllByRole("button", { name: /^Remove / })+ .map((remove) => remove.getAttribute("aria-label"))+ ).toEqual(entries.map((entry) => `Remove ${entry}`));+ });++ test("takes the addresses out of a pasted list, and shows but does not count repeats, bad entries and the owner", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("11–50"));+ type(invitees(), "[email protected]");++ // False: the paste's default action, inserting the text, was prevented.+ expect(+ fireEvent.paste(invitees(), {+ clipboardData: {+ getData: () =>+ 'Ann Lee <[email protected]>, "[email protected]";[email protected]\nmailto:[email protected]. ([email protected]) a@[email protected] gil@localhost [email protected]',+ },+ })+ ).toBe(false);++ expect(invitees()).toHaveValue("");+ expect(+ screen+ .getAllByRole("button", { name: /^Remove / })+ .map((remove) => remove.getAttribute("aria-label"))+ ).toEqual([+ "Remove [email protected]",+ "Remove [email protected]",+ "Remove [email protected]",+ "Remove [email protected]",+ "Remove [email protected]",+ "Remove a@[email protected]",+ "Remove gil@localhost",+ "Remove [email protected]",+ ]);+ for (const bad of ["a@[email protected]", "gil@localhost"]) {+ expect(screen.getByText(bad).parentElement).toHaveTextContent(+ "Not an email address"+ );+ }+ expect(+ screen.getByText("[email protected]").parentElement+ ).toHaveTextContent("Your own address");+ expect(+ screen.getByRole("button", { name: "Send 5 invites and finish" })+ ).toBeEnabled();++ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );++ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Send 4 invites and finish" })+ ).toBeEnabled();+ });++ test.each([+ { typed: "ann@example", entered: "not an address", finishes: false },+ { typed: "[email protected]", entered: "an address", finishes: true },+ ])("enters text left in the field when the button is pressed, and stops there when it is $entered", async ({+ typed,+ finishes,+ }) => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ type(invitees(), typed);+ const button = screen.getByRole("button", { name: /finish$/i });++ // A press moves the focus out of the field before its click.+ fireEvent.pointerDown(button);+ fireEvent.blur(invitees());+ fireEvent.click(button);++ expect(screen.getByText(typed)).toBeInTheDocument();+ if (finishes) {+ await landed();+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledWith(+ [{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],+ REPORT);- } else {- expect(mocks.saveWorkspaceSetupFinished).not.toHaveBeenCalled();+ return;}+ expect(screen.getByText(typed).parentElement).toHaveTextContent(+ "Not an email address"+ );+ expect(writes()).toEqual([]);++ fireEvent.click(finishButton());++ await landed();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ });++ test("stops a press on Finish without the sample that enters text that is not an address", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ fireEvent.click(finishButton());+ await failed();+ type(invitees(), "ann@example");+ const button = screen.getByRole("button", {+ name: "Finish without the sample",+ });+ const writesBefore = writes();++ fireEvent.pointerDown(button);+ fireEvent.blur(invitees());+ fireEvent.click(button);++ expect(screen.getByText("ann@example").parentElement).toHaveTextContent(+ "Not an email address"+ );+ // No attempt started: it would have saved the names first.+ expect(writes()).toEqual(writesBefore);++ fireEvent.click(button);++ await landed();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ });++ test("does not stop a press that enters the account's own address", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ type(invitees(), "[email protected]");+ const button = finishButton();++ fireEvent.pointerDown(button);+ fireEvent.blur(invitees());+ fireEvent.click(button);++ await landed();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ });++ test.each([+ { separator: ",", how: "a full-width comma" },+ { separator: ";", how: "a full-width semicolon" },+ { separator: "、", how: "an ideographic comma" },+ ])("splits addresses at $how, as an input method types it", async ({+ separator,+ }) => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));++ type(invitees(), `[email protected]${separator}`);+ fireEvent.paste(invitees(), {+ clipboardData: {+ getData: () => `[email protected]${separator}[email protected]`,+ },+ });++ expect(+ screen.getByRole("button", { name: "Send 3 invites and finish" })+ ).toBeEnabled();+ });++ test("leaves the Enter that confirms an input method's text to the input method", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ type(invitees(), "tanaka");++ fireEvent.keyDown(invitees(), { key: "Enter", isComposing: true });++ expect(invitees()).toHaveValue("tanaka");+ expect(+ screen.queryByRole("button", { name: /^Remove / })+ ).not.toBeInTheDocument();+ });++ test("leaves the Backspace that edits an input method's text to the input method", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ enterAddress("[email protected]");++ fireEvent.keyDown(invitees(), { key: "Backspace", isComposing: true });++ expect(+ screen.getByRole("button", { name: "Remove [email protected]" })+ ).toBeInTheDocument();+ });++ test("leaves a single pasted address to the browser, as typed text", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));++ expect(+ fireEvent.paste(invitees(), {+ clipboardData: { getData: () => "[email protected]" },+ })+ ).toBe(true);+ });++ test("adds an address on a separator, on Enter and on leaving the field, and removes the last on Backspace", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ const chips = () =>+ screen+ .getAllByRole("button", { name: /^Remove / })+ .map((remove) => remove.getAttribute("aria-label"));++ type(invitees(), "[email protected],");+ type(invitees(), "[email protected]");+ // False: Enter adds the address; it must not submit the wizard.+ expect(fireEvent.keyDown(invitees(), { key: "Enter" })).toBe(false);+ type(invitees(), "[email protected]");+ fireEvent.blur(invitees());++ expect(chips()).toEqual([+ "Remove [email protected]",+ "Remove [email protected]",+ "Remove [email protected]",+ ]);+ expect(writes()).toEqual([]);++ fireEvent.keyDown(invitees(), { key: "Backspace" });++ expect(chips()).toEqual([+ "Remove [email protected]",+ "Remove [email protected]",+ ]);+ });++ test("leaves the invitees out, on screen and at Finish, when the answer goes back to Just me", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));+ enterAddress("[email protected]");++ fireEvent.click(screen.getByText("Just me"));++ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ fireEvent.click(finishButton());+ await landed();+ expect(writes()).toEqual([+ "updateUser",+ "updateWorkspace",+ "createProject",+ "prepareSample",+ ]);+ });++ test("asks only the team size on self-hosted, where a member added would have no password", async () => {+ mocks.isSaaSMode = false;+ await startAtTeam();+ fireEvent.click(screen.getByText("2–10"));++ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ fireEvent.click(finishButton());+ await landed();+ expect(mocks.updateProjectIamPolicy).not.toHaveBeenCalled();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ });++ test("adds no one on self-hosted from addresses a draft holds", async () => {+ mocks.isSaaSMode = false;+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]"],+ });+ render(<WorkspaceSetupPage />);++ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ fireEvent.click(finishButton());+ await landed();+ expect(mocks.updateProjectIamPolicy).not.toHaveBeenCalled();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({ result: "finished", invite_count: 0 }),+ ]);+ });++ test.each([+ { database: SAMPLE, arriveFirst: false },+ { database: OWN_INSTANCE, arriveFirst: true },+ ])("tells the account whether its invitees arrive before the databases, with $database", async ({+ database,+ arriveFirst,+ }) => {+ await startAtTeam({ database });+ fireEvent.click(screen.getByText("2–10"));++ expect(+ screen.queryAllByText(+ /Its databases appear once your instance is connected\./+ )+ ).toHaveLength(arriveFirst ? 1 : 0);+ });+ });++ describe("Back", () => {+ const answerEverything = async () => {+ type(screen.getByLabelText(/^Your name/), "Edward");+ type(screen.getByLabelText("Workspace name"), "Acme");+ goToProject(CHANGE_GOAL);+ await nameProject();+ editProjectId("pay");+ await waitFor(() => expect(continueButton()).toBeEnabled());+ fireEvent.click(screen.getByText(OWN_INSTANCE));+ fireEvent.click(continueButton());+ fireEvent.click(screen.getByText("2–10"));+ enterAddress("[email protected]");+ };+ const expectEveryAnswer = async () => {+ expect(choice("2–10")).toBeChecked();+ expect(screen.getByText("[email protected]")).toBeInTheDocument();++ fireEvent.click(backButton());+ expect(screen.getByLabelText(/^Project name/)).toHaveValue("Payments");+ expect(screen.getByText("pay")).toBeInTheDocument();+ expect(choice(OWN_INSTANCE)).toBeChecked();+ await waitFor(() => expect(continueButton()).toBeEnabled());++ fireEvent.click(backButton());+ expect(choice(CHANGE_GOAL)).toBeChecked();++ fireEvent.click(backButton());+ expect(screen.getByLabelText(/^Your name/)).toHaveValue("Edward");+ expect(screen.getByLabelText("Workspace name")).toHaveValue("Acme");+ };++ test("returns through every screen with each answer kept, a hand-set project ID included", async () => {+ render(<WorkspaceSetupPage />);+ await answerEverything();++ await expectEveryAnswer();++ fireEvent.click(continueButton());+ fireEvent.click(continueButton());+ fireEvent.click(continueButton());+ expect(choice("2–10")).toBeChecked();+ expect(screen.getByText("[email protected]")).toBeInTheDocument();+ });++ test("finds every answer on the same screen after a reload", async () => {+ const first = render(<WorkspaceSetupPage />);+ await answerEverything();+ first.unmount();++ render(<WorkspaceSetupPage />);++ await expectEveryAnswer();+ });+ });- page.unmount();+ describe("left panel", () => {+ // The layout's left column, which it hands to the wizard on this route.+ function WithLeftColumn() {+ const [column, setColumn] = useState<HTMLElement | null>(null);+ return (+ <>+ <aside ref={setColumn} data-testid="left-column" />+ <SplashPanelContext.Provider value={column}>+ <WorkspaceSetupPage />+ </SplashPanelContext.Provider>+ </>+ );}- );+ const panel = () => within(screen.getByTestId("left-column"));+ const still = () => panel().getByRole("presentation").dataset.still;++ test("previews the workspace as it is named, then shows each goal's own picture", async () => {+ render(<WithLeftColumn />);+ expect(panel().getAllByText("Workspace One")).not.toHaveLength(0);+ expect(panel().getByText("Ed")).toBeInTheDocument();+ expect(panel().getByText("Workspace Admin")).toBeInTheDocument();+ expect(panel().getAllByText("Workspace Member")).toHaveLength(2);+ type(screen.getByLabelText(/^Your name/), "Ada Park");+ type(screen.getByLabelText("Workspace name"), "Acme");+ expect(panel().getAllByText("Acme")).not.toHaveLength(0);+ expect(panel().getByText("Ada Park")).toBeInTheDocument();++ goToGoal();+ expect(panel().getAllByText("Acme")).not.toHaveLength(0);+ fireEvent.click(screen.getByText(CHANGE_GOAL));+ expect(still()).toBe("hero");+ // Its size is known before the file loads, so the panel does not start+ // out collapsed.+ expect(panel().getByRole("presentation")).toHaveAttribute(+ "width",+ "1638"+ );+ expect(panel().getByRole("presentation")).toHaveAttribute(+ "height",+ "1111"+ );+ fireEvent.click(screen.getByText(QUERY_GOAL));+ expect(still()).toBe("query");+ fireEvent.click(screen.getByText(EXPLORING));+ expect(still()).toBe("explore");+ });++ test("draws the workspace, the project and its instance as they are answered", async () => {+ render(<WithLeftColumn />);+ goToProject();++ expect(panel().getByText("Workspace One")).toBeInTheDocument();+ expect(panel().getByText("your project")).toBeInTheDocument();+ expect(panel().getByText("Sample Project Instance")).toBeInTheDocument();+ expect(panel().getByText("Sample database")).toBeInTheDocument();++ await nameProject();+ expect(panel().getByText("Payments")).toBeInTheDocument();++ fireEvent.click(screen.getByText(OWN_INSTANCE));+ expect(panel().getByText("Your instance")).toBeInTheDocument();+ expect(panel().getByText("Connected after setup")).toBeInTheDocument();+ expect(panel().getByText("Its databases")).toBeInTheDocument();+ expect(+ panel().queryByText("Sample Project Instance")+ ).not.toBeInTheDocument();+ });++ test("draws no instances for a project self-hosted leaves for later", async () => {+ mocks.isSaaSMode = false;+ render(<WithLeftColumn />);+ goToProject();++ expect(panel().getByText("your project")).toBeInTheDocument();+ expect(+ panel().queryByText("Sample Project Instance")+ ).not.toBeInTheDocument();++ await nameProject();+ expect(panel().getByText("Sample Project Instance")).toBeInTheDocument();+ });++ test("lists the team in the workspace as it is answered, five rows at most", async () => {+ render(<WithLeftColumn />);+ await goToTeam();++ expect(panel().getAllByText("Workspace One")).not.toHaveLength(0);+ expect(panel().getByText("Ed")).toBeInTheDocument();+ expect(panel().getByText("Workspace Admin")).toBeInTheDocument();+ expect(panel().queryByText("Workspace Member")).not.toBeInTheDocument();++ fireEvent.click(screen.getByText("2–10"));+ enterAddress("[email protected]");+ enterAddress("not-an-address");+ expect(panel().getByText("[email protected]")).toBeInTheDocument();+ expect(panel().getAllByText("Workspace Member")).toHaveLength(4);+ expect(panel().queryByText("not-an-address")).not.toBeInTheDocument();++ for (const name of ["bob", "cy", "dee", "eve", "fay"]) {+ enterAddress(`${name}@example.com`);+ }+ expect(panel().getByText("[email protected]")).toBeInTheDocument();+ expect(panel().queryByText("[email protected]")).not.toBeInTheDocument();+ expect(panel().getByText("+2 more")).toBeInTheDocument();++ fireEvent.click(screen.getByText("Just me"));+ expect(panel().queryByText("[email protected]")).not.toBeInTheDocument();+ expect(panel().getByText("Ed")).toBeInTheDocument();+ });++ test("draws a wider column's picture larger, as one", () => {+ const width = vi+ .spyOn(HTMLElement.prototype, "clientWidth", "get")+ .mockReturnValue(1024);+ render(<WithLeftColumn />);++ const picture = screen.getByTestId("left-column").firstElementChild;+ expect(picture?.firstElementChild).toHaveStyle({+ transform: "scale(2)",+ });+ width.mockRestore();+ });+ });++ describe("events", () => {+ test("records entering setup once per account", () => {+ const first = render(<WorkspaceSetupPage />);+ first.rerender(<WorkspaceSetupPage />);+ first.unmount();+ render(<WorkspaceSetupPage />);++ expect(eventsNamed("workspace setup page entered")).toEqual([+ { setup_version: "v2" },+ ]);+ });++ test("records entering setup even when its marker cannot be saved", () => {+ mocks.saveIntroStateByKey.mockImplementation(() => {+ throw new Error("localStorage unavailable");+ });++ expect(() => render(<WorkspaceSetupPage />)).not.toThrow();+ expect(eventsNamed("workspace setup page entered")).toHaveLength(1);+ });++ test("records each Continue with the answers so far and no names", async () => {+ await startAtTeam({ goal: CHANGE_GOAL, database: OWN_INSTANCE });++ expect(eventsNamed("workspace setup screen continued")).toEqual([+ {+ setup_version: "v2",+ screen: 1,+ goal: "unselected",+ project_named: false,+ },+ {+ setup_version: "v2",+ screen: 2,+ goal: "create-database-change",+ project_named: false,+ },+ {+ setup_version: "v2",+ screen: 3,+ goal: "create-database-change",+ project_named: true,+ source: "own",+ },+ ]);+ expect(JSON.stringify(mocks.captureMetric.mock.calls)).not.toMatch(+ /Payments|ed@example\.com|Workspace One/+ );+ });++ test("records the sample request, then a finished setup with its goal, source, team size and invite count", async () => {+ await startAtTeam({ goal: QUERY_GOAL });+ fireEvent.click(screen.getByText("11–50"));+ enterAddress("[email protected]");+ enterAddress("[email protected]");+ enterAddress("not-an-address");+ fireEvent.click(+ screen.getByRole("button", { name: "Send 2 invites and finish" })+ );+ await landed();++ expect(+ mocks.captureMetric.mock.calls+ .map(([metric]) => metric as { event: string; properties: unknown })+ .filter(({ event }) => event !== "workspace setup screen continued")+ .slice(1)+ ).toEqual([+ {+ event: "sample instance requested",+ properties: { source: "workspace_setup" },+ },+ {+ event: "workspace setup submitted",+ properties: {+ setup_version: "v2",+ result: "finished",+ scenario: "query-data",+ source: "sample",+ team_size: "11-50",+ invite_count: 2,+ sample_enabled: true,+ collaboration_type: "team",+ },+ },+ ]);+ expect(JSON.stringify(mocks.captureMetric.mock.calls)).not.toMatch(+ /ann@example\.com/+ );+ });++ test("records a finished own-instance setup as having no sample, and requests none", async () => {+ await startAtTeam({ goal: CHANGE_GOAL, database: OWN_INSTANCE });+ finishAlone();+ await landed();++ expect(eventsNamed("sample instance requested")).toEqual([]);+ expect(eventsNamed("workspace setup submitted")).toEqual([+ {+ setup_version: "v2",+ result: "finished",+ scenario: "create-database-change",+ source: "own",+ team_size: "just-me",+ invite_count: 0,+ sample_enabled: false,+ collaboration_type: "solo",+ },+ ]);+ });++ test("records a failed Finish with the stage that failed, then the finish without the sample", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam({ goal: EXPLORING });+ finishAlone();+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Finish without the sample" })+ );+ await landed();++ const answers = {+ setup_version: "v2",+ scenario: "just-exploring",+ team_size: "just-me",+ invite_count: 0,+ collaboration_type: "solo",+ };+ expect(eventsNamed("workspace setup submitted")).toEqual([+ {+ ...answers,+ result: "failed",+ failure_stage: "sample",+ source: "sample",+ sample_enabled: true,+ },+ { ...answers, result: "finished", source: "own", sample_enabled: false },+ ]);+ });++ test("records a project ID the server refused as a failed project stage", async () => {+ mocks.createProject.mockRejectedValueOnce(alreadyExists());+ await startAtTeam({ database: OWN_INSTANCE });+ finishAlone();+ await screen.findByText(ID_EXISTS);++ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({+ result: "failed",+ failure_stage: "project",+ source: "own",+ sample_enabled: false,+ }),+ ]);+ });+ });++ describe("draft", () => {+ test.each([+ { deployment: "self-hosted", isSaaSMode: false, heading: "Your team" },+ {+ deployment: "Cloud",+ isSaaSMode: true,+ heading: "Create a project and choose its database",+ },+ ])("resumes a draft with no project name where $deployment allows it", ({+ isSaaSMode,+ heading,+ }) => {+ mocks.isSaaSMode = isSaaSMode;+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "",+ projectId: "",+ teamSize: "2-10",+ });++ render(<WorkspaceSetupPage />);++ expect(screen.getByRole("heading", { name: heading })).toBeInTheDocument();+ });++ test("resumes on screen 3 a self-hosted draft whose create was sent before its name was cleared", () => {+ mocks.isSaaSMode = false;+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "",+ projectId: "",+ teamSize: "2-10",+ attemptedProjectId: "payments-ab12",+ });++ render(<WorkspaceSetupPage />);++ expect(+ screen.getByRole("heading", {+ name: "Create a project and choose its database",+ })+ ).toBeInTheDocument();+ });++ test.each([+ {+ who: "another user of the browser",+ user: { email: "[email protected]", workspace: "workspaces/ws1" },+ },+ {+ who: "the same user in another workspace",+ user: { email: "[email protected]", workspace: "workspaces/ws2" },+ },+ ])("does not show one account's draft to $who", async ({ user }) => {+ const first = startAtProject();+ await nameProject();+ first.unmount();++ mocks.currentUser = {+ ...mocks.currentUser,+ name: `users/${user.email}`,+ email: user.email,+ workspace: user.workspace,+ } as User;+ mocks.workspace = { ...mocks.workspace, name: user.workspace } as Workspace;+ render(<WorkspaceSetupPage />);++ expect(+ screen.getByRole("heading", { name: "Set up your workspace" })+ ).toBeInTheDocument();+ });++ test.each([+ {+ missing: "a goal",+ stored: { screen: "team", goal: "not-a-goal", emails: "x" },+ opensOn: "What do you want to do first?",+ },+ {+ missing: "a project name",+ stored: { screen: "team", goal: "query-data", projectId: "pay" },+ opensOn: "Create a project and choose its database",+ },+ ])("opens on the first unanswered screen when the stored draft is ahead of its answers, here $missing", ({+ stored,+ opensOn,+ }) => {+ storeDraft(stored);++ render(<WorkspaceSetupPage />);++ expect(+ screen.getByRole("heading", { name: opensOn })+ ).toBeInTheDocument();+ });++ test("is gone once Finish succeeds", async () => {+ const first = await startAtTeam();+ finishAlone();+ await landed();+ first.unmount();++ render(<WorkspaceSetupPage />);++ expect(+ screen.getByRole("heading", { name: "Set up your workspace" })+ ).toBeInTheDocument();+ });++ test("remembers across a reload that the project was created", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ const first = await startAtTeam();+ finishAlone();+ await failed();+ first.unmount();++ render(<WorkspaceSetupPage />);+ fireEvent.click(finishButton());++ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(1);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledTimes(2);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenLastCalledWith(+ "projects/payments-ab12"+ );+ });++ test("remembers across a reload that the sample was prepared", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ const first = await startAtTeam();+ finishInviting("[email protected]");+ await failed();+ first.unmount();++ render(<WorkspaceSetupPage />);+ fireEvent.click(screen.getByRole("button", { name: /and finish$/ }));++ await landed();+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledTimes(1);+ });++ test("keeps the sample as the project's database after a reload that cut its request short, and asks for it again", async () => {+ // The draft holds the project and no word on the sample; the server+ // lists the instance, which on self-hosted it does before it is ready.+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "sample",+ teamSize: "2-10",+ createdProject: "projects/payments-ab12",+ });+ mocks.sample = {+ available: true,+ instances: [{ instance: "projects/payments-ab12/instances/sample" }],+ };++ render(<WorkspaceSetupPage />);++ expect(+ screen.queryByText(/Its databases appear once your instance is connected/)+ ).not.toBeInTheDocument();+ fireEvent.click(finishButton());+ await landed();+ expect(writes()).toEqual(["updateUser", "updateWorkspace", "prepareSample"]);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/payments-ab12"+ );+ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({ source: "sample", sample_enabled: true }),+ ]);+ });++ test("keeps the choice to finish without the sample after a reload, though the server lists it under the project", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "just-me",+ createdProject: "projects/payments-ab12",+ });+ mocks.sample = {+ available: true,+ instances: [{ instance: "projects/payments-ab12/instances/sample" }],+ };++ render(<WorkspaceSetupPage />);+ fireEvent.click(finishButton());++ await landed();+ expect(writes()).toEqual(["updateUser", "updateWorkspace"]);+ expect(eventsNamed("workspace setup submitted")).toEqual([+ expect.objectContaining({ source: "own", sample_enabled: false }),+ ]);+ });++ test("does not take another project's sample for this one's", () => {+ storeDraft({+ screen: "project",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ createdProject: "projects/payments-ab12",+ });+ mocks.sample = {+ available: true,+ instances: [{ instance: "projects/earlier/instances/sample" }],+ };++ render(<WorkspaceSetupPage />);++ expect(screen.getByLabelText(/^Project name/)).toBeDisabled();+ expect(choice(OWN_INSTANCE)).toBeChecked();+ expect(screen.queryByText(SAMPLE)).not.toBeInTheDocument();+ expect(+ screen.getByText("This workspace has already used its sample database.")+ ).toBeInTheDocument();+ });++ test("does not stop setup when the browser will not store anything", async () => {+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new DOMException("quota");+ });+ mocks.setRecentProject.mockImplementation(() => {+ throw new DOMException("quota");+ });+ await startAtTeam();++ finishAlone();++ await landed();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "payments-ab12" },+ });+ });+ });++ describe("Finish", () => {+ test("creates nothing before Finish, then everything in order, and lands on the project home", async () => {+ await startAtTeam({ goal: CHANGE_GOAL });+ fireEvent.click(screen.getByText("2–10"));+ enterAddress("[email protected]");++ expect(writes()).toEqual([]);++ fireEvent.click(+ screen.getByRole("button", { name: "Send 1 invite and finish" })+ );++ await landed();+ expect(writes()).toEqual([+ "updateUser",+ "updateWorkspace",+ "createProject",+ "prepareSample",+ "projectMembers",+ "workspaceMembers",+ ]);+ expect(mocks.updateUser).toHaveBeenCalledWith(+ expect.objectContaining({+ user: expect.objectContaining({+ name: "users/[email protected]",+ title: "Ed",+ }),+ }),+ REPORT+ );+ expect(mocks.updateWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({+ name: "workspaces/ws1",+ title: "Workspace One",+ }),+ ["title"],+ REPORT+ );+ expect(mocks.createProject).toHaveBeenCalledWith(+ "Payments",+ "payments-ab12",+ REPORT+ );+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/payments-ab12"+ );+ const [policyRead, policyReadOptions] =+ mocks.getProjectIamPolicy.mock.calls[0];+ expect(policyRead).toMatchObject({ resource: "projects/payments-ab12" });+ expect(+ policyReadOptions.contextValues.get(skipErrorNotificationContextKey)+ ).toBe(true);+ expect(mocks.updateProjectIamPolicy).toHaveBeenCalledWith(+ "projects/payments-ab12",+ expect.anything(),+ REPORT+ );+ expect(projectBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledWith(+ [{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],+ REPORT+ );+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "payments-ab12" },+ });+ });++ test("adds the workspace role to an invitee without taking away one they already hold", async () => {+ mocks.workspacePolicy = {+ bindings: [+ { role: "roles/workspaceAdmin", members: ["user:[email protected]"] },+ { role: "roles/workspaceDBA", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;+ await startAtTeam();++ finishInviting("[email protected]");++ await landed();+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledWith(+ [+ {+ member: "user:[email protected]",+ roles: ["roles/workspaceDBA", "roles/workspaceMember"],+ },+ ],+ REPORT+ );+ });++ test("builds the workspace write on the policy the server holds then, not the one the page loaded", async () => {+ await startAtTeam();+ // Since the page loaded, ann was made a DBA from somewhere else.+ mocks.fetchWorkspaceIamPolicy.mockImplementation(async () => {+ mocks.workspacePolicy = {+ bindings: [+ { role: "roles/workspaceAdmin", members: ["user:[email protected]"] },+ { role: "roles/workspaceDBA", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;+ return mocks.workspacePolicy;+ });++ finishInviting("[email protected]");++ await landed();+ expect(mocks.fetchWorkspaceIamPolicy).toHaveBeenCalledWith(false, REPORT);+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledWith(+ [+ {+ member: "user:[email protected]",+ roles: ["roles/workspaceDBA", "roles/workspaceMember"],+ },+ ],+ REPORT+ );+ });++ test("hands the goal and team size to the guide, and ends mandatory setup on Cloud", async () => {+ await startAtTeam({ goal: EXPLORING });+ fireEvent.click(screen.getByText("Just me"));++ expect(readSelectedGuideScenarioId()).toBeUndefined();+ expect(readGuideTeamSize()).toBeUndefined();++ fireEvent.click(finishButton());++ await landed();+ expect(readSelectedGuideScenarioId()).toBe("just-exploring");+ expect(readGuideTeamSize()).toBe("just-me");+ expect(readWorkspaceSetupFinished("workspaces/ws1")).toBe(true);+ expect(mocks.setRecentProject).toHaveBeenCalledWith(+ "projects/payments-ab12"+ );+ });++ test("leaves the setup flag alone on self-hosted, where setup is not mandatory", async () => {+ mocks.isSaaSMode = false;+ await startAtTeam();+ finishAlone();++ await landed();+ expect(readWorkspaceSetupFinished("workspaces/ws1")).toBeUndefined();+ });++ test("does not save an emptied name over the account's", async () => {+ render(<WorkspaceSetupPage />);+ type(screen.getByLabelText(/^Your name/), " ");+ await goToTeam();+ finishAlone();++ await landed();+ expect(writes()).toEqual([+ "updateWorkspace",+ "createProject",+ "prepareSample",+ ]);+ });++ test("finishes the own-instance path with an empty project, on the project home", async () => {+ await startAtTeam({ database: OWN_INSTANCE });+ finishAlone();++ await landed();+ expect(writes()).toEqual(["updateUser", "updateWorkspace", "createProject"]);+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "payments-ab12" },+ });+ });++ test("holds the screen, with what it is creating, while Finish runs", async () => {+ const release = holdNextCall(mocks.prepareSampleProjectInstance);+ await startAtTeam();+ finishInviting("[email protected]");++ expect(+ await screen.findByRole("button", { name: "Setting up…" })+ ).toBeDisabled();+ expect(backButton()).toBeDisabled();+ expect(+ screen.getByText("Creating Payments and its sample database…")+ ).toBeInTheDocument();+ for (const radio of screen.getAllByRole("radio")) {+ expect(radio).toHaveAttribute("aria-disabled", "true");+ }+ expect(invitees()).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Remove [email protected]" })+ ).toBeDisabled();++ release();+ await landed();+ });++ test("shows only the progress of a retry while it runs, not the failure before it", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishAlone();+ await failed();+ const release = holdNextCall(mocks.prepareSampleProjectInstance);++ tryAgain();++ expect(+ await screen.findByRole("button", { name: "Setting up…" })+ ).toBeDisabled();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Finish without the sample" })+ ).not.toBeInTheDocument();++ release();+ await landed();+ });++ test("drops a failure's report once its screen is left", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishAlone();+ await failed();++ fireEvent.click(backButton());+ fireEvent.click(screen.getByText(OWN_INSTANCE));+ fireEvent.click(continueButton());++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Finish without the sample" })+ ).not.toBeInTheDocument();+ expect(finishButton()).toBeEnabled();+ });++ test("takes the invitees off the project when the write that added them lost its answer", async () => {+ loseAnswerOf(mocks.updateProjectIamPolicy);+ await startAtTeam();+ finishInviting("[email protected]");+ await failed();+ expect(server.projectPolicy.bindings).toHaveLength(3);++ fireEvent.click(screen.getByText("Just me"));+ finishAgain();++ await landed();+ expect(projectBindings()).toEqual([OWNER_BINDING]);+ });++ test.each([+ {+ step: "saving the names",+ fail: () => mocks.updateWorkspace.mockRejectedValueOnce(unavailable()),+ message: "Could not save your name and the workspace name.",+ },+ {+ step: "creating the project",+ fail: () => mocks.createProject.mockRejectedValueOnce(unavailable()),+ message: "Could not create Payments.",+ },+ {+ step: "preparing the sample",+ fail: () =>+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(+ unavailable()+ ),+ message: "Could not prepare the sample database.",+ },+ {+ step: "adding the invitees to the project",+ fail: () =>+ mocks.updateProjectIamPolicy.mockRejectedValueOnce(unavailable()),+ message: "Could not add the people you listed.",+ },+ {+ step: "adding the invitees to the workspace",+ fail: () =>+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable()),+ message: "Could not add the people you listed.",+ },+ ])("stays on the team screen and names the step when $step fails", async ({+ fail,+ message,+ }) => {+ fail();+ await startAtTeam();+ finishInviting("[email protected]");++ const alert = await failed();+ expect(alert).toHaveTextContent(message);+ expect(alert).toHaveTextContent("offline");+ expect(screen.getByRole("button", { name: "Try again" })).toBeEnabled();+ expect(backButton()).toBeEnabled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();+ expect(readWorkspaceSetupFinished("workspaces/ws1")).toBeUndefined();+ expect(readSelectedGuideScenarioId()).toBeUndefined();+ });++ test.each([+ {+ answer: "the team size",+ change: () => fireEvent.click(screen.getByText("Just me")),+ button: "Finish",+ },+ {+ answer: "the addresses",+ change: () =>+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ ),+ button: "Send 1 invite and finish",+ },+ ])("drops a failed attempt's error once $answer change", async ({+ change,+ button,+ }) => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();++ change();++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: button })).toBeEnabled();+ });++ test("keeps another step's failure, and Finish without the sample, when the team answers change", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();++ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );++ expect(screen.getByRole("alert")).toHaveTextContent(+ "Could not prepare the sample database."+ );+ expect(screen.getByRole("button", { name: "Try again" })).toBeEnabled();+ expect(+ screen.getByRole("button", { name: "Finish without the sample" })+ ).toBeEnabled();+ });++ test("has no members step for an account finishing alone on its first attempt", async () => {+ mocks.getProjectIamPolicy.mockRejectedValue(unavailable());+ await startAtTeam();++ finishAlone();++ await landed();+ expect(mocks.getProjectIamPolicy).not.toHaveBeenCalled();+ });++ test("writes no members when the project's access policy cannot be read, and keeps the owner on the retry", async () => {+ mocks.getProjectIamPolicy.mockRejectedValueOnce(+ unavailable("policy unavailable")+ );+ await startAtTeam();+ finishInviting("[email protected]");++ const alert = await failed();+ expect(alert).toHaveTextContent("Could not add the people you listed.");+ expect(alert).toHaveTextContent("policy unavailable");+ expect(mocks.updateProjectIamPolicy).not.toHaveBeenCalled();+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();++ tryAgain();++ await landed();+ expect(projectBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("tries again without creating the project or requesting the sample twice", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]");+ await failed();++ tryAgain();++ await landed();+ expect(writes()).toEqual([+ "updateUser",+ "updateWorkspace",+ "createProject",+ "prepareSample",+ "projectMembers",+ "workspaceMembers",+ "updateUser",+ "updateWorkspace",+ "projectMembers",+ "workspaceMembers",+ ]);+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("drops an invitee removed after a failed attempt from the project too", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();+ expect(projectBindings()).toContainEqual([+ "roles/projectDeveloper",+ ["user:[email protected]", "user:[email protected]"],+ ]);++ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ finishAgain();++ await landed();+ expect(projectBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenLastCalledWith(+ [{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],+ REPORT+ );+ });++ test("takes every invitee off the project when the answer becomes Just me after a failed attempt", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]");+ await failed();++ fireEvent.click(screen.getByText("Just me"));+ finishAgain();++ await landed();+ expect(projectBindings()).toEqual([OWNER_BINDING]);+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledTimes(1);+ });++ test("takes off the project only the addresses it added, and leaves what anyone else was given", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();+ // From somewhere else, before the retry: zoe is made a developer, and+ // bob is given a developer role that expires.+ const expiring = {+ role: "roles/projectDeveloper",+ members: ["user:[email protected]"],+ condition: { expression: 'request.time < timestamp("2027-01-01T00:00:00Z")' },+ };+ server.projectPolicy = {+ ...server.projectPolicy,+ bindings: [+ ...server.projectPolicy.bindings.map((binding) =>+ binding.role === "roles/projectDeveloper"+ ? { ...binding, members: [...binding.members, "user:[email protected]"] }+ : binding+ ),+ expiring,+ ],+ } as IamPolicy;++ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ finishAgain();++ await landed();+ expect(+ server.projectPolicy.bindings.map(({ role, members, condition }) => [+ role,+ members,+ condition?.expression ?? "",+ ])+ ).toEqual([+ ["roles/projectOwner", ["user:[email protected]"], ""],+ [expiring.role, expiring.members, expiring.condition.expression],+ [+ "roles/projectDeveloper",+ ["user:[email protected]", "user:[email protected]"],+ "",+ ],+ ["roles/sqlEditorReadUser", ["user:[email protected]"], ""],+ ]);+ });++ test("still knows after a reload which addresses it added to the project", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ const first = await startAtTeam();+ finishInviting("[email protected]");+ await failed();+ first.unmount();++ render(<WorkspaceSetupPage />);+ fireEvent.click(screen.getByText("Just me"));+ fireEvent.click(finishButton());++ await landed();+ expect(projectBindings()).toEqual([OWNER_BINDING]);+ });++ test("does not take away a role an address held before the wizard listed it", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]", "[email protected]"],+ createdProject: "projects/payments-ab12",+ });+ // From another browser, ann was given both roles already.+ server.projectPolicy = {+ ...server.projectPolicy,+ bindings: [+ ...server.projectPolicy.bindings,+ { role: "roles/projectDeveloper", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ render(<WorkspaceSetupPage />);+ fireEvent.click(+ screen.getByRole("button", { name: "Send 2 invites and finish" })+ );+ await failed();++ fireEvent.click(screen.getByText("Just me"));+ finishAgain();++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("keeps counting an address it added while the write that took it away has not been made", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ mocks.updateProjectIamPolicy.mockRejectedValueOnce(unavailable());+ finishAgain();+ await failed();++ tryAgain();++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("stops counting an address once a write has taken it away, so a later grant of it stays", async () => {+ mocks.patchWorkspaceIamPolicy+ .mockRejectedValueOnce(unavailable())+ .mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ finishAgain();+ await failed();+ // From somewhere else, bob is made a developer again.+ grantElsewhere("roles/projectDeveloper", "user:[email protected]");++ tryAgain();++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ [+ "roles/projectDeveloper",+ ["user:[email protected]", "user:[email protected]"],+ ],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("forgets what a refused write would have added, so another writer's grant stays", async () => {+ // Another browser gives ann both roles between the wizard's read and+ // its write, so the server refuses the write as made on a stale policy.+ mocks.getProjectIamPolicy.mockImplementationOnce(async () => {+ const read = server.projectPolicy;+ server.projectPolicy = {+ etag: "9",+ bindings: [+ ...read.bindings,+ { role: "roles/projectDeveloper", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;+ return read;+ });+ await startAtTeam();+ finishInviting("[email protected]");+ expect(await failed()).toHaveTextContent("concurrent update");++ fireEvent.click(screen.getByText("Just me"));+ finishAgain();++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("stops counting a removed address once the next write lands, though the removal's answer was lost", async () => {+ mocks.patchWorkspaceIamPolicy+ .mockRejectedValueOnce(unavailable())+ .mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]", "[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ // The write that takes bob away is made, and its answer lost.+ loseAnswerOf(mocks.updateProjectIamPolicy);+ finishAgain();+ await failed();+ // The next attempt writes the policy again, as it already is, then fails+ // at the workspace.+ tryAgain();+ await waitFor(() =>+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalledTimes(2)+ );+ await failed();+ // From somewhere else, bob is made a developer again.+ grantElsewhere("roles/projectDeveloper", "user:[email protected]");++ tryAgain();++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ [+ "roles/projectDeveloper",+ ["user:[email protected]", "user:[email protected]"],+ ],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("lets no lost write of an invitee's roles land after the next attempt took the invitee off", async () => {+ await startAtTeam({ database: OWN_INSTANCE });+ const land = delayLostWrite(mocks.updateProjectIamPolicy);+ finishInviting("[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );++ finishAgain();+ await landed();+ land();+ await settle();++ expect(serverBindings()).toEqual([OWNER_BINDING]);+ });++ test("lets no lost write that took an invitee off land after the next attempt listed them again", async () => {+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam({ database: OWN_INSTANCE });+ finishInviting("[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Remove [email protected]" })+ );+ const land = delayLostWrite(mocks.updateProjectIamPolicy);+ finishAgain();+ await waitFor(() =>+ expect(mocks.updateProjectIamPolicy).toHaveBeenCalledTimes(2)+ );+ await failed();+ enterAddress("[email protected]");++ finishAgain();+ await landed();+ land();+ await settle();++ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ describe("with two tabs on the wizard", () => {+ const SAVED_ELSEWHERE = "This setup continued in another tab";+ const continueHere = (tab: HTMLElement) =>+ fireEvent.click(+ within(tab).getByRole("button", { name: "Continue here" })+ );+ // Two tabs on one draft. In a browser only the other tab hears of a+ // save, so the tab that saved is closed before the notice is sent.+ const twoTabs = () => {+ const a = render(<WorkspaceSetupPage />);+ const b = render(<WorkspaceSetupPage />);+ return { a: a.container, closeA: a.unmount, b: b.container };+ };++ test("stops a tab when the other saves, until it continues there with the saved answers", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "sample",+ teamSize: "just-me",+ });+ const tab = twoTabs();+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(+ unavailable()+ );+ fireEvent.click(within(tab.a).getByRole("button", { name: /^Finish$/ }));+ await within(tab.a).findByRole("alert");+ tab.closeA();++ anotherTabSaved();++ expect(within(tab.b).getByText(SAVED_ELSEWHERE)).toBeInTheDocument();+ expect(within(tab.b).queryByRole("radio")).not.toBeInTheDocument();+ continueHere(tab.b);+ fireEvent.click(within(tab.b).getByRole("button", { name: /^Finish$/ }));++ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(1);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenLastCalledWith(+ "projects/payments-ab12"+ );+ });++ test("continues with the answers the other tab saved, not its own older ones", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Orders",+ projectId: "orders-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]"],+ });+ const tabB = render(<WorkspaceSetupPage />).container;+ // The other tab saves a Finish that created Payments.+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]"],+ attemptedProjectId: "payments-ab12",+ createdProject: "projects/payments-ab12",+ });+ server.projects.set("projects/payments-ab12", {+ name: "projects/payments-ab12",+ title: "Payments",+ });+ anotherTabSaved();++ continueHere(tabB);+ expect(+ within(tabB).getByText(/propose changes in Payments\./)+ ).toBeInTheDocument();+ fireEvent.click(+ within(tabB).getByRole("button", { name: "Send 1 invite and finish" })+ );++ await landed();+ expect(mocks.createProject).not.toHaveBeenCalled();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "payments-ab12" },+ });+ });++ test("takes off the project, from the other tab, an invitee that tab's attempt added", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]", "[email protected]"],+ });+ const tab = twoTabs();+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ fireEvent.click(+ within(tab.a).getByRole("button", { name: "Send 2 invites and finish" })+ );+ await within(tab.a).findByRole("alert");+ tab.closeA();+ anotherTabSaved();++ continueHere(tab.b);+ fireEvent.click(+ within(tab.b).getByRole("button", { name: "Remove [email protected]" })+ );+ fireEvent.click(+ within(tab.b).getByRole("button", { name: "Send 1 invite and finish" })+ );++ await landed();+ expect(serverBindings()).toEqual([+ OWNER_BINDING,+ ["roles/projectDeveloper", ["user:[email protected]"]],+ ["roles/sqlEditorReadUser", ["user:[email protected]"]],+ ]);+ });++ test("stops a running Finish once the wizard is left, so the answers of a later Finish stand", async () => {+ const release = holdNextCall(mocks.prepareSampleProjectInstance);+ const first = await startAtTeam();+ finishInviting("[email protected]");+ await waitFor(() =>+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalled()+ );++ first.unmount();+ render(<WorkspaceSetupPage />);+ finishAlone();+ await landed();+ release();+ await settle();++ expect(serverBindings()).toEqual([OWNER_BINDING]);+ expect(mocks.patchWorkspaceIamPolicy).not.toHaveBeenCalled();+ });++ test("lets no roles write of a stopped tab land after the other tab finished without its invitee", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "2-10",+ emails: ["[email protected]"],+ });+ const tab = twoTabs();+ const release = holdNextCall(mocks.updateProjectIamPolicy);+ fireEvent.click(+ within(tab.a).getByRole("button", { name: "Send 1 invite and finish" })+ );+ await waitFor(() =>+ expect(mocks.updateProjectIamPolicy).toHaveBeenCalled()+ );++ // Both tabs hear of the save, as tab A would once tab B continues.+ anotherTabSaved();+ continueHere(tab.b);+ fireEvent.click(within(tab.b).getByText("Just me"));+ fireEvent.click(+ within(tab.b).getByRole("button", { name: /^Finish$/ })+ );+ await landed();+ release();+ await settle();++ expect(serverBindings()).toEqual([OWNER_BINDING]);+ });++ describe("when the other tab takes setup up while this one works", () => {+ const stored = () =>+ JSON.parse(localStorage.getItem(DRAFT_KEY) ?? "null");+ const otherTabSaves = (draft: Record<string, unknown>) => {+ storeDraft(draft);+ anotherTabSaved();+ };+ const otherTabEnds = () => {+ localStorage.removeItem(DRAFT_KEY);+ anotherTab(null);+ };+ // The draft as the other tab saves it after taking it up: its own+ // instance, and nobody invited.+ const takenUpAlone = () => ({+ ...stored(),+ source: "own",+ teamSize: "just-me",+ emails: [],+ });++ test("gives the invitee nothing once the other tab finished setup alone during the sample", async () => {+ const release = holdNextCall(mocks.prepareSampleProjectInstance);+ await startAtTeam();+ finishInviting("[email protected]");+ await waitFor(() =>+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalled()+ );++ otherTabSaves(takenUpAlone());+ otherTabEnds();+ expect(+ screen.getByRole("button", { name: "Setting up…" })+ ).toBeDisabled();+ release();++ expect(+ await screen.findByText("This setup ended in another tab")+ ).toBeInTheDocument();+ expect(writes()).toEqual([+ "updateUser",+ "updateWorkspace",+ "createProject",+ "prepareSample",+ ]);+ expect(serverBindings()).toEqual([OWNER_BINDING]);+ expect(localStorage.getItem(DRAFT_KEY)).toBeNull();+ expect(mocks.routerReplace).not.toHaveBeenCalled();+ });++ test("creates nothing once the other tab took setup up while the names were saved", async () => {+ const release = holdNextCall(mocks.updateUser);+ await startAtTeam();+ finishAlone();+ await waitFor(() => expect(mocks.updateUser).toHaveBeenCalled());++ otherTabSaves(takenUpAlone());+ release();++ expect(await screen.findByText(SAVED_ELSEWHERE)).toBeInTheDocument();+ expect(writes()).toEqual(["updateUser"]);+ });++ test("asks for no sample and saves over nothing once the other tab took setup up during the create, which that tab then finds", async () => {+ const release = holdNextCall(mocks.createProject);+ await startAtTeam();+ finishAlone();+ await waitFor(() => expect(mocks.createProject).toHaveBeenCalled());++ const theirs = takenUpAlone();+ otherTabSaves(theirs);+ release();++ expect(await screen.findByText(SAVED_ELSEWHERE)).toBeInTheDocument();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ expect(stored()).toEqual(theirs);++ continueHere(document.body);+ fireEvent.click(finishButton());+ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(2);+ expect(server.projects.size).toBe(1);+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ });++ test.each([+ {+ read: "the project's roles",+ call: mocks.getProjectIamPolicy,+ sent: ["updateUser", "updateWorkspace", "createProject"],+ },+ {+ read: "the workspace's members",+ call: mocks.fetchWorkspaceIamPolicy,+ sent: [+ "updateUser",+ "updateWorkspace",+ "createProject",+ "projectMembers",+ ],+ },+ ])("gives the invitee nothing more once the other tab took setup up while $read were read", async ({+ call,+ sent,+ }) => {+ const release = holdNextCall(call);+ await startAtTeam({ database: OWN_INSTANCE });+ finishInviting("[email protected]");+ await waitFor(() => expect(call).toHaveBeenCalled());++ otherTabSaves(takenUpAlone());+ release();++ expect(await screen.findByText(SAVED_ELSEWHERE)).toBeInTheDocument();+ expect(writes()).toEqual(sent);+ });++ test.each([+ { outcome: "succeeds", error: undefined },+ { outcome: "fails", error: unavailable() },+ ])("neither leaves nor reports when its last write $outcome after the other tab took setup up", async ({+ error,+ }) => {+ const answer = holdNextCall(mocks.patchWorkspaceIamPolicy);+ await startAtTeam({ database: OWN_INSTANCE });+ finishInviting("[email protected]");+ await waitFor(() =>+ expect(mocks.patchWorkspaceIamPolicy).toHaveBeenCalled()+ );++ const theirs = takenUpAlone();+ otherTabSaves(theirs);+ answer(error);++ expect(await screen.findByText(SAVED_ELSEWHERE)).toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(mocks.routerReplace).not.toHaveBeenCalled();+ expect(stored()).toEqual(theirs);+ expect(readWorkspaceSetupFinished("workspaces/ws1")).toBeUndefined();+ expect(eventsNamed("workspace setup submitted")).toEqual([]);+ });++ test("saves nothing it finds about a lost create once the other tab took setup up", async () => {+ storeDraft({+ screen: "project",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "sample",+ attemptedProjectId: "payments-ab12",+ });+ const answer = holdNextCall(mocks.getProject);+ render(<WorkspaceSetupPage />);+ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());++ const theirs = {+ screen: "project",+ goal: "query-data",+ projectTitle: "Orders",+ projectId: "orders-ab12",+ source: "own",+ };+ otherTabSaves(theirs);+ answer();+ await settle();++ expect(stored()).toEqual(theirs);+ });++ test("neither clears the draft nor leaves when the other tab took setup up during a skip", async () => {+ mocks.isSaaSMode = false;+ const release = holdNextCall(mocks.updateUser);+ startAtProject();+ await nameProject();+ fireEvent.click(+ screen.getByRole("button", { name: "I'll do this later" })+ );+ await waitFor(() => expect(mocks.updateUser).toHaveBeenCalled());++ const theirs = { ...stored(), projectTitle: "Orders" };+ otherTabSaves(theirs);+ release();+ await settle();++ expect(writes()).toEqual(["updateUser"]);+ expect(mocks.routerReplace).not.toHaveBeenCalled();+ expect(stored()).toEqual(theirs);+ });++ test("reports no failure of a skip the other tab took setup up from", async () => {+ mocks.isSaaSMode = false;+ const fail = holdNextCall(mocks.updateUser);+ startAtProject();+ await nameProject();+ fireEvent.click(+ screen.getByRole("button", { name: "I'll do this later" })+ );+ await waitFor(() => expect(mocks.updateUser).toHaveBeenCalled());++ otherTabSaves({ ...stored(), projectTitle: "Orders" });+ continueHere(document.body);+ fail(unavailable());+ await settle();++ expect(screen.getByLabelText(/^Project name/)).toHaveValue("Orders");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("saves the draft as soon as it continues here, so a tab still working on it stops", () => {+ storeDraft({ screen: "goal", goal: "query-data" });+ render(<WorkspaceSetupPage />);+ anotherTabSaved();+ const before = localStorage.getItem(DRAFT_KEY);++ continueHere(document.body);++ expect(localStorage.getItem(DRAFT_KEY)).not.toBe(before);+ });++ test("saves the draft before Finish writes anything, even with no answer changed", async () => {+ await startAtTeam();+ fireEvent.click(screen.getByText("Just me"));+ const before = localStorage.getItem(DRAFT_KEY);+ holdNextCall(mocks.updateUser);++ fireEvent.click(finishButton());++ await waitFor(() => expect(mocks.updateUser).toHaveBeenCalled());+ expect(localStorage.getItem(DRAFT_KEY)).not.toBe(before);+ });+ });++ test.each([+ { change: "another key", key: "bb.recent-visit", newValue: "[]" },+ {+ change: "another account's draft",+ key: storageKeyWorkspaceSetupDraft(+ "workspaces/ws1",+ ),+ newValue: "{}",+ },+ {+ change: "another workspace's draft",+ key: storageKeyWorkspaceSetupDraft(+ "workspaces/ws2",+ ),+ newValue: "{}",+ },+ { change: "all of storage, by clearing it", key: null, newValue: null },+ ])("keeps working when another tab changes $change", ({+ key,+ newValue,+ }) => {+ render(<WorkspaceSetupPage />);++ act(() => {+ window.dispatchEvent(new StorageEvent("storage", { key, newValue }));+ });++ expect(screen.queryByText(SAVED_ELSEWHERE)).not.toBeInTheDocument();+ expect(+ screen.queryByText("This setup ended in another tab")+ ).not.toBeInTheDocument();+ expect(continueButton()).toBeEnabled();+ });++ test.each([+ {+ report: "a failed Finish",+ arrange: async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(+ unavailable()+ );+ await startAtTeam();+ finishAlone();+ },+ },+ {+ report: "a failed skip",+ arrange: async () => {+ mocks.isSaaSMode = false;+ mocks.updateUser.mockRejectedValueOnce(unavailable());+ startAtProject();+ fireEvent.click(+ screen.getByRole("button", { name: "I'll do this later" })+ );+ },+ },+ ])("drops the report of $report when it continues after the other tab saved", async ({+ arrange,+ }) => {+ await arrange();+ await failed();++ anotherTabSaved();+ fireEvent.click(screen.getByRole("button", { name: "Continue here" }));++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("sends a tab to the workspace when the other tab ends setup", () => {+ render(<WorkspaceSetupPage />);++ anotherTab(null);+ fireEvent.click(+ screen.getByRole("button", { name: "Go to the workspace" })+ );++ expect(screen.getByText("This setup ended in another tab")).toBeInTheDocument();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DASHBOARD,+ });+ });+ });++ test("keeps its own progress when the browser stops storing partway", async () => {+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "sample",+ teamSize: "2-10",+ emails: ["[email protected]"],+ });+ render(<WorkspaceSetupPage />);+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new DOMException("quota");+ });+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ fireEvent.click(+ screen.getByRole("button", { name: "Send 1 invite and finish" })+ );+ await failed();++ tryAgain();++ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(1);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledTimes(1);+ });++ test("writes nothing to a project it added nobody to, whoever holds roles there by now", async () => {+ // A Finish that created the project and stopped; it is resumed after+ // teammates were given roles on the project from another browser.+ storeDraft({+ screen: "team",+ goal: "query-data",+ projectTitle: "Payments",+ projectId: "payments-ab12",+ source: "own",+ teamSize: "just-me",+ createdProject: "projects/payments-ab12",+ });+ server.projectPolicy = {+ ...server.projectPolicy,+ bindings: [+ ...server.projectPolicy.bindings,+ { role: "roles/projectDeveloper", members: ["user:[email protected]"] },+ { role: "roles/sqlEditorReadUser", members: ["user:[email protected]"] },+ ],+ } as IamPolicy;+ render(<WorkspaceSetupPage />);++ fireEvent.click(finishButton());++ await landed();+ expect(writes()).toEqual(["updateUser", "updateWorkspace"]);+ });++ test("offers to finish without the sample only when the sample is what failed", async () => {+ mocks.createProject.mockRejectedValueOnce(unavailable());+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(+ unavailable("no capacity")+ );+ await startAtTeam();+ finishAlone();+ await failed();+ expect(+ screen.queryByRole("button", { name: "Finish without the sample" })+ ).not.toBeInTheDocument();++ tryAgain();+ fireEvent.click(+ await screen.findByRole("button", { name: "Finish without the sample" })+ );++ await landed();+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledTimes(1);+ expect(mocks.createProject).toHaveBeenCalledTimes(2);+ });++ test("does not ask for the sample again on a retry after Finish without the sample", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValueOnce(unavailable());+ mocks.patchWorkspaceIamPolicy.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishInviting("[email protected]");+ await failed();+ fireEvent.click(+ screen.getByRole("button", { name: "Finish without the sample" })+ );+ expect(await failed()).toHaveTextContent(+ "Could not add the people you listed."+ );++ tryAgain();++ await landed();+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledTimes(1);+ expect(eventsNamed("workspace setup submitted").at(-1)).toMatchObject({+ result: "finished",+ source: "own",+ sample_enabled: false,+ });+ });++ describe("when the project ID already exists", () => {+ const hold = (title: string) =>+ server.projects.set("projects/payments-ab12", {+ name: "projects/payments-ab12",+ title,+ });+ // The create reaches the server and its answer is lost.+ const loseTheFirstAnswer = async () => {+ loseAnswerOf(mocks.createProject);+ const view = await startAtTeam();+ finishAlone();+ await failed();+ return view;+ };+ // The create never reaches the server.+ const failTheFirstCreate = async () => {+ mocks.createProject.mockRejectedValueOnce(unavailable());+ await startAtTeam();+ finishAlone();+ await failed();+ };+ const adopted = async () => {+ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(2);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/payments-ab12"+ );+ expect(server.projects.size).toBe(1);+ };++ test("adopts the project its own lost attempt created", async () => {+ await loseTheFirstAnswer();++ tryAgain();++ await adopted();+ for (const read of [mocks.getProject, mocks.getProjectIamPolicy]) {+ expect(+ read.mock.calls[0][1].contextValues.get(+ skipErrorNotificationContextKey+ )+ ).toBe(true);+ }+ });++ test("adopts it after a reload too", async () => {+ const first = await loseTheFirstAnswer();+ first.unmount();++ render(<WorkspaceSetupPage />);+ fireEvent.click(finishButton());++ await adopted();+ });++ test("finds it on Back, and shows the project as existing from then on", async () => {+ await loseTheFirstAnswer();++ fireEvent.click(backButton());++ await waitFor(() =>+ expect(screen.getByLabelText(/^Project name/)).toBeDisabled()+ );+ expect(+ screen.getByText(+ "This project already exists. Rename it in its settings."+ )+ ).toBeInTheDocument();+ expect(screen.queryByText(ID_EXISTS)).not.toBeInTheDocument();+ fireEvent.click(continueButton());+ fireEvent.click(finishButton());++ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(1);+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/payments-ab12"+ );+ });++ test("calls it a clash on Back when the project that holds the ID is not its own", async () => {+ await failTheFirstCreate();+ hold("Billing");++ fireEvent.click(backButton());++ expect(await screen.findByText(ID_EXISTS)).toBeInTheDocument();+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ expect(continueButton()).toBeDisabled();+ });++ test("does not give the project it finds the name and ID typed while it looked", async () => {+ await loseTheFirstAnswer();+ const answer = holdNextCall(mocks.getProject);++ fireEvent.click(backButton());+ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());+ await nameProject("Orders");+ answer();++ await waitFor(() =>+ expect(mocks.getProjectIamPolicy).toHaveBeenCalled()+ );+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ expect(screen.getByLabelText(/^Project name/)).toHaveValue("Orders");+ fireEvent.click(continueButton());+ fireEvent.click(finishButton());+ await landed();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "orders-ab12" },+ });+ });++ test.each([+ {+ edit: "a new name with the ID kept",+ change: async () => {+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));+ type(screen.getByLabelText(/^Project name/), "Orders");+ },+ },+ {+ edit: "a new ID with the name kept",+ change: async () => editProjectId("payments-2"),+ },+ ])("drops what it finds when $edit was typed while it looked", async ({+ change,+ }) => {+ await loseTheFirstAnswer();+ const answer = holdNextCall(mocks.getProject);+ fireEvent.click(backButton());+ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());++ await change();+ answer();++ await waitFor(() =>+ expect(mocks.getProjectIamPolicy).toHaveBeenCalled()+ );+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ expect(+ screen.queryByText(+ "This project already exists. Rename it in its settings."+ )+ ).not.toBeInTheDocument();+ });++ test("leaves a create it finds missing unsettled, so the retry takes the project as its own once the create lands", async () => {+ mocks.isSaaSMode = false;+ const land = delayLostWrite(mocks.createProject);+ await startAtTeam();+ finishAlone();+ await failed();++ fireEvent.click(backButton());+ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());+ await settle();+ expect(+ screen.queryByRole("button", { name: "I'll do this later" })+ ).not.toBeInTheDocument();+ land();+ await settle();+ fireEvent.click(continueButton());+ fireEvent.click(finishButton());++ await landed();+ expect(mocks.createProject).toHaveBeenCalledTimes(2);+ expect(server.projects.size).toBe(1);+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: "payments-ab12" },+ });+ });++ test("saves nothing it finds once Finish has ended setup while it looked", async () => {+ await loseTheFirstAnswer();+ const answer = holdNextCall(mocks.getProject);+ fireEvent.click(backButton());+ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());++ fireEvent.click(continueButton());+ fireEvent.click(finishButton());+ await landed();+ answer();+ await settle();++ expect(localStorage.getItem(DRAFT_KEY)).toBeNull();+ });++ test("leaves the ID usable on Back when the server cannot be read", async () => {+ await loseTheFirstAnswer();+ mocks.getProject.mockRejectedValueOnce(unavailable());++ fireEvent.click(backButton());++ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ expect(screen.queryByText(ID_EXISTS)).not.toBeInTheDocument();+ expect(continueButton()).toBeEnabled();+ });++ test("leaves the project editable on Back when the create never reached the server", async () => {+ await failTheFirstCreate();++ fireEvent.click(backButton());++ await waitFor(() => expect(mocks.getProject).toHaveBeenCalled());+ expect(screen.getByLabelText(/^Project name/)).toBeEnabled();+ expect(screen.queryByText(ID_EXISTS)).not.toBeInTheDocument();+ expect(continueButton()).toBeEnabled();+ });++ test.each([+ { what: "the project", read: mocks.getProject },+ { what: "its access policy", read: mocks.getProjectIamPolicy },+ ])("stays retryable when $what cannot be read", async ({ read }) => {+ await loseTheFirstAnswer();+ read.mockRejectedValueOnce(unavailable("read failed"));++ tryAgain();++ const alert = await failed();+ expect(alert).toHaveTextContent("Could not create Payments.");+ expect(alert).toHaveTextContent("read failed");+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();++ tryAgain();++ await landed();+ expect(server.projects.size).toBe(1);+ });++ test.each([+ {+ whose: "someone else has been given access to",+ bindings: [+ { role: "roles/projectOwner", members: ["user:[email protected]"] },+ { role: "roles/projectDeveloper", members: ["user:[email protected]"] },+ ],+ },+ {+ whose: "someone else owns",+ bindings: [+ { role: "roles/projectOwner", members: ["user:[email protected]"] },+ ],+ },+ {+ whose: "this account holds without owning",+ bindings: [+ { role: "roles/projectDeveloper", members: ["user:[email protected]"] },+ ],+ },+ {+ whose: "has a second owner",+ bindings: [+ {+ role: "roles/projectOwner",+ members: ["user:[email protected]", "user:[email protected]"],+ },+ ],+ },+ ])("does not take over a project of the same ID and name that $whose", async ({+ bindings,+ }) => {+ await failTheFirstCreate();+ hold("Payments");+ server.projectPolicy = { etag: "7", bindings } as IamPolicy;++ tryAgain();++ await screen.findByText(ID_EXISTS, { selector: "li" });+ expect(continueButton()).toBeDisabled();+ expect(writes()).not.toContain("projectMembers");+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ expect(server.projectPolicy.bindings).toEqual(bindings);+ });++ test("asks for another ID when the project that holds it has another name", async () => {+ await failTheFirstCreate();+ hold("Billing");++ tryAgain();++ // Once the field's own check has answered, it is the one place that+ // says so.+ await screen.findByText(ID_EXISTS, { selector: "li" });+ expect(screen.getAllByText(ID_EXISTS)).toHaveLength(1);+ expect(continueButton()).toBeDisabled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ });++ test("asks for another ID when the ID is held outside this workspace, after a reload too, until the ID changes", async () => {+ const first = await startAtTeam();+ // Another workspace's project: the create is refused, and this+ // workspace cannot read it.+ mocks.createProject.mockRejectedValue(alreadyExists());+ finishAlone();++ expect(await failed()).toHaveTextContent(ID_EXISTS);+ expect(continueButton()).toBeDisabled();++ first.unmount();+ render(<WorkspaceSetupPage />);++ expect(await failed()).toHaveTextContent(ID_EXISTS);+ expect(continueButton()).toBeDisabled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();++ editProjectId("payments-2");++ await waitFor(() => expect(continueButton()).toBeEnabled());+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("asks for another ID when a retry finds the ID held outside this workspace", async () => {+ await failTheFirstCreate();+ mocks.createProject.mockRejectedValueOnce(alreadyExists());++ tryAgain();++ expect(await failed()).toHaveTextContent(ID_EXISTS);+ expect(continueButton()).toBeDisabled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ });++ test("asks for another ID on a first attempt, even when a project of the same name holds it", async () => {+ const first = await startAtTeam();+ hold("Payments");++ finishAlone();++ await screen.findByText(ID_EXISTS, { selector: "li" });+ expect(screen.getAllByText(ID_EXISTS)).toHaveLength(1);+ expect(continueButton()).toBeDisabled();+ expect(mocks.getProject).not.toHaveBeenCalled();++ // The refusal settled that create: a reload does not turn it into one+ // whose answer was lost.+ first.unmount();+ render(<WorkspaceSetupPage />);++ await screen.findByText(ID_EXISTS, { selector: "li" });+ expect(continueButton()).toBeDisabled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();+ });++ });++ test("returns to the project screen with the server's reason when it refuses the ID", async () => {+ mocks.createProject.mockRejectedValueOnce(+ new ConnectError(+ 'project ID "payments-ab12" is reserved',+ Code.InvalidArgument+ )+ );+ const first = await startAtTeam();++ finishAlone();++ expect(await failed()).toHaveTextContent(+ 'project ID "payments-ab12" is reserved'+ );+ expect(screen.getByLabelText(/^Project name/)).toHaveValue("Payments");+ expect(continueButton()).toBeDisabled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();++ first.unmount();+ render(<WorkspaceSetupPage />);++ expect(await failed()).toHaveTextContent(+ 'project ID "payments-ab12" is reserved'+ );+ expect(continueButton()).toBeDisabled();++ editProjectId("main");++ await waitFor(() => expect(continueButton()).toBeEnabled());+ });+ });});diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.tsxindex e4fde41a3c..60104b80b2 100644--- a/frontend/src/routes/auth/WorkspaceSetupPage.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.tsx@@ -1,22 +1,16 @@-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { useCallback, useEffect, useRef, useState } from "react";+import { ConnectError } from "@connectrpc/connect";+import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { createBehaviorMetric } from "@/app/analytics/behavior";import { behaviorAnalytics } from "@/app/analytics/provider";+import { SplashPanel } from "@/app/layouts/SplashLayout";import { router } from "@/app/router";import {PROJECT_V1_ROUTE_DASHBOARD,PROJECT_V1_ROUTE_DETAIL,} from "@/app/router/handles";-import { ResourceIdField } from "@/components/ResourceIdField";import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { FormField } from "@/components/ui/form";-import { Input } from "@/components/ui/input";-import { StepIndicator } from "@/components/ui/step-indicator";import {- useCreateProject,useCurrentUser,useIntroStateByKey,useWorkspace,@@ -26,99 +20,210 @@ import {CREATE_PROJECT_PRODUCT_INTRO,PRODUCT_INTRO_QUERY_KEY,} from "@/lib/productIntro";-import { cn } from "@/lib/utils";import {- clearGuideWorkspaceUsage,- clearSelectedGuideScenarioId,- saveGuideWorkspaceUsage,+ saveGuideTeamSize,saveSelectedGuideScenarioId,} from "@/modules/workspace-setup-guide/selection";import { saveWorkspaceSetupFinished } from "@/modules/workspace-setup-guide/setup";-import type {- GuideScenarioId,- GuideWorkspaceUsage,-} from "@/modules/workspace-setup-guide/types";-import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";import type { ValidatedMessage } from "@/types";-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";-import { WorkspaceSchema } from "@/types/proto-es/v1/workspace_service_pb";-import { extractProjectResourceName } from "@/utils";-import { extractGrpcErrorMessage } from "@/utils/connect";-import { WorkspaceSetupQuestionnaireStep } from "./WorkspaceSetupQuestionnaireStep";+import { extractProjectResourceName } from "@/utils/v1/project";+import {+ clearSetupDraft,+ projectOptional,+ readSetupDraft,+ type SetupDraft,+ type SetupSource,+ saveSetupDraft,+ watchSetupDraft,+} from "./workspace-setup/draft";+import {+ findLostCreate,+ runSetupFinish,+ type SetupNames,+ saveSetupNames,+} from "./workspace-setup/finish";+import { GoalScreen } from "./workspace-setup/GoalScreen";+import { validInviteAddresses } from "./workspace-setup/inviteEmails";+import {+ ProjectScreen,+ type SampleOffer,+} from "./workspace-setup/ProjectScreen";+import {+ guessDisplayName,+ guessWorkspaceTitle,+} from "./workspace-setup/prefill";+import { SetupPanel } from "./workspace-setup/SetupPanel";+import {+ type SetupFinishFailure,+ TeamScreen,+} from "./workspace-setup/TeamScreen";+import { WorkspaceScreen } from "./workspace-setup/WorkspaceScreen";const WORKSPACE_SETUP_PAGE_ENTERED_KEY = "workspace-setup.page-entered.v1";-const WORKSPACE_SETUP_VERSION = "v1";+const WORKSPACE_SETUP_VERSION = "v2";++// The server's own words for a failure, when it gave any.+const serverReason = (error: unknown) =>+ error instanceof ConnectError ? error.rawMessage : undefined;export function WorkspaceSetupPage() {+ const currentUser = useCurrentUser();+ // The draft is kept per account, which is known only once the user loads.+ if (!currentUser.email) return null;+ return <WorkspaceSetupWizard key={currentUser.email} />;+}++function WorkspaceSetupWizard() {const { t } = useTranslation();const currentUser = useCurrentUser();- const updateUser = useAppStore((state) => state.updateUser);- const updateWorkspace = useAppStore((state) => state.updateWorkspace);- const prepareSampleProjectInstance = useAppStore(- (state) => state.prepareSampleProjectInstance- );- const isSaaSMode = useAppStore((state) => state.isSaaSMode());- const sampleAvailable = useAppStore(- (state) => state.serverInfo?.sample?.available ?? false- );- const sampleProvisioned = useAppStore(- (state) => (state.serverInfo?.sample?.instances.length ?? 0) > 0- );- const canPrepareSample = sampleAvailable && !sampleProvisioned;- const { createProject, setRecentProject } = useCreateProject();const workspace = useWorkspace();const workspacePolicy = useAppStore((state) => state.workspacePolicy);+ const isSaaSMode = useAppStore((state) => state.isSaaSMode());+ const sample = useAppStore((state) => state.serverInfo?.sample);const canUpdateWorkspace = useWorkspacePermission("bb.workspaces.update");- const canCreateProject = useWorkspacePermission("bb.projects.create");const setupPageEntered = useIntroStateByKey(WORKSPACE_SETUP_PAGE_ENTERED_KEY);const setupPageEnteredRef = useRef(false);+ const [draft, setDraft] = useState<SetupDraft>(() =>+ readSetupDraft(isSaaSMode)+ );+ // One tab works on setup at a time: the one that saved the draft last. When+ // another tab saves it or ends setup, this one shows a notice in place of+ // its screen. Then, or once setup ends here or the wizard is left, what it+ // had started writes nothing more (D11).+ const [elsewhere, setElsewhere] = useState<"saved" | "ended">();+ const lostHolds = useRef(0);+ useEffect(() => {+ const stopWatching = watchSetupDraft((ended) => {+ lostHolds.current += 1;+ setElsewhere(ended ? "ended" : "saved");+ });+ return () => {+ stopWatching();+ lostHolds.current += 1;+ };+ }, []);+ // For work starting now: true once this tab no longer holds setup.+ const supersededFromNow = () => {+ const at = lostHolds.current;+ return () => lostHolds.current !== at;+ };+ const endSetup = () => {+ lostHolds.current += 1;+ clearSetupDraft();+ };+ // Written through on every answer, so a reload, or a tab closed while Finish+ // runs, loses nothing: least of all that the project was created.+ const draftRef = useRef(draft);+ const update = (patch: Partial<SetupDraft>) => {+ const next = { ...draftRef.current, ...patch };+ draftRef.current = next;+ setDraft(next);+ saveSetupDraft(next);+ setElsewhere(undefined);+ };+ // False only while the ID field shows why. Its checks answer after each+ // change, and Finish has the server's word on an ID that got past them.+ const [projectIdValid, setProjectIdValid] = useState(true);+ const [finishing, setFinishing] = useState(false);+ const [failure, setFailure] = useState<SetupFinishFailure>();+ const [skipping, setSkipping] = useState(false);+ const [skipFailure, setSkipFailure] = useState<{ detail?: string }>();++ const idTaken = t("resource-id.validation.duplicated", {+ resource: t("common.project"),+ });+ const validateProjectId = async (id: string): Promise<ValidatedMessage[]> => {+ const taken: ValidatedMessage[] = [{ type: "error", message: idTaken }];+ const { attemptedProjectId, projectTitle } = draftRef.current;+ if (attemptedProjectId !== id) {+ const existing = await useAppStore+ .getState()+ .fetchProject(`${projectNamePrefix}${id}`, true);+ return existing ? taken : [];+ }+ // A create for this ID got no answer. A project that holds the ID settles+ // it: the draft's own exists from here on, and another's leaves nothing of+ // the draft's behind. No project settles nothing, as the create may still+ // be on its way.+ const superseded = supersededFromNow();+ try {+ const found = await findLostCreate(+ id,+ projectTitle.trim(),+ currentUser.email+ );+ // The answer is about the name and ID it was asked with; one typed+ // while it was out is not that project's, and a draft this tab no longer+ // holds is not its to settle.+ const now = draftRef.current;+ if (+ found.kind === "absent" ||+ superseded() ||+ now.projectId !== id ||+ now.projectTitle !== projectTitle+ ) {+ return [];+ }+ update({+ attemptedProjectId: undefined,+ ...(found.kind === "own" ? { createdProject: found.project } : {}),+ });+ return found.kind === "other" ? taken : [];+ } catch {+ // Still unknown; Finish asks the server again.+ return [];+ }+ };- // Show workspace name field only if the user is the sole member of the- // workspace (i.e. they just created it), not when they were invited.+ // Only the sole member, who just created the workspace, names it; an+ // invited account joins a workspace that already has its name.const canRenameWorkspace =canUpdateWorkspace &&(workspacePolicy?.bindings ?? []).reduce(- (count, b) => count + b.members.length,+ (count, binding) => count + binding.members.length,0) === 1;- const [setupStep, setSetupStep] = useState<"scenario" | "workspace">(- "scenario"- );- const [selectedScenarioId, setSelectedScenarioId] =- useState<GuideScenarioId>();- const [workspaceUsage, setWorkspaceUsage] = useState<GuideWorkspaceUsage>();-- // `currentUser` loads asynchronously (unknownUser with an empty email until- // then), so seed the name field once the real user is known rather than- // freezing on the placeholder title. The ref keeps it a one-shot seed so- // later edits aren't clobbered.- const [name, setName] = useState(- currentUser.email ? (currentUser.title ?? "") : ""- );- const nameSeededRef = useRef(Boolean(currentUser.email));- useEffect(() => {- if (!nameSeededRef.current && currentUser.email) {- nameSeededRef.current = true;- setName(currentUser.title ?? "");+ const guessedName = guessDisplayName(currentUser.email, currentUser.title);+ const guessedWorkspaceTitle = () => {+ const guess = guessWorkspaceTitle(+ currentUser.email,+ guessedName,+ workspace?.title+ );+ switch (guess.kind) {+ case "title":+ return guess.title;+ case "personal":+ return t("workspace-setup.workspace.default-name", {+ name: guess.firstName,+ });+ case "anonymous":+ return t("workspace-setup.workspace.default-name-anonymous");}- }, [currentUser.email, currentUser.title]);- const [workspaceTitle, setWorkspaceTitle] = useState(workspace?.title ?? "");- const [projectTitle, setProjectTitle] = useState(() =>- t("settings.profile.default-project-name")+ };+ // A sample the server lists under this draft's own project is not one+ // another project used: a reload cut its request short, and the stored+ // choice still decides whether to ask for it again.+ const sampleUsedElsewhere = !!sample?.instances.some(+ ({ instance }) =>+ !draft.createdProject || !instance.startsWith(`${draft.createdProject}/`));- const [projectResourceId, setProjectResourceId] = useState("");- const [isProjectResourceIdValid, setIsProjectResourceIdValid] =- useState(false);- const [enableSampleDatabases, setEnableSampleDatabases] = useState(true);- const [saving, setSaving] = useState(false);- const shouldCreateProject = canCreateProject && !!projectTitle.trim();- const projectIsReady =- shouldCreateProject && !!projectResourceId && isProjectResourceIdValid;- const sampleRequested =- shouldCreateProject && enableSampleDatabases && canPrepareSample;- const canEnableSample = !!projectTitle.trim() && !!projectResourceId;+ const sampleOffer: SampleOffer = !sample?.available+ ? "unavailable"+ : sampleUsedElsewhere+ ? "used"+ : "offered";+ // Once its request has returned, the sample is the project's database+ // whatever the server offers now.+ const source: SetupSource = draft.samplePrepared+ ? "sample"+ : sampleOffer === "offered"+ ? draft.source+ : "own";+ const name = draft.name ?? guessedName;+ const workspaceTitle = draft.workspaceTitle ?? guessedWorkspaceTitle();useEffect(() => {if (@@ -145,319 +250,332 @@ export function WorkspaceSetupPage() {);}, [currentUser.name, setupPageEntered, workspace?.name]);- const validateProjectResourceId = useCallback(- async (id: string): Promise<ValidatedMessage[]> => {- try {- const existing = await useAppStore- .getState()- .fetchProject(`${projectNamePrefix}${id}`, true);- if (!existing) return [];- return [- {- type: "error",- message: t("resource-id.validation.duplicated", {- resource: t("common.project"),- }),- },- ];- } catch {- return [];- }- },- [t]- );-- const canSave =- !!name.trim() &&- !saving &&- (isSaaSMode ? projectIsReady : !shouldCreateProject || projectIsReady);+ // A failed attempt is reported for the answers it ran with, so the report+ // goes when its screen is left, and a failure adding the people listed goes+ // when the team answers change. Any other step's failure still stands then.+ const show = (screen: SetupDraft["screen"]) => {+ setFailure(undefined);+ setSkipFailure(undefined);+ update({ screen });+ };+ const answerTeam = (+ patch: Partial<Pick<SetupDraft, "teamSize" | "emails">>+ ) => {+ if (failure?.stage === "invitees") setFailure(undefined);+ update(patch);+ };- const handleSave = async () => {- if (!currentUser?.name || !canSave) return;- setSaving(true);- try {- await updateUser(- create(UpdateUserRequestSchema, {- user: { name: currentUser.name, title: name.trim() },- updateMask: create(FieldMaskSchema, { paths: ["title"] }),- })- );- if (canRenameWorkspace && workspaceTitle.trim() && workspace?.name) {- await updateWorkspace(- create(WorkspaceSchema, {- name: workspace.name,- title: workspaceTitle.trim(),- }),- ["title"]- );- }- let createdProjectName = "";- if (shouldCreateProject) {- const createdProject = await createProject(- projectTitle.trim(),- projectResourceId- );- setRecentProject(createdProject.name);- createdProjectName = createdProject.name;- if (sampleRequested && createdProject.name) {- behaviorAnalytics.captureMetric(- createBehaviorMetric("sample instance requested", {- properties: { source: "workspace_setup" },- })- );- try {- await prepareSampleProjectInstance(createdProject.name);- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("instance.prepare-sample-instance-failed"),- description: extractGrpcErrorMessage(error),- });- }- }- }- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("settings.profile.setup-success"),- });- if (isSaaSMode) {- saveWorkspaceSetupFinished(- workspace?.name ?? currentUser.workspace,- true- );- }- behaviorAnalytics.captureMetric(- createBehaviorMetric("workspace setup submitted", {- properties: {- scenario: selectedScenarioId ?? "unselected",- collaboration_type: workspaceUsage ?? "unselected",- result: "finished",- sample_enabled: sampleRequested,- },- })- );- if (createdProjectName) {- router.replace({- name: PROJECT_V1_ROUTE_DETAIL,- params: {- projectId: extractProjectResourceName(createdProjectName),- },- });- } else {- goToDashboard();- }- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("settings.profile.setup-failed"),- });- } finally {- setSaving(false);- }+ // Takes the stored draft up only when asked: a screen's fields and a failure+ // report hold state that a draft taken in underneath them would not match.+ const continueHere = () => {+ draftRef.current = readSetupDraft(isSaaSMode);+ // Saved at once, so a tab still working on the draft stops there.+ show(draftRef.current.screen);+ setProjectIdValid(true);};- const goToDashboard = () => {- router.replace({- name: PROJECT_V1_ROUTE_DASHBOARD,- query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },- });+ // Emitted on the click, so a leaver can be placed on a screen. No event+ // carries a name, an address or a project name.+ const continueFrom = (screen: 1 | 2 | 3, next: SetupDraft["screen"]) => {+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("workspace setup screen continued", {+ properties: {+ setup_version: WORKSPACE_SETUP_VERSION,+ screen,+ goal: draft.goal ?? "unselected",+ project_named: !!draft.projectTitle.trim(),+ ...(screen === 3 ? { source } : {}),+ },+ })+ );+ show(next);};- const handleSkip = () => {+ const captureSubmitted = (properties: Record<string, unknown>) =>behaviorAnalytics.captureMetric(createBehaviorMetric("workspace setup submitted", {properties: {- scenario: selectedScenarioId ?? "unselected",- collaboration_type: workspaceUsage ?? "unselected",- result: "skipped",- sample_enabled: false,+ setup_version: WORKSPACE_SETUP_VERSION,+ scenario: draft.goal ?? "unselected",+ ...properties,},}));- goToDashboard();++ const names: SetupNames = {+ userName: currentUser.name,+ displayName: name.trim(),+ workspaceName: canRenameWorkspace ? workspace?.name : undefined,+ workspaceTitle: workspaceTitle.trim(),+ };++ // The projects page, which offers to create the first one.+ const leaveWithoutProject = () =>+ router.replace({+ name: PROJECT_V1_ROUTE_DASHBOARD,+ query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },+ });++ // Self-hosted only: setup is offered once there and may be left for later.+ const skip = async () => {+ const superseded = supersededFromNow();+ setSkipping(true);+ setSkipFailure(undefined);+ try {+ await saveSetupNames(names, superseded);+ } catch (error) {+ if (!superseded()) setSkipFailure({ detail: serverReason(error) });+ setSkipping(false);+ return;+ }+ if (superseded()) {+ setSkipping(false);+ return;+ }+ endSetup();+ if (draft.goal) saveSelectedGuideScenarioId(draft.goal);+ captureSubmitted({ result: "skipped", sample_enabled: false });+ leaveWithoutProject();};- const setupSteps = [- {- key: "scenario",- title: t("settings.profile.setup-steps.scenario"),- },- {- key: "workspace",- title: t("settings.profile.setup-steps.workspace"),- },- ];+ const mayLeaveProject = projectOptional(draft, isSaaSMode);+ const withoutProject = mayLeaveProject && !draft.projectTitle.trim();+ // The addresses Finish adds. Self-hosted lists no one (D7), whatever an+ // earlier draft holds.+ const invitees =+ !isSaaSMode || draft.teamSize === "just-me"+ ? []+ : validInviteAddresses(draft.emails, currentUser.email);++ const finish = async ({ withoutSample = false } = {}) => {+ if (!draft.teamSize) return;+ // Saved first, so another tab on the draft stops before this attempt+ // writes.+ update(withoutSample ? { source: "own" } : {});+ const superseded = supersededFromNow();+ // What the attempt learns is saved only while this tab holds setup.+ const save = (patch: Partial<SetupDraft>) => {+ if (!superseded()) update(patch);+ };+ setFinishing(true);+ setFailure(undefined);+ const finishSource: SetupSource = withoutSample ? "own" : source;+ const answers = {+ source: withoutProject ? "none" : finishSource,+ team_size: draft.teamSize,+ invite_count: invitees.length,+ // Kept beside `team_size` for the dashboards built on the earlier+ // wizard's team-or-solo answer.+ collaboration_type: draft.teamSize === "just-me" ? "solo" : "team",+ sample_enabled: !withoutProject && finishSource === "sample",+ };+ const result = await runSetupFinish(+ {+ ...names,+ withoutProject,+ projectTitle: draft.projectTitle.trim(),+ projectId: draft.projectId,+ createdProject: draft.createdProject,+ ownerEmail: currentUser.email,+ createAttempted: draft.attemptedProjectId === draft.projectId,+ // Asked again until the request has returned once: a self-hosted+ // server lists the instance before it is ready, and a repeated+ // request answers with the same one.+ prepareSample:+ !withoutProject && finishSource === "sample" && !draft.samplePrepared,+ invitees,+ projectGrants: draft.projectGrants ?? {},+ superseded,+ },+ {+ projectCreateSent: () => save({ attemptedProjectId: draft.projectId }),+ projectCreated: (createdProject) => save({ createdProject }),+ samplePrepared: () => save({ samplePrepared: true }),+ projectGrants: (projectGrants) => save({ projectGrants }),+ }+ );+ if ("superseded" in result) {+ // The notice that took the screen's place shows from here.+ setFinishing(false);+ return;+ }+ if (!result.ok) {+ captureSubmitted({+ ...answers,+ result: "failed",+ failure_stage: result.stage,+ });+ if (result.refusal) {+ // The server settled that create: nothing of this draft's holds the ID.+ update({+ attemptedProjectId: undefined,+ refusedProjectId: { id: draft.projectId, ...result.refusal },+ });+ show("project");+ } else {+ setFailure({+ stage: result.stage,+ detail: serverReason(result.error),+ });+ }+ setFinishing(false);+ return;+ }+ captureSubmitted({ ...answers, result: "finished" });+ endSetup();+ if (draft.goal) saveSelectedGuideScenarioId(draft.goal);+ saveGuideTeamSize(draft.teamSize);+ if (isSaaSMode) {+ saveWorkspaceSetupFinished(+ workspace?.name ?? currentUser.workspace,+ true+ );+ }+ if (!result.project) {+ leaveWithoutProject();+ return;+ }+ try {+ useAppStore.getState().setRecentProject(result.project);+ } catch {+ // Everything exists on the server; a browser that cannot store the+ // recent project must still leave the wizard.+ }+ router.replace({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: extractProjectResourceName(result.project) },+ });+ };- if (setupStep === "scenario") {- return (- <div className="flex min-h-screen items-center justify-center px-4">- <div className="flex w-full max-w-lg flex-col gap-y-6">- <StepIndicator steps={setupSteps} currentKey={setupStep} />- <WorkspaceSetupQuestionnaireStep- scenarioValue={selectedScenarioId}- workspaceUsageValue={workspaceUsage}- required={isSaaSMode}- onScenarioChange={setSelectedScenarioId}- onWorkspaceUsageChange={setWorkspaceUsage}- onContinue={() => {- if (selectedScenarioId) {- saveSelectedGuideScenarioId(selectedScenarioId);+ const renderScreen = () => {+ switch (draft.screen) {+ case "workspace":+ return (+ <WorkspaceScreen+ name={name}+ workspaceTitle={workspaceTitle}+ showWorkspaceTitle={canRenameWorkspace}+ onNameChange={(value) => update({ name: value })}+ onWorkspaceTitleChange={(value) =>+ update({ workspaceTitle: value })+ }+ onContinue={() => continueFrom(1, "goal")}+ />+ );+ case "goal":+ return (+ <GoalScreen+ goal={draft.goal}+ onGoalChange={(goal) => update({ goal })}+ onBack={() => show("workspace")}+ onContinue={() => continueFrom(2, "project")}+ />+ );+ case "team":+ return (+ <TeamScreen+ teamSize={draft.teamSize}+ addresses={draft.emails}+ ownerEmail={currentUser.email}+ projectTitle={draft.projectTitle.trim()}+ source={source}+ isSaaS={isSaaSMode}+ onTeamSizeChange={(teamSize) => answerTeam({ teamSize })}+ onAddressesChange={(emails) => answerTeam({ emails })}+ finishing={finishing}+ failure={failure}+ onBack={() => show("project")}+ onFinish={() => void finish()}+ onFinishWithoutSample={() => void finish({ withoutSample: true })}+ />+ );+ case "project":+ return (+ <ProjectScreen+ projectTitle={draft.projectTitle}+ projectId={draft.projectId}+ projectIdValid={projectIdValid}+ projectIdRefusal={+ draft.refusedProjectId?.id === draft.projectId+ ? (draft.refusedProjectId.reason ?? idTaken)+ : undefined+ }+ projectExists={!!draft.createdProject}+ source={source}+ sample={sampleOffer}+ samplePrepared={!!draft.samplePrepared}+ isSaaS={isSaaSMode}+ projectOptional={mayLeaveProject}+ skipping={skipping}+ skipFailure={skipFailure}+ onSkip={mayLeaveProject ? () => void skip() : undefined}+ validateProjectId={validateProjectId}+ onProjectTitleChange={(projectTitle) => {+ if (projectTitle.trim()) {+ update({ projectTitle });} else {- clearSelectedGuideScenarioId();+ // An unnamed project has no ID, and so no verdict on one; the+ // next name derives a new ID.+ update({ projectTitle, projectId: "" });+ setProjectIdValid(true);}- if (workspaceUsage) {- saveGuideWorkspaceUsage(workspaceUsage);- } else {- clearGuideWorkspaceUsage();+ }}+ onProjectIdChange={(projectId) => {+ if (draftRef.current.projectId !== projectId) {+ update({ projectId });}- setSetupStep("workspace");}}+ onProjectIdValidChange={setProjectIdValid}+ onSourceChange={(source) => update({ source })}+ onBack={() => show("goal")}+ onContinue={() => continueFrom(3, "team")}/>- </div>- </div>- );- }+ );+ }+ };return (- <div className="flex flex-col items-center justify-center min-h-screen px-4">- <div className="w-full max-w-lg mx-4 flex flex-col items-center gap-y-6">- <StepIndicator- className="w-full"- steps={setupSteps}- currentKey={setupStep}+ <>+ <SplashPanel>+ <SetupPanel+ screen={draft.screen}+ goal={draft.goal}+ workspaceTitle={+ canRenameWorkspace ? workspaceTitle : (workspace?.title ?? "")+ }+ memberName={name.trim() || currentUser.title || currentUser.email}+ memberEmail={currentUser.email}+ projectTitle={draft.projectTitle.trim()}+ source={source}+ noProject={withoutProject}+ teamSize={draft.teamSize}+ invitees={invitees}/>- <h1 className="sr-only">- {t("settings.profile.setup-steps.workspace")}- </h1>-- <div className="w-full flex flex-col gap-y-4">- <FormField title={t("settings.profile.display-name")}>- <Input- data-testid="profile-display-name"- value={name}- autoComplete="off"- onChange={(e) => setName(e.target.value)}- placeholder={t("settings.profile.display-name-placeholder")}- autoFocus- onKeyDown={(e) => {- if (e.key === "Enter" && name.trim()) {- void handleSave();- }- }}- />- </FormField>-- {canRenameWorkspace && (- <FormField title={t("settings.profile.workspace-name")}>- <Input- data-testid="profile-workspace-title"- value={workspaceTitle}- autoComplete="off"- onChange={(event) => setWorkspaceTitle(event.target.value)}- placeholder={t("settings.profile.workspace-name-placeholder")}- />- </FormField>- )}-- {canCreateProject && (- <FormField- title={- <>- {t("settings.profile.setup-first-project")}- {isSaaSMode && (- <span- aria-hidden="true"- className="ml-1 text-error"- data-testid="project-required-indicator"- >- *- </span>- )}- </>- }- >- <Input- data-testid="profile-project-title"- value={projectTitle}- autoComplete="off"- required={isSaaSMode}- onChange={(event) => {- const title = event.target.value;- setProjectTitle(title);- if (!title.trim()) {- setProjectResourceId("");- setIsProjectResourceIdValid(false);- }- }}- placeholder={t("project.create-modal.project-name")}- />- {!!projectTitle.trim() && (- <ResourceIdField- suffix- value={projectResourceId}- autoComplete="off"- resourceName={t("common.project")}- resourceTitle={projectTitle}- validate={validateProjectResourceId}- onChange={setProjectResourceId}- onValidationChange={setIsProjectResourceIdValid}- />- )}- {canPrepareSample && (- <div className="flex items-center gap-x-2 pt-1">- <Checkbox- id="enable-sample-databases"- data-testid="enable-sample-databases"- checked={canEnableSample && enableSampleDatabases}- disabled={!canEnableSample}- onCheckedChange={setEnableSampleDatabases}- />- <label- htmlFor="enable-sample-databases"- className={cn(- "cursor-pointer",- !canEnableSample &&- "cursor-not-allowed text-control-placeholder"- )}- >- {t(- selectedScenarioId === "query-data"- ? "settings.profile.enable-sample-databases-query-data"- : selectedScenarioId === "create-database-change"- ? "settings.profile.enable-sample-databases-create-change"- : selectedScenarioId === "mark-sensitive-data"- ? "settings.profile.enable-sample-databases-mark-sensitive-data"- : "settings.profile.enable-sample-databases"- )}- </label>- </div>- )}- </FormField>- )}-- <div className="mt-2 flex items-center justify-between gap-x-2 border-t border-block-border pt-4">+ </SplashPanel>+ {elsewhere && !finishing ? (+ <div className="mx-auto flex w-full max-w-lg flex-col items-start gap-y-4">+ <h1 className="text-xl font-semibold text-main">+ {elsewhere === "ended"+ ? t("workspace-setup.elsewhere.ended")+ : t("workspace-setup.elsewhere.saved")}+ </h1>+ {elsewhere === "ended" ? (<Button- appearance="secondary"- onClick={() => setSetupStep("scenario")}+ onClick={() =>+ router.replace({ name: PROJECT_V1_ROUTE_DASHBOARD })+ }>- {t("common.back")}+ {t("workspace-setup.elsewhere.workspace")}</Button>- <div className="flex flex-col items-end gap-y-2 sm:flex-row sm:items-center sm:gap-x-2 sm:gap-y-0">- {!isSaaSMode && (- <Button appearance="secondary" onClick={handleSkip}>- {t("settings.profile.setup-skip")}- </Button>- )}- <Button onClick={() => void handleSave()} disabled={!canSave}>- {t("settings.profile.setup-submit")}- </Button>- </div>- </div>+ ) : (+ <Button onClick={continueHere}>+ {t("workspace-setup.elsewhere.continue")}+ </Button>+ )}</div>- </div>- </div>+ ) : (+ renderScreen()+ )}+ </>);}diff --git a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsxdeleted file mode 100644index 6737ca6b33..0000000000--- a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx+++ /dev/null@@ -1,201 +0,0 @@-import { fireEvent } from "@testing-library/react";-import type { ReactElement } from "react";-import { act } from "react";-import { createRoot } from "react-dom/client";-import { beforeEach, describe, expect, test, vi } from "vitest";-import enUS from "@/locales/en-US.json";-import type {- GuideScenarioId,- GuideWorkspaceUsage,-} from "@/modules/workspace-setup-guide/types";-import { WorkspaceSetupQuestionnaireStep } from "./WorkspaceSetupQuestionnaireStep";--(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =- true;--vi.mock("react-i18next", () => ({- initReactI18next: { type: "3rdParty", init: () => undefined },- useTranslation: () => ({- t: (key: string) =>- (- {- "settings.profile.setup-scenario.outcome-title":- "What would you like to do with Bytebase?",- "settings.profile.setup-scenario.create-database-change.title":- "Create a database change",- "settings.profile.setup-scenario.create-database-change.description":- "Define a change and create its issue.",- "settings.profile.setup-scenario.query-data.title": "Query data",- "settings.profile.setup-scenario.query-data.description":- "Open SQL Editor and run a statement.",- "settings.profile.setup-scenario.mark-sensitive-data.title":- "Mark sensitive data",- "settings.profile.setup-scenario.mark-sensitive-data.description":- "Identify sensitive columns and apply masking.",- "settings.profile.setup-scenario.workspace-usage.title":- "Who will use Bytebase with you?",- "settings.profile.setup-scenario.workspace-usage.team.title":- "My team",- "settings.profile.setup-scenario.workspace-usage.team.description":- "I will work with other people.",- "settings.profile.setup-scenario.workspace-usage.solo.title":- "Just me",- "settings.profile.setup-scenario.workspace-usage.solo.description":- "I will use Bytebase on my own.",- "settings.profile.setup-scenario.continue": "Continue",- } as Record<string, string>- )[key] ?? key,- }),-}));--const renderIntoContainer = (element: ReactElement) => {- const container = document.createElement("div");- const root = createRoot(container);- act(() => root.render(element));- return {- container,- unmount: () => act(() => root.unmount()),- };-};--const renderQuestionnaire = (- props: Partial<{- scenarioValue: GuideScenarioId;- workspaceUsageValue: GuideWorkspaceUsage;- required: boolean;- onScenarioChange: (value: GuideScenarioId) => void;- onWorkspaceUsageChange: (value: GuideWorkspaceUsage) => void;- onContinue: () => void;- }> = {}-) =>- renderIntoContainer(- <WorkspaceSetupQuestionnaireStep- scenarioValue={props.scenarioValue}- workspaceUsageValue={props.workspaceUsageValue}- required={props.required}- onScenarioChange={props.onScenarioChange ?? vi.fn()}- onWorkspaceUsageChange={props.onWorkspaceUsageChange ?? vi.fn()}- onContinue={props.onContinue ?? vi.fn()}- />- );--describe("WorkspaceSetupQuestionnaireStep", () => {- beforeEach(() => vi.clearAllMocks());-- test("uses a goal question that names Bytebase", () => {- expect(- enUS.settings.profile["setup-scenario"]["outcome-title"]- ).toBe("What would you like to do with Bytebase?");- });-- test("starts with both questions unanswered and allows Continue", () => {- const page = renderQuestionnaire();- const radios = [...page.container.querySelectorAll("[role='radio']")];- const buttons = [...page.container.querySelectorAll("button")];-- expect(radios).toHaveLength(5);- expect(radios.every((radio) => radio.getAttribute("aria-checked") === "false"))- .toBe(true);- expect(buttons).toHaveLength(1);- expect(buttons[0]).toHaveTextContent("Continue");- expect(buttons[0]).toBeEnabled();- expect(page.container.textContent).not.toContain("Skip");- expect(page.container.querySelector("h1")).toHaveTextContent(- "What would you like to do with Bytebase?"- );- expect(page.container.textContent).toContain("Mark sensitive data");- expect(page.container.textContent).not.toContain(- "Tell us about your setup"- );- expect(page.container.textContent).not.toContain(- "We will tailor your getting-started guide."- );- page.unmount();- });-- test("requires both answers when configured for SaaS", () => {- const unanswered = renderQuestionnaire({ required: true });- const unansweredContinue = unanswered.container.querySelector("button")!;- expect(unansweredContinue).toBeDisabled();- const requiredIndicators = unanswered.container.querySelectorAll(- "[data-testid='required-indicator']"- );- expect(requiredIndicators).toHaveLength(2);- for (const indicator of requiredIndicators) {- expect(indicator).toHaveClass("ml-1");- }- expect(- unanswered.container.querySelectorAll("[aria-required='true']")- ).toHaveLength(2);- unanswered.unmount();-- const partiallyAnswered = renderQuestionnaire({- required: true,- scenarioValue: "query-data",- });- expect(partiallyAnswered.container.querySelector("button")).toBeDisabled();- partiallyAnswered.unmount();-- const answered = renderQuestionnaire({- required: true,- scenarioValue: "query-data",- workspaceUsageValue: "solo",- });- expect(answered.container.querySelector("button")).toBeEnabled();- answered.unmount();- });-- test("does not show required markers when answers are optional", () => {- const page = renderQuestionnaire({ required: false });-- expect(- page.container.querySelectorAll("[data-testid='required-indicator']")- ).toHaveLength(0);- expect(- page.container.querySelectorAll("[aria-required='true']")- ).toHaveLength(0);- page.unmount();- });-- test("reports each answer independently", () => {- const onScenarioChange = vi.fn();- const onWorkspaceUsageChange = vi.fn();- const page = renderQuestionnaire({- onScenarioChange,- onWorkspaceUsageChange,- });- const labels = [...page.container.querySelectorAll("label")];-- act(() =>- fireEvent.click(- labels.find((label) => label.textContent?.includes("Query data"))!- )- );- act(() =>- fireEvent.click(- labels.find((label) => label.textContent?.includes("My team"))!- .querySelector('[role="radio"]')!- )- );-- expect(onScenarioChange).toHaveBeenCalledWith("query-data");- expect(onWorkspaceUsageChange).toHaveBeenCalledWith("team");- page.unmount();- });-- test("continues without requiring either answer", () => {- const onContinue = vi.fn();- const page = renderQuestionnaire({ onContinue });-- act(() =>- fireEvent.click(- [...page.container.querySelectorAll("button")].find((button) =>- button.textContent?.includes("Continue")- )!- )- );-- expect(onContinue).toHaveBeenCalledOnce();- page.unmount();- });-});diff --git a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsxdeleted file mode 100644index ad2fd0ec88..0000000000--- a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx+++ /dev/null@@ -1,178 +0,0 @@-import { useTranslation } from "react-i18next";-import { Button } from "@/components/ui/button";-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";-import { cn } from "@/lib/utils";-import {- isGuideScenarioId,- isGuideWorkspaceUsage,-} from "@/modules/workspace-setup-guide/selection";-import type {- GuideScenarioId,- GuideWorkspaceUsage,-} from "@/modules/workspace-setup-guide/types";--type WorkspaceSetupQuestionnaireStepProps = {- scenarioValue?: GuideScenarioId;- workspaceUsageValue?: GuideWorkspaceUsage;- onScenarioChange: (value: GuideScenarioId) => void;- onWorkspaceUsageChange: (value: GuideWorkspaceUsage) => void;- onContinue: () => void;- required?: boolean;-};--const SCENARIO_OPTIONS: Array<{- id: GuideScenarioId;- titleKey: string;- descriptionKey: string;-}> = [- {- id: "create-database-change",- titleKey: "settings.profile.setup-scenario.create-database-change.title",- descriptionKey:- "settings.profile.setup-scenario.create-database-change.description",- },- {- id: "query-data",- titleKey: "settings.profile.setup-scenario.query-data.title",- descriptionKey: "settings.profile.setup-scenario.query-data.description",- },- {- id: "mark-sensitive-data",- titleKey: "settings.profile.setup-scenario.mark-sensitive-data.title",- descriptionKey:- "settings.profile.setup-scenario.mark-sensitive-data.description",- },-];--const WORKSPACE_USAGE_OPTIONS: Array<{- id: GuideWorkspaceUsage;- titleKey: string;- descriptionKey: string;-}> = [- {- id: "team",- titleKey: "settings.profile.setup-scenario.workspace-usage.team.title",- descriptionKey:- "settings.profile.setup-scenario.workspace-usage.team.description",- },- {- id: "solo",- titleKey: "settings.profile.setup-scenario.workspace-usage.solo.title",- descriptionKey:- "settings.profile.setup-scenario.workspace-usage.solo.description",- },-];--const optionClassName = (selected: boolean) =>- cn(- "items-start rounded-sm border px-4 py-3",- selected- ? "border-accent bg-accent/5"- : "border-control-border hover:bg-control-bg"- );--export function WorkspaceSetupQuestionnaireStep({- scenarioValue,- workspaceUsageValue,- onScenarioChange,- onWorkspaceUsageChange,- onContinue,- required = false,-}: WorkspaceSetupQuestionnaireStepProps) {- const { t } = useTranslation();-- return (- <div className="flex w-full max-w-lg flex-col gap-y-6">- <div className="flex flex-col gap-y-3">- <h1 className="font-medium text-main">- {t("settings.profile.setup-scenario.outcome-title")}- {required && (- <span- aria-hidden="true"- className="ml-1 text-error"- data-testid="required-indicator"- >- *- </span>- )}- </h1>- <RadioGroup- aria-label={t("settings.profile.setup-scenario.outcome-title")}- aria-required={required}- value={scenarioValue ?? ""}- onValueChange={(nextValue) => {- if (isGuideScenarioId(nextValue)) onScenarioChange(nextValue);- }}- className="flex-col items-stretch gap-y-2"- >- {SCENARIO_OPTIONS.map((option) => (- <RadioGroupItem- key={option.id}- value={option.id}- className={optionClassName(scenarioValue === option.id)}- radioClassName="mt-0.5"- contentClassName="min-w-0"- >- <div className="font-medium text-main">{t(option.titleKey)}</div>- <div className="mt-1 text-sm text-control-light">- {t(option.descriptionKey)}- </div>- </RadioGroupItem>- ))}- </RadioGroup>- </div>-- <div className="flex flex-col gap-y-3">- <h2 className="font-medium text-main">- {t("settings.profile.setup-scenario.workspace-usage.title")}- {required && (- <span- aria-hidden="true"- className="ml-1 text-error"- data-testid="required-indicator"- >- *- </span>- )}- </h2>- <RadioGroup- aria-label={t(- "settings.profile.setup-scenario.workspace-usage.title"- )}- aria-required={required}- value={workspaceUsageValue ?? ""}- onValueChange={(nextValue) => {- if (isGuideWorkspaceUsage(nextValue)) {- onWorkspaceUsageChange(nextValue);- }- }}- className="flex-col items-stretch gap-y-2"- >- {WORKSPACE_USAGE_OPTIONS.map((option) => (- <RadioGroupItem- key={option.id}- value={option.id}- className={optionClassName(workspaceUsageValue === option.id)}- radioClassName="mt-0.5"- contentClassName="min-w-0"- >- <div className="font-medium text-main">{t(option.titleKey)}</div>- <div className="mt-1 text-sm text-control-light">- {t(option.descriptionKey)}- </div>- </RadioGroupItem>- ))}- </RadioGroup>- </div>-- <div className="flex items-center justify-end gap-x-2 border-t border-block-border pt-4">- <Button- onClick={onContinue}- disabled={required && (!scenarioValue || !workspaceUsageValue)}- >- {t("settings.profile.setup-scenario.continue")}- </Button>- </div>- </div>- );-}diff --git a/frontend/src/routes/auth/workspace-setup/GoalScreen.tsx b/frontend/src/routes/auth/workspace-setup/GoalScreen.tsxnew file mode 100644index 0000000000..952be4271d--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/GoalScreen.tsx@@ -0,0 +1,108 @@+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { isSetupGoal, type SetupGoal } from "./draft";+import {+ choiceCardClassName,+ SetupNote,+ SetupScreenFrame,+} from "./SetupScreenFrame";++export function GoalScreen({+ goal,+ onGoalChange,+ onBack,+ onContinue,+}: {+ readonly goal: SetupGoal | undefined;+ readonly onGoalChange: (goal: SetupGoal) => void;+ readonly onBack: () => void;+ readonly onContinue: () => void;+}) {+ const { t } = useTranslation();++ return (+ <SetupScreenFrame+ screen="goal"+ title={t("workspace-setup.goal.title")}+ description={t("workspace-setup.goal.description")}+ onSubmit={() => {+ if (goal) onContinue();+ }}+ footer={+ <>+ <Button type="button" appearance="secondary" onClick={onBack}>+ {t("common.back")}+ </Button>+ <Button type="submit" disabled={!goal}>+ {t("workspace-setup.continue")}+ </Button>+ </>+ }+ >+ <div className="flex flex-col gap-y-2">+ <RadioGroup+ aria-label={t("workspace-setup.goal.title")}+ aria-describedby={goal ? undefined : "workspace-setup-goal-note"}+ value={goal ?? ""}+ onValueChange={(value) => {+ if (isSetupGoal(value)) onGoalChange(value);+ }}+ className="flex-col items-stretch gap-y-2"+ >+ <RadioGroupItem+ value="create-database-change"+ className={choiceCardClassName(goal === "create-database-change")}+ radioClassName="mt-0.5"+ contentClassName="min-w-0"+ >+ <div className="font-medium text-main">+ {t("workspace-setup.goal.change.title")}+ </div>+ <div className="mt-1 text-control-light">+ {t("workspace-setup.goal.change.description")}+ </div>+ <div className="mt-2 text-xs text-control-light">+ {t("workspace-setup.goal.change.finish-line")}+ </div>+ </RadioGroupItem>+ <RadioGroupItem+ value="query-data"+ className={choiceCardClassName(goal === "query-data")}+ radioClassName="mt-0.5"+ contentClassName="min-w-0"+ >+ <div className="font-medium text-main">+ {t("workspace-setup.goal.query.title")}+ </div>+ <div className="mt-1 text-control-light">+ {t("workspace-setup.goal.query.description")}+ </div>+ <div className="mt-2 text-xs text-control-light">+ {t("workspace-setup.goal.query.finish-line")}+ </div>+ </RadioGroupItem>+ {/* Drawn without a card so it does not read as a third goal. */}+ <RadioGroupItem+ value="just-exploring"+ className="items-start px-4 py-2"+ radioClassName="mt-0.5"+ contentClassName="min-w-0"+ >+ <div className="text-control">+ {t("workspace-setup.goal.explore.title")}+ </div>+ <div className="mt-1 text-xs text-control-light">+ {t("workspace-setup.goal.explore.description")}+ </div>+ </RadioGroupItem>+ </RadioGroup>+ {!goal && (+ <SetupNote id="workspace-setup-goal-note">+ {t("workspace-setup.goal.required")}+ </SetupNote>+ )}+ </div>+ </SetupScreenFrame>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/InviteEmailsInput.tsx b/frontend/src/routes/auth/workspace-setup/InviteEmailsInput.tsxnew file mode 100644index 0000000000..e7601f6831--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/InviteEmailsInput.tsx@@ -0,0 +1,140 @@+import { X } from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils";+import {+ addInviteAddresses,+ describeInviteAddresses,+ endsAnAddress,+} from "./inviteEmails";++export function InviteEmailsInput({+ id,+ addresses,+ ownerEmail,+ describedBy,+ disabled = false,+ onChange,+}: {+ readonly id: string;+ readonly addresses: readonly string[];+ readonly ownerEmail: string;+ readonly describedBy: string;+ readonly disabled?: boolean;+ readonly onChange: (addresses: string[]) => void;+}) {+ const { t } = useTranslation();+ const [pending, setPending] = useState("");+ const entries = describeInviteAddresses(addresses, ownerEmail);++ const add = (text: string) => {+ onChange(addInviteAddresses(addresses, text));+ setPending("");+ };+ const commit = () => {+ if (pending.trim()) add(pending);+ };++ return (+ <div className="flex min-h-9 w-full min-w-0 flex-wrap items-center gap-1 rounded-xs border border-control-border bg-background px-3 py-1 focus-within:border-accent">+ {entries.map((entry) => {+ const problem =+ entry.problem === "invalid"+ ? t("workspace-setup.team.address-invalid")+ : entry.problem === "own"+ ? t("workspace-setup.team.address-own")+ : undefined;+ return (+ <span+ key={entry.address}+ title={problem}+ className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-xs bg-control-bg px-1.5 py-0.5 text-xs"+ >+ <span+ className={cn(+ "min-w-0 truncate",+ problem && "text-control-light line-through"+ )}+ >+ {entry.address}+ </span>+ {problem && <span className="sr-only">{problem}</span>}+ <Button+ type="button"+ appearance="secondary"+ size="xs"+ className="text-control-placeholder hover:text-control-light"+ aria-label={t("workspace-setup.team.remove-address", {+ email: entry.address,+ })}+ disabled={disabled}+ onClick={() =>+ onChange(+ addresses.filter((address) => address !== entry.address)+ )+ }+ >+ <X className="size-3" />+ </Button>+ </span>+ );+ })}+ <Input+ id={id}+ size="xs"+ type="text"+ inputMode="email"+ autoComplete="off"+ value={pending}+ disabled={disabled}+ aria-describedby={describedBy}+ placeholder={+ addresses.length > 0+ ? t("workspace-setup.team.address-placeholder-more")+ : t("workspace-setup.team.address-placeholder")+ }+ className="min-w-40 flex-1 border-0 bg-transparent"+ onChange={(event) => {+ const value = event.target.value;+ if (endsAnAddress(value)) add(value);+ else setPending(value);+ }}+ // A single-line input drops the line breaks of a pasted column, which+ // would join its addresses, so a pasted list is read from the clipboard.+ onPaste={(event) => {+ const text = event.clipboardData.getData("text");+ if (!endsAnAddress(text.trim())) return;+ event.preventDefault();+ // The list takes the selection's place, and the text typed around it+ // stays a recipient of its own.+ const { selectionStart, selectionEnd } = event.currentTarget;+ add(+ [+ pending.slice(0, selectionStart ?? pending.length),+ text,+ pending.slice(selectionEnd ?? pending.length),+ ].join("\n")+ );+ }}+ onKeyDown={(event) => {+ // While an input method composes text, its keys are its own.+ if (event.nativeEvent.isComposing) return;+ if (event.key === "Enter") {+ // Enter adds the address; it must not submit the wizard.+ event.preventDefault();+ commit();+ } else if (+ event.key === "Backspace" &&+ !pending &&+ addresses.length > 0+ ) {+ onChange(addresses.slice(0, -1));+ }+ }}+ onBlur={commit}+ />+ </div>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/ProjectScreen.tsx b/frontend/src/routes/auth/workspace-setup/ProjectScreen.tsxnew file mode 100644index 0000000000..f4b1e6daf1--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/ProjectScreen.tsx@@ -0,0 +1,252 @@+import { useTranslation } from "react-i18next";+import { ResourceIdField } from "@/components/ResourceIdField";+import { Alert } from "@/components/ui/alert";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ FormError,+ FormField,+ FormFieldGroup,+ FormLabel,+ FormTitle,+} from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { cn } from "@/lib/utils";+import type { ValidatedMessage } from "@/types";+import type { SetupSource } from "./draft";+import {+ choiceCardClassName,+ SetupNote,+ SetupScreenFrame,+} from "./SetupScreenFrame";++// The sample is single-use per workspace, and a server may not offer one.+export type SampleOffer = "offered" | "used" | "unavailable";++export function ProjectScreen({+ projectTitle,+ projectId,+ projectIdValid,+ projectIdRefusal,+ projectExists,+ source,+ sample,+ samplePrepared,+ isSaaS,+ projectOptional,+ skipping,+ skipFailure,+ validateProjectId,+ onProjectTitleChange,+ onProjectIdChange,+ onProjectIdValidChange,+ onSourceChange,+ onBack,+ onContinue,+ onSkip,+}: {+ readonly projectTitle: string;+ readonly projectId: string;+ readonly projectIdValid: boolean;+ readonly projectIdRefusal: string | undefined;+ // A Finish attempt created the project, so its name and ID are fixed here.+ readonly projectExists: boolean;+ readonly source: SetupSource;+ readonly sample: SampleOffer;+ readonly samplePrepared: boolean;+ readonly isSaaS: boolean;+ // Left empty, no project is made, and so no database is offered (D12).+ readonly projectOptional: boolean;+ readonly skipping: boolean;+ readonly skipFailure: { detail?: string } | undefined;+ readonly validateProjectId: (id: string) => Promise<ValidatedMessage[]>;+ readonly onProjectTitleChange: (value: string) => void;+ readonly onProjectIdChange: (value: string) => void;+ readonly onProjectIdValidChange: (valid: boolean) => void;+ readonly onSourceChange: (source: SetupSource) => void;+ readonly onBack: () => void;+ readonly onContinue: () => void;+ // Offered only where setup is optional and nothing has been created yet.+ readonly onSkip: (() => void) | undefined;+}) {+ const { t } = useTranslation();+ const named = !!projectTitle.trim();+ const ready =+ projectExists ||+ (named+ ? !!projectId && projectIdValid && !projectIdRefusal+ : projectOptional);+ const showSample = samplePrepared || sample === "offered";+ const projectLabel = named+ ? projectTitle.trim()+ : t("workspace-setup.project.your-project");+ const databaseTitle = t("workspace-setup.project.database-title", {+ project: projectLabel,+ });++ return (+ <SetupScreenFrame+ screen="project"+ title={t("workspace-setup.project.title")}+ description={t("workspace-setup.project.description")}+ onSubmit={() => {+ if (ready) onContinue();+ }}+ footer={+ <>+ <Button+ type="button"+ appearance="secondary"+ disabled={skipping}+ onClick={onBack}+ >+ {t("common.back")}+ </Button>+ <div className="flex flex-wrap items-center justify-end gap-2">+ {onSkip && (+ <Button+ type="button"+ appearance="secondary"+ disabled={skipping}+ onClick={onSkip}+ >+ {t("workspace-setup.project.skip")}+ </Button>+ )}+ <Button type="submit" disabled={!ready || skipping}>+ {t("workspace-setup.continue")}+ </Button>+ </div>+ </>+ }+ >+ <FormFieldGroup>+ <FormField>+ <FormLabel htmlFor="workspace-setup-project-title">+ {t("workspace-setup.project.name")}+ {projectOptional && (+ <span className="ml-1 font-normal text-control-light">+ {t("workspace-setup.optional")}+ </span>+ )}+ </FormLabel>+ <Input+ id="workspace-setup-project-title"+ value={projectTitle}+ autoComplete="off"+ disabled={projectExists}+ placeholder={t("workspace-setup.project.name-placeholder")}+ aria-describedby={cn(+ "workspace-setup-project-title-hint",+ !named && "workspace-setup-project-title-note"+ )}+ onChange={(event) => onProjectTitleChange(event.target.value)}+ />+ <SetupNote id="workspace-setup-project-title-hint">+ {projectExists+ ? t("workspace-setup.project.exists")+ : t("workspace-setup.project.name-hint")}+ </SetupNote>+ {named ? (+ <ResourceIdField+ suffix+ keepInitialValue+ readonly={projectExists}+ value={projectId}+ autoComplete="off"+ resourceName={t("common.project")}+ resourceTitle={projectTitle}+ validate={validateProjectId}+ onChange={onProjectIdChange}+ onValidationChange={onProjectIdValidChange}+ />+ ) : (+ <SetupNote id="workspace-setup-project-title-note">+ {projectOptional+ ? t("workspace-setup.project.name-optional-note")+ : t("workspace-setup.project.name-required")}+ </SetupNote>+ )}+ {/* The field shows its own reason when its checks fail. */}+ {named && projectIdRefusal && projectIdValid && (+ <FormError>{projectIdRefusal}</FormError>+ )}+ </FormField>+ {(named || !projectOptional) && (+ <FormField>+ <FormTitle>{databaseTitle}</FormTitle>+ <RadioGroup+ aria-label={databaseTitle}+ value={source}+ disabled={samplePrepared}+ onValueChange={(value) => {+ if (value === "sample" || value === "own")+ onSourceChange(value);+ }}+ className="flex-col items-stretch gap-y-2"+ >+ {showSample && (+ <RadioGroupItem+ value="sample"+ className={choiceCardClassName(source === "sample")}+ radioClassName="mt-0.5"+ contentClassName="min-w-0"+ >+ <div className="flex flex-wrap items-center gap-x-2 font-medium text-main">+ {t("workspace-setup.project.sample.title")}+ <Badge variant="secondary">+ {t("workspace-setup.project.sample.recommended")}+ </Badge>+ </div>+ <div className="mt-1 text-control-light">+ {isSaaS+ ? t("workspace-setup.project.sample.description")+ : t(+ "workspace-setup.project.sample.description-self-host"+ )}+ </div>+ </RadioGroupItem>+ )}+ <RadioGroupItem+ value="own"+ className={choiceCardClassName(source === "own")}+ radioClassName="mt-0.5"+ contentClassName="min-w-0"+ >+ <div className="font-medium text-main">+ {t("workspace-setup.project.own.title")}+ </div>+ <div className="mt-1 text-control-light">+ {t("workspace-setup.project.own.description", {+ project: projectLabel,+ })}+ </div>+ </RadioGroupItem>+ </RadioGroup>+ {samplePrepared ? (+ <SetupNote>+ {t("workspace-setup.project.sample.prepared")}+ </SetupNote>+ ) : (+ sample !== "offered" && (+ <SetupNote>+ {sample === "used"+ ? t("workspace-setup.project.sample.used")+ : t("workspace-setup.project.sample.unavailable")}+ </SetupNote>+ )+ )}+ </FormField>+ )}+ </FormFieldGroup>+ {skipFailure && (+ <Alert+ variant="error"+ title={t("workspace-setup.team.failed.names")}+ description={skipFailure.detail}+ />+ )}+ </SetupScreenFrame>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/SetupPanel.tsx b/frontend/src/routes/auth/workspace-setup/SetupPanel.tsxnew file mode 100644index 0000000000..f7f11acc31--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/SetupPanel.tsx@@ -0,0 +1,431 @@+import { Database, Folder } from "lucide-react";+import { type ReactNode, useLayoutEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import exploreImage from "@/assets/illustration/setup-explore.webp";+import heroImage from "@/assets/illustration/setup-hero.webp";+import queryImage from "@/assets/illustration/setup-query.webp";+import logoFull from "@/assets/logo-full.svg";+import { EngineIcon } from "@/components/EngineIcon";+import { UserAvatar } from "@/components/UserAvatar";+import { cn } from "@/lib/utils";+import type { GuideTeamSize } from "@/modules/workspace-setup-guide/types";+import { PresetRoleType } from "@/types/iam/role";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { displayRoleTitle } from "@/utils/role";+import type { SetupGoal, SetupScreen, SetupSource } from "./draft";++// Each still with its pixel size, which holds the picture's place in the+// panel until the file has loaded.+const STILLS = {+ hero: { src: heroImage, width: 1638, height: 1111 },+ query: { src: queryImage, width: 1638, height: 1136 },+ explore: { src: exploreImage, width: 1638, height: 1002 },+} as const;++type Still = keyof typeof STILLS;++const stillFor = (goal: SetupGoal | undefined): Still | undefined => {+ switch (goal) {+ case "create-database-change":+ return "hero";+ case "query-data":+ return "query";+ case "just-exploring":+ return "explore";+ case undefined:+ return undefined;+ }+};++const FRAME = "overflow-hidden rounded-sm border border-block-border";++// Every picture takes 70% of the panel's column, which is half the window,+// never under 512px or over 800px, and never taller than the window.+const pictureWidth = (width: number, height: number) =>+ `min(100%, clamp(32rem, 35vw, 50rem), calc((100dvh - 6rem) * ${width / height}))`;++const CAPTION = "font-mono text-xs uppercase tracking-wider text-control-light";++// A picture drawn at a fixed size and scaled as one, so a wide screen gets the+// same picture larger.+function Drawn({+ width,+ height,+ children,+}: {+ readonly width: number;+ readonly height: number;+ readonly children: ReactNode;+}) {+ const frameRef = useRef<HTMLDivElement>(null);+ const [scale, setScale] = useState(1);+ useLayoutEffect(() => {+ const frame = frameRef.current;+ if (!frame) return;+ const measure = () => setScale(frame.clientWidth / width || 1);+ measure();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(measure);+ observer.observe(frame);+ return () => observer.disconnect();+ }, [width]);++ return (+ <div+ ref={frameRef}+ aria-hidden="true"+ className={cn(FRAME, "relative bg-background")}+ style={{+ width: pictureWidth(width, height),+ aspectRatio: `${width} / ${height}`,+ }}+ >+ <div+ className="absolute top-0 left-0 origin-top-left bg-accent/5"+ style={{ width, height, transform: `scale(${scale})` }}+ >+ {children}+ </div>+ </div>+ );+}++function GhostBar({ width }: { readonly width: string }) {+ return (+ <div className="h-2 rounded-full bg-control-bg-hover" style={{ width }} />+ );+}++// At most this many rows of people, the person setting up included.+const MEMBER_ROWS = 5;++// The workspace as screen 1 names it, with its first member: what the two+// names are for. On screen 4 its member rows hold the team: each address+// listed, then, while the team is bigger, dimmed rows.+function WorkspacePreview({+ workspaceTitle,+ memberName,+ memberEmail,+ team,+}: {+ readonly workspaceTitle: string;+ readonly memberName: string;+ readonly memberEmail: string;+ readonly team?: {+ readonly size: GuideTeamSize | undefined;+ readonly invitees: readonly string[];+ };+}) {+ const { t } = useTranslation();+ const shown = team?.invitees.slice(0, MEMBER_ROWS - 1) ?? [];+ const hidden = (team?.invitees.length ?? 0) - shown.length;+ const ghosts = !team+ ? 2+ : team.size && team.size !== "just-me"+ ? MEMBER_ROWS - 1 - shown.length+ : 0;+ const memberRole = displayRoleTitle(PresetRoleType.WORKSPACE_MEMBER);+ return (+ <Drawn width={512} height={team ? 456 : 360}>+ <div className="h-full p-7">+ <div className="overflow-hidden rounded-sm border border-block-border bg-background">+ <div className="flex h-11 items-center gap-x-2 border-b border-block-border px-3.5 text-sm text-main">+ <img src={logoFull} className="h-4 shrink-0" alt="" />+ <span className="text-control-placeholder">/</span>+ <span className="truncate">{workspaceTitle}</span>+ <UserAvatar+ title={memberName}+ colorSeed={memberEmail}+ size="sm"+ className="ml-auto"+ />+ </div>+ <div className={cn("flex", team ? "h-[352px]" : "h-64")}>+ <div className="flex w-28 shrink-0 flex-col gap-y-3 border-r border-block-border p-3">+ {[70, 55, 80, 60, 75, 50, 65].map((width, index) => (+ <div+ key={index}+ className="h-2 rounded-full bg-control-bg"+ style={{ width: `${width}%` }}+ />+ ))}+ </div>+ <div className="min-w-0 flex-1 p-4">+ <div className="truncate font-medium text-main">+ {workspaceTitle}+ </div>+ <div className="mt-3 divide-y divide-block-border border-t border-block-border">+ <div className="flex items-center gap-x-2 py-2.5 text-sm text-main">+ <UserAvatar+ title={memberName}+ colorSeed={memberEmail}+ size="sm"+ />+ <span className="max-w-[60%] shrink-0 truncate">+ {memberName}+ </span>+ <span className="ml-auto min-w-0 truncate text-xs text-control-light">+ {displayRoleTitle(PresetRoleType.WORKSPACE_ADMIN)}+ </span>+ </div>+ {shown.map((email) => (+ <div+ key={email}+ className="flex items-center gap-x-2 py-2.5 text-sm text-main"+ >+ <UserAvatar title={email} colorSeed={email} size="sm" />+ <span className="min-w-0 truncate">{email}</span>+ <span className="ml-auto shrink-0 text-xs text-control-light">+ {memberRole}+ </span>+ </div>+ ))}+ {Array.from({ length: ghosts }, (_, index) => (+ <div+ key={index}+ className="flex items-center gap-x-2 py-2.5 opacity-40"+ >+ <div className="size-7 shrink-0 rounded-full bg-control-bg-hover" />+ <GhostBar width={`${[24, 18, 22, 16][index]}%`} />+ <span className="ml-auto min-w-0 truncate text-xs text-control-light">+ {memberRole}+ </span>+ </div>+ ))}+ {hidden > 0 && (+ <div className="py-2.5 pl-9 text-xs text-control-light">+ {t("common.n-more", { n: hidden })}+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ </Drawn>+ );+}++function ProjectIcon({ className }: { readonly className?: string }) {+ return (+ <div+ className={cn(+ "flex shrink-0 items-center justify-center rounded-sm bg-accent text-accent-text",+ className+ )}+ >+ <Folder className="size-1/2" />+ </div>+ );+}++function GhostInstance({ left }: { readonly left: number }) {+ return (+ <div+ className="absolute top-[262px] h-[134px] w-[154px] rounded-sm border border-block-border bg-background p-3 opacity-50"+ style={{ left }}+ >+ <div className="flex gap-x-2">+ <div className="size-5 shrink-0 rounded-xs bg-control-bg-hover" />+ <div className="flex flex-1 flex-col gap-y-2 pt-1">+ <GhostBar width="80%" />+ <GhostBar width="45%" />+ </div>+ </div>+ <div className="mt-8 h-8 rounded-xs bg-control-bg-hover" />+ </div>+ );+}++// The workspace holding the project as it is named, and the project's+// instances: the one the database choice brings, then two to come. A project+// left for later is dashed, with no instances.+function ProjectPreview({+ workspaceTitle,+ projectTitle,+ source,+ noProject,+}: {+ readonly workspaceTitle: string;+ readonly projectTitle: string;+ readonly source: SetupSource;+ readonly noProject: boolean;+}) {+ const { t } = useTranslation();+ const own = source === "own";+ return (+ <Drawn width={640} height={452}>+ <div className="absolute inset-6 rounded-sm border border-control-border bg-background/60" />+ <div className="absolute top-10 left-11 max-w-[540px]">+ <div className={CAPTION}>{t("workspace-setup.panel.workspace")}</div>+ <div className="mt-1 truncate text-lg font-semibold text-main">+ {workspaceTitle}+ </div>+ </div>+ <div+ className={cn(+ "absolute top-[108px] left-11 flex h-[76px] w-[296px] items-center gap-x-3 rounded-sm border bg-background px-4",+ noProject+ ? "border-dashed border-control-border text-control-light"+ : "border-block-border text-main"+ )}+ >+ {noProject ? (+ <div className="size-9 shrink-0 rounded-sm bg-control-bg-hover" />+ ) : (+ <ProjectIcon className="size-9" />+ )}+ <div className="min-w-0">+ <div className="truncate text-lg font-semibold">+ {projectTitle || t("workspace-setup.project.your-project")}+ </div>+ <div className={CAPTION}>{t("common.project")}</div>+ </div>+ </div>+ <div className="absolute top-[108px] left-[356px] flex h-[76px] w-[240px] items-center gap-x-3 rounded-sm border border-block-border bg-background px-4 opacity-50">+ <div className="size-9 shrink-0 rounded-sm bg-control-bg-hover" />+ <div className="flex flex-1 flex-col gap-y-2">+ <GhostBar width="70%" />+ <GhostBar width="40%" />+ </div>+ </div>+ {!noProject && (+ <>+ <svg+ className="absolute inset-0 fill-none stroke-control-border"+ viewBox="0 0 640 452"+ >+ <path d="M192 184 V204" />+ <rect+ x="187.5"+ y="204.5"+ width="10"+ height="10"+ rx="2"+ className="fill-background"+ />+ <path d="M192 215 V228 C192 235 188 238 182 238 H159 C153 238 149 241 149 247 V262" />+ <path d="M192 228 C192 235 196 238 202 238 H509 C515 238 519 241 519 247 V262" />+ <path d="M337 238 C343 238 347 241 347 247 V262" />+ </svg>+ <div+ className={cn(+ "absolute top-[262px] left-11 h-[134px] w-[210px] rounded-sm border bg-background p-3",+ own+ ? "border-dashed border-control-border"+ : "border-block-border"+ )}+ >+ <div className="flex gap-x-2">+ {own ? (+ <div className="size-5 shrink-0 rounded-xs bg-control-bg-hover" />+ ) : (+ <EngineIcon engine={Engine.POSTGRES} className="size-5" />+ )}+ <div className="min-w-0">+ <div className="text-sm font-semibold text-main">+ {own+ ? t("workspace-setup.panel.own-instance")+ : t("workspace-setup.panel.sample-instance")}+ </div>+ <div className={cn(CAPTION, "mt-1")}>+ {own+ ? t("workspace-setup.panel.connected-after-setup")+ : t("common.instance")}+ </div>+ </div>+ </div>+ <div+ className={cn(+ "mt-3 flex items-center gap-x-1.5 truncate rounded-xs px-2.5 py-2 font-mono text-xs",+ own+ ? "border border-dashed border-control-border text-control-light"+ : "bg-main text-background"+ )}+ >+ <Database className="size-3.5 shrink-0" />+ {own+ ? t("workspace-setup.panel.own-databases")+ : t("workspace-setup.panel.sample-database")}+ </div>+ </div>+ <GhostInstance left={270} />+ <GhostInstance left={442} />+ </>+ )}+ </Drawn>+ );+}++export function SetupPanel({+ screen,+ goal,+ workspaceTitle,+ memberName,+ memberEmail,+ projectTitle,+ source,+ noProject,+ teamSize,+ invitees,+}: {+ readonly screen: SetupScreen;+ readonly goal: SetupGoal | undefined;+ readonly workspaceTitle: string;+ readonly memberName: string;+ readonly memberEmail: string;+ readonly projectTitle: string;+ readonly source: SetupSource;+ // Self-hosted left the project for later.+ readonly noProject: boolean;+ readonly teamSize: GuideTeamSize | undefined;+ // The addresses Finish would add.+ readonly invitees: readonly string[];+}) {+ if (screen === "project") {+ return (+ <ProjectPreview+ workspaceTitle={workspaceTitle}+ projectTitle={projectTitle}+ source={source}+ noProject={noProject}+ />+ );+ }+ if (screen === "team") {+ return (+ <WorkspacePreview+ workspaceTitle={workspaceTitle}+ memberName={memberName}+ memberEmail={memberEmail}+ team={{ size: teamSize, invitees }}+ />+ );+ }+ // The chosen goal's picture; until a goal is chosen the workspace preview+ // stays.+ const still = screen === "goal" ? stillFor(goal) : undefined;+ if (!still) {+ return (+ <WorkspacePreview+ workspaceTitle={workspaceTitle}+ memberName={memberName}+ memberEmail={memberEmail}+ />+ );+ }+ const { width, height } = STILLS[still];+ return (+ <div+ className={cn(FRAME, "bg-background")}+ style={{ width: pictureWidth(width, height) }}+ >+ <img+ className="block h-auto w-full"+ {...STILLS[still]}+ data-still={still}+ alt=""+ />+ </div>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/SetupScreenFrame.tsx b/frontend/src/routes/auth/workspace-setup/SetupScreenFrame.tsxnew file mode 100644index 0000000000..983f8df524--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/SetupScreenFrame.tsx@@ -0,0 +1,93 @@+import { type ReactNode, useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Separator } from "@/components/ui/separator";+import { StepIndicator } from "@/components/ui/step-indicator";+import { cn } from "@/lib/utils";+import type { SetupScreen } from "./draft";++export function SetupScreenFrame({+ screen,+ title,+ description,+ children,+ footer,+ onSubmit,+}: {+ readonly screen: SetupScreen;+ readonly title: string;+ readonly description: string;+ readonly children: ReactNode;+ readonly footer: ReactNode;+ readonly onSubmit: () => void;+}) {+ const { t } = useTranslation();+ const steps = [+ { key: "workspace", title: t("workspace-setup.steps.workspace") },+ { key: "goal", title: t("workspace-setup.steps.goal") },+ { key: "project", title: t("workspace-setup.steps.project") },+ { key: "team", title: t("workspace-setup.steps.team") },+ ];++ // Each screen is a new form, and the button that led here is gone, so the+ // keyboard would be left on the page body. It goes to the screen's first+ // answer: a text field, or the chosen option of a choice.+ const formRef = useRef<HTMLFormElement>(null);+ useEffect(() => {+ const first = formRef.current?.querySelector<HTMLElement>(+ 'input:not([type="radio"]):not([type="hidden"]):not(:disabled), [role="radio"]'+ );+ const chosen =+ first?.getAttribute("role") === "radio"+ ? first+ .closest('[role="radiogroup"]')+ ?.querySelector<HTMLElement>('[role="radio"][aria-checked="true"]')+ : undefined;+ (chosen ?? first)?.focus();+ }, []);++ return (+ <form+ ref={formRef}+ className="mx-auto flex w-full max-w-lg flex-col gap-y-6"+ noValidate+ onSubmit={(event) => {+ event.preventDefault();+ onSubmit();+ }}+ >+ <StepIndicator steps={steps} currentKey={screen} fitOneRow />+ <div className="flex flex-col gap-y-1">+ <h1 className="text-xl font-semibold text-main">{title}</h1>+ <p className="text-sm text-control-light">{description}</p>+ </div>+ {children}+ <Separator />+ <div className="flex items-center justify-between gap-x-2">{footer}</div>+ </form>+ );+}++// The note under a field or question: a hint, or the reason Continue or Finish+// is disabled, which must sit with what it is about. A control references it+// by `aria-describedby`.+export function SetupNote({+ id,+ children,+}: {+ readonly id?: string;+ readonly children: ReactNode;+}) {+ return (+ <p id={id} className="text-sm text-control-light">+ {children}+ </p>+ );+}++export const choiceCardClassName = (selected: boolean) =>+ cn(+ "items-start rounded-sm border px-4 py-3",+ selected+ ? "border-accent bg-accent/5"+ : "border-control-border hover:bg-control-bg"+ );diff --git a/frontend/src/routes/auth/workspace-setup/TeamScreen.tsx b/frontend/src/routes/auth/workspace-setup/TeamScreen.tsxnew file mode 100644index 0000000000..8c9de6676c--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/TeamScreen.tsx@@ -0,0 +1,235 @@+import { useRef } from "react";+import { useTranslation } from "react-i18next";+import { Alert } from "@/components/ui/alert";+import { Button } from "@/components/ui/button";+import {+ FormField,+ FormFieldGroup,+ FormLabel,+ FormTitle,+} from "@/components/ui/form";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { isGuideTeamSize } from "@/modules/workspace-setup-guide/selection";+import {+ GUIDE_TEAM_SIZES,+ type GuideTeamSize,+} from "@/modules/workspace-setup-guide/types";+import type { SetupSource } from "./draft";+import type { SetupFinishStage } from "./finish";+import { InviteEmailsInput } from "./InviteEmailsInput";+import { describeInviteAddresses, validInviteAddresses } from "./inviteEmails";+import { SetupNote, SetupScreenFrame } from "./SetupScreenFrame";++export type SetupFinishFailure = {+ stage: SetupFinishStage;+ detail?: string;+};++export function TeamScreen({+ teamSize,+ addresses,+ ownerEmail,+ projectTitle,+ source,+ isSaaS,+ finishing,+ failure,+ onTeamSizeChange,+ onAddressesChange,+ onBack,+ onFinish,+ onFinishWithoutSample,+}: {+ readonly teamSize: GuideTeamSize | undefined;+ readonly addresses: readonly string[];+ readonly ownerEmail: string;+ readonly projectTitle: string;+ readonly source: SetupSource;+ // An invitation is an email, and only Cloud can send one at first run.+ // Self-hosted lists no one: a member added there would have no password.+ readonly isSaaS: boolean;+ readonly finishing: boolean;+ readonly failure: SetupFinishFailure | undefined;+ readonly onTeamSizeChange: (size: GuideTeamSize) => void;+ readonly onAddressesChange: (addresses: string[]) => void;+ readonly onBack: () => void;+ readonly onFinish: () => void;+ readonly onFinishWithoutSample: () => void;+}) {+ const { t } = useTranslation();+ // The list as it was when the button was pressed. Text left in the field is+ // entered as the press takes the focus; a press that makes it an entry that+ // is not an address stops there, so that entry is seen before Finish runs.+ const listAtPress = useRef<readonly string[] | undefined>(undefined);+ const pressed = () => {+ listAtPress.current = addresses;+ };+ const enteredNonAddress = () => {+ const before = listAtPress.current;+ listAtPress.current = undefined;+ return describeInviteAddresses(+ addresses.filter((address) => before && !before.includes(address)),+ ownerEmail+ ).some(({ problem }) => problem === "invalid");+ };+ const invites = isSaaS && !!teamSize && teamSize !== "just-me";+ const inviteeCount = invites+ ? validInviteAddresses(addresses, ownerEmail).length+ : 0;++ const sizeLabel = (size: GuideTeamSize) => {+ switch (size) {+ case "just-me":+ return t("workspace-setup.team.sizes.just-me");+ case "2-10":+ return t("workspace-setup.team.sizes.2-10");+ case "11-50":+ return t("workspace-setup.team.sizes.11-50");+ case "51-200":+ return t("workspace-setup.team.sizes.51-200");+ case "200+":+ return t("workspace-setup.team.sizes.200-plus");+ }+ };+ const failureTitle = (stage: SetupFinishStage) => {+ switch (stage) {+ case "names":+ return t("workspace-setup.team.failed.names");+ case "project":+ return t("workspace-setup.team.failed.project", {+ project: projectTitle,+ });+ case "sample":+ return t("workspace-setup.team.failed.sample");+ case "invitees":+ return t("workspace-setup.team.failed.invitees");+ }+ };+ const finishLabel = finishing+ ? t("workspace-setup.team.finishing")+ : failure+ ? t("workspace-setup.team.try-again")+ : inviteeCount === 0+ ? t("workspace-setup.team.finish")+ : t("workspace-setup.team.finish-invite", { count: inviteeCount });++ return (+ <SetupScreenFrame+ screen="team"+ title={t("workspace-setup.team.title")}+ description={t("workspace-setup.team.description")}+ onSubmit={() => {+ if (enteredNonAddress()) return;+ if (teamSize && !finishing) onFinish();+ }}+ footer={+ <>+ <Button+ type="button"+ appearance="secondary"+ disabled={finishing}+ onClick={onBack}+ >+ {t("common.back")}+ </Button>+ <div className="flex flex-wrap items-center justify-end gap-2">+ {failure?.stage === "sample" && (+ <Button+ type="button"+ appearance="secondary"+ onPointerDown={pressed}+ onClick={() => {+ if (!enteredNonAddress()) onFinishWithoutSample();+ }}+ >+ {t("workspace-setup.team.finish-without-sample")}+ </Button>+ )}+ <Button+ type="submit"+ disabled={!teamSize || finishing}+ onPointerDown={pressed}+ >+ {finishLabel}+ </Button>+ </div>+ </>+ }+ >+ <FormFieldGroup>+ <FormField>+ <FormTitle>{t("workspace-setup.team.size")}</FormTitle>+ <RadioGroup+ aria-label={t("workspace-setup.team.size")}+ aria-describedby={+ teamSize ? undefined : "workspace-setup-team-size-note"+ }+ value={teamSize ?? ""}+ disabled={finishing}+ onValueChange={(value) => {+ if (isGuideTeamSize(value)) onTeamSizeChange(value);+ }}+ className="flex-wrap gap-y-2"+ >+ {GUIDE_TEAM_SIZES.map((size) => (+ <RadioGroupItem key={size} value={size}>+ {sizeLabel(size)}+ </RadioGroupItem>+ ))}+ </RadioGroup>+ {!teamSize && (+ <SetupNote id="workspace-setup-team-size-note">+ {t("workspace-setup.team.size-required")}+ </SetupNote>+ )}+ </FormField>+ {invites && (+ <FormField>+ <FormLabel htmlFor="workspace-setup-invitees">+ {t("workspace-setup.team.invite-teammates")}+ <span className="ml-1 font-normal text-control-light">+ {t("workspace-setup.optional")}+ </span>+ </FormLabel>+ <InviteEmailsInput+ id="workspace-setup-invitees"+ addresses={addresses}+ ownerEmail={ownerEmail}+ describedBy="workspace-setup-invitees-note"+ disabled={finishing}+ onChange={onAddressesChange}+ />+ <SetupNote id="workspace-setup-invitees-note">+ {[+ t("workspace-setup.team.members-enter"),+ t("workspace-setup.team.members-role", {+ project: projectTitle,+ }),+ source === "own" && t("workspace-setup.team.members-own"),+ t("workspace-setup.team.members-roles-later"),+ ]+ .filter(Boolean)+ .join(" ")}+ </SetupNote>+ </FormField>+ )}+ </FormFieldGroup>+ {failure && (+ <Alert+ variant="error"+ title={failureTitle(failure.stage)}+ description={failure.detail}+ />+ )}+ {finishing && (+ <p role="status" className="text-sm text-control-light">+ {source === "sample"+ ? t("workspace-setup.team.progress-sample", {+ project: projectTitle,+ })+ : t("workspace-setup.team.progress", { project: projectTitle })}+ </p>+ )}+ </SetupScreenFrame>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/WorkspaceScreen.tsx b/frontend/src/routes/auth/workspace-setup/WorkspaceScreen.tsxnew file mode 100644index 0000000000..7cbeacaf12--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/WorkspaceScreen.tsx@@ -0,0 +1,84 @@+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { FormField, FormFieldGroup, FormLabel } from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import { SetupNote, SetupScreenFrame } from "./SetupScreenFrame";++export function WorkspaceScreen({+ name,+ workspaceTitle,+ showWorkspaceTitle,+ onNameChange,+ onWorkspaceTitleChange,+ onContinue,+}: {+ readonly name: string;+ readonly workspaceTitle: string;+ readonly showWorkspaceTitle: boolean;+ readonly onNameChange: (value: string) => void;+ readonly onWorkspaceTitleChange: (value: string) => void;+ readonly onContinue: () => void;+}) {+ const { t } = useTranslation();+ const missingWorkspaceTitle = showWorkspaceTitle && !workspaceTitle.trim();++ return (+ <SetupScreenFrame+ screen="workspace"+ title={t("workspace-setup.workspace.title")}+ description={t("workspace-setup.workspace.description")}+ onSubmit={() => {+ if (!missingWorkspaceTitle) onContinue();+ }}+ footer={+ <Button+ type="submit"+ className="ml-auto"+ disabled={missingWorkspaceTitle}+ >+ {t("workspace-setup.continue")}+ </Button>+ }+ >+ <FormFieldGroup>+ <FormField>+ <FormLabel htmlFor="workspace-setup-name">+ {t("settings.profile.display-name")}+ <span className="ml-1 font-normal text-control-light">+ {t("workspace-setup.optional")}+ </span>+ </FormLabel>+ <Input+ id="workspace-setup-name"+ value={name}+ autoComplete="off"+ placeholder={t("workspace-setup.workspace.name-placeholder")}+ onChange={(event) => onNameChange(event.target.value)}+ />+ </FormField>+ {showWorkspaceTitle && (+ <FormField>+ <FormLabel htmlFor="workspace-setup-workspace-title">+ {t("workspace-setup.workspace.workspace-name")}+ </FormLabel>+ <Input+ id="workspace-setup-workspace-title"+ value={workspaceTitle}+ autoComplete="off"+ placeholder={t(+ "workspace-setup.workspace.workspace-name-placeholder"+ )}+ aria-describedby="workspace-setup-workspace-title-note"+ onChange={(event) => onWorkspaceTitleChange(event.target.value)}+ />+ <SetupNote id="workspace-setup-workspace-title-note">+ {missingWorkspaceTitle+ ? t("workspace-setup.workspace.workspace-name-required")+ : t("workspace-setup.workspace.workspace-name-hint")}+ </SetupNote>+ </FormField>+ )}+ </FormFieldGroup>+ </SetupScreenFrame>+ );+}diff --git a/frontend/src/routes/auth/workspace-setup/draft.ts b/frontend/src/routes/auth/workspace-setup/draft.tsnew file mode 100644index 0000000000..3f33e7bfcb--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/draft.ts@@ -0,0 +1,155 @@+import { isGuideScenarioId } from "@/modules/workspace-setup-guide/scenarios";+import {+ isGuideTeamSize,+ saveSetupAnswer,+ setupStorageKey,+} from "@/modules/workspace-setup-guide/selection";+import type {+ GuideScenarioId,+ GuideTeamSize,+} from "@/modules/workspace-setup-guide/types";+import { readJson } from "@/stores/app/utils";+import { storageKeyWorkspaceSetupDraft } from "@/utils/storage-keys";+import type { ProjectGrants, ProjectIdRefusal } from "./finish";++const SETUP_SCREENS = ["workspace", "goal", "project", "team"] as const;++export type SetupScreen = (typeof SETUP_SCREENS)[number];++export type SetupGoal = Exclude<GuideScenarioId, "mark-sensitive-data">;++export type SetupSource = "sample" | "own";++export type SetupDraft = {+ screen: SetupScreen;+ // Undefined until edited, so an untouched field keeps showing its prefill.+ name?: string;+ workspaceTitle?: string;+ goal?: SetupGoal;+ projectTitle: string;+ projectId: string;+ source: SetupSource;+ teamSize?: GuideTeamSize;+ emails: string[];+ // The ID a Finish attempt has sent a create for. Until `createdProject` is+ // set, that create's outcome is unknown; a refusal, or a project found+ // holding the ID, settles it.+ attemptedProjectId?: string;+ // The ID the server refused at Finish, which blocks until the ID changes.+ refusedProjectId?: ProjectIdRefusal & { id: string };+ // What a Finish attempt has already made on the server; from then on the+ // project's name, ID and prepared sample are fixed.+ createdProject?: string;+ samplePrepared?: boolean;+ projectGrants?: ProjectGrants;+};++const emptySetupDraft = (): SetupDraft => ({+ screen: "workspace",+ projectTitle: "",+ projectId: "",+ source: "sample",+ emails: [],+});++export const isSetupGoal = (value: unknown): value is SetupGoal =>+ isGuideScenarioId(value) && value !== "mark-sensitive-data";++// Kept as the guide's stored answers are. It holds no credentials, because the+// wizard collects none.+const draftStorageKey = () => setupStorageKey(storageKeyWorkspaceSetupDraft);++const optionalString = (value: unknown) =>+ typeof value === "string" ? value : undefined;++const strings = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];++const grants = (value: unknown): ProjectGrants =>+ value && typeof value === "object"+ ? Object.fromEntries(+ Object.entries(value).map(([role, members]) => [role, strings(members)])+ )+ : {};++const refusedId = (value: unknown): SetupDraft["refusedProjectId"] => {+ if (!value || typeof value !== "object") return undefined;+ const { id, reason } = value as Record<string, unknown>;+ return typeof id === "string"+ ? { id, reason: optionalString(reason) }+ : undefined;+};++// Self-hosted may leave the project for later while no create has been sent,+// as with the skip (D12).+export const projectOptional = (draft: SetupDraft, isSaaS: boolean) =>+ !isSaaS && !draft.createdProject && !draft.attemptedProjectId;++// Storage is outside the type system, so every field is read defensively and+// the screen falls back to the first one whose answer is missing.+export const readSetupDraft = (isSaaS: boolean): SetupDraft => {+ const key = draftStorageKey();+ if (!key) return emptySetupDraft();+ const stored = readJson<Record<string, unknown> | undefined>(key, undefined);+ if (!stored || typeof stored !== "object") return emptySetupDraft();++ const draft: SetupDraft = {+ ...emptySetupDraft(),+ name: optionalString(stored.name),+ workspaceTitle: optionalString(stored.workspaceTitle),+ goal: isSetupGoal(stored.goal) ? stored.goal : undefined,+ projectTitle: optionalString(stored.projectTitle) ?? "",+ projectId: optionalString(stored.projectId) ?? "",+ source: stored.source === "own" ? "own" : "sample",+ teamSize: isGuideTeamSize(stored.teamSize) ? stored.teamSize : undefined,+ emails: strings(stored.emails),+ attemptedProjectId: optionalString(stored.attemptedProjectId),+ refusedProjectId: refusedId(stored.refusedProjectId),+ createdProject: optionalString(stored.createdProject),+ samplePrepared: stored.samplePrepared === true,+ projectGrants: grants(stored.projectGrants),+ };+ const projectAnswered = draft.projectTitle.trim()+ ? !!draft.projectId+ : projectOptional(draft, isSaaS);+ const reachable: SetupScreen = !draft.goal+ ? "goal"+ : !projectAnswered+ ? "project"+ : "team";+ const storedScreen = SETUP_SCREENS.find((screen) => screen === stored.screen);+ draft.screen =+ storedScreen &&+ SETUP_SCREENS.indexOf(storedScreen) <= SETUP_SCREENS.indexOf(reachable)+ ? storedScreen+ : reachable;+ return draft;+};++// Each save is stored with a revision of its own, so it changes what is stored+// even when no answer changed, and the other tabs hear of it.+export const saveSetupDraft = (draft: SetupDraft) =>+ saveSetupAnswer(storageKeyWorkspaceSetupDraft, {+ ...draft,+ revision: crypto.getRandomValues(new Uint32Array(2)).join("-"),+ });++// Calls `onChange` when another tab saves the draft, or removes it because+// setup ended there.+export const watchSetupDraft = (onChange: (ended: boolean) => void) => {+ const listener = (event: StorageEvent) => {+ if (event.key === draftStorageKey()) onChange(event.newValue === null);+ };+ window.addEventListener("storage", listener);+ return () => window.removeEventListener("storage", listener);+};++export const clearSetupDraft = () => {+ const key = draftStorageKey();+ if (!key) return;+ try {+ localStorage.removeItem(key);+ } catch {+ // Nothing to remove from storage that cannot be reached.+ }+};diff --git a/frontend/src/routes/auth/workspace-setup/finish.ts b/frontend/src/routes/auth/workspace-setup/finish.tsnew file mode 100644index 0000000000..35767ff4c4--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/finish.ts@@ -0,0 +1,408 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import { Code, ConnectError } from "@connectrpc/connect";+import { projectServiceClientConnect } from "@/api";+import { createBehaviorMetric } from "@/app/analytics/behavior";+import { behaviorAnalytics } from "@/app/analytics/provider";+import { useAppStore } from "@/stores/app";+import { callOptions, isConnectAlreadyExists } from "@/stores/app/utils";+import { projectNamePrefix } from "@/stores/modules/v1/common";+import { PresetRoleType } from "@/types/iam/role";+import {+ type Binding,+ BindingSchema,+ GetIamPolicyRequestSchema,+ type IamPolicy,+} from "@/types/proto-es/v1/iam_policy_pb";+import {+ GetProjectRequestSchema,+ type Project,+} from "@/types/proto-es/v1/project_service_pb";+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";+import { WorkspaceSchema } from "@/types/proto-es/v1/workspace_service_pb";+import { getUserEmailInBinding } from "@/types/v1/user";++export type SetupFinishStage = "names" | "project" | "sample" | "invitees";++// Why the server will not create a project with the chosen ID: its reason, or+// none when another project holds the ID. Only screen 3 can change the ID, so+// a refusal sends the wizard back there.+export type ProjectIdRefusal = { reason?: string };++// For each invitee role, the members it holds because a Finish attempt added+// them.+export type ProjectGrants = Readonly<Record<string, readonly string[]>>;++// What the server holds for a project ID whose create got no answer.+type LostCreate =+ | { kind: "own"; project: string }+ // No such project in this workspace.+ | { kind: "absent" }+ | { kind: "other" };++export type SetupNames = {+ userName: string;+ displayName: string;+ // Set only when this account may name the workspace.+ workspaceName?: string;+ workspaceTitle: string;+};++// True once this tab no longer holds setup (D11). No write is sent after that.+type Superseded = () => boolean;++type SetupFinishInput = SetupNames & {+ ownerEmail: string;+ // Self-hosted may leave the project for later (D12): nothing past the names+ // is written then.+ withoutProject: boolean;+ projectTitle: string;+ projectId: string;+ // The project an earlier attempt created.+ createdProject?: string;+ // An earlier attempt from this draft already sent a create for `projectId`.+ // Only then can a project that holds the ID be the one this draft made.+ createAttempted: boolean;+ prepareSample: boolean;+ invitees: readonly string[];+ projectGrants: ProjectGrants;+ superseded: Superseded;+};++type SetupFinishResult =+ | { ok: true; project: string | undefined }+ | {+ ok: false;+ stage: SetupFinishStage;+ error: unknown;+ refusal?: ProjectIdRefusal;+ }+ // The attempt stopped because this tab no longer holds setup.+ | { ok: false; superseded: true };++const SUPERSEDED = { ok: false, superseded: true } as const;++// The wizard shows each failure beside what failed, so the global error toast+// would report it a second time.+const REPORT = { byCaller: true };++// Together these let an invitee propose changes and run read-only queries.+const INVITEE_PROJECT_ROLES: string[] = [+ PresetRoleType.PROJECT_DEVELOPER,+ PresetRoleType.SQL_EDITOR_READ_USER,+];++// Screen 1's two names. The name is optional, and an empty one is not saved+// over the account's.+export const saveSetupNames = async (+ names: SetupNames,+ superseded: Superseded+) => {+ const store = useAppStore.getState();+ if (names.displayName) {+ await store.updateUser(+ create(UpdateUserRequestSchema, {+ user: { name: names.userName, title: names.displayName },+ updateMask: create(FieldMaskSchema, { paths: ["title"] }),+ }),+ REPORT+ );+ }+ if (names.workspaceName && !superseded()) {+ await store.updateWorkspace(+ create(WorkspaceSchema, {+ name: names.workspaceName,+ title: names.workspaceTitle,+ }),+ ["title"],+ REPORT+ );+ }+};++// Looks up what the server holds now for an ID whose create got no answer.+// The project is the draft's own only when it carries the draft's name and its+// access is still what the server gives a new project: its creator as owner,+// and nobody else. A project anyone else has been given access to is never+// taken over. Rejects when the server cannot be read.+export const findLostCreate = async (+ projectId: string,+ projectTitle: string,+ ownerEmail: string+): Promise<LostCreate> => {+ const name = `${projectNamePrefix}${projectId}`;+ let existing: Project;+ try {+ existing = await projectServiceClientConnect.getProject(+ create(GetProjectRequestSchema, { name }),+ callOptions(REPORT)+ );+ } catch (error) {+ if (error instanceof ConnectError && error.code === Code.NotFound) {+ return { kind: "absent" };+ }+ throw error;+ }+ if (existing.title !== projectTitle) return { kind: "other" };+ const { bindings } = await projectServiceClientConnect.getIamPolicy(+ create(GetIamPolicyRequestSchema, { resource: name }),+ callOptions(REPORT)+ );+ const untouched =+ bindings.length === 1 &&+ bindings[0].role === PresetRoleType.PROJECT_OWNER &&+ bindings[0].members.length === 1 &&+ bindings[0].members[0] === getUserEmailInBinding(ownerEmail);+ return untouched+ ? { kind: "own", project: existing.name }+ : { kind: "other" };+};++// Returns the project's resource name, or why it cannot be created.+const createOrAdoptProject = async (+ input: SetupFinishInput+): Promise<string | { error: unknown; refusal?: ProjectIdRefusal }> => {+ const store = useAppStore.getState();+ try {+ const created = await store.createProject(+ input.projectTitle,+ input.projectId,+ REPORT+ );+ return created.name;+ } catch (error) {+ if (error instanceof ConnectError && error.code === Code.InvalidArgument) {+ return { error, refusal: { reason: error.rawMessage } };+ }+ if (!isConnectAlreadyExists(error)) return { error };+ if (!input.createAttempted) return { error, refusal: {} };+ // The earlier attempt may have created the project although its answer+ // never arrived. An ID that exists and is not in this workspace is held+ // by another one: IDs are shared by all.+ try {+ const found = await findLostCreate(+ input.projectId,+ input.projectTitle,+ input.ownerEmail+ );+ return found.kind === "own" ? found.project : { error, refusal: {} };+ } catch (readError) {+ return { error: readError };+ }+ }+};++// Failures that may come after the server applied the write: the request was+// cut off, or the server failed while answering. Any other answer is the+// server's refusal, and a refused write changed nothing.+const MAY_HAVE_APPLIED = new Set([+ Code.Canceled,+ Code.Unknown,+ Code.DeadlineExceeded,+ Code.Unavailable,+ Code.Internal,+ Code.DataLoss,+]);+const refused = (error: unknown) =>+ error instanceof ConnectError && !MAY_HAVE_APPLIED.has(error.code);++// Gives the invitee roles to `invitees` and takes away the ones in `earlier`+// whose address is no longer listed: the wizard undoes only what it added, so+// a role someone else gave keeps its members. The write replaces every+// binding, the owner's included, so `policy` must be the one the server holds+// now, with its etag: the store's copy would miss the write of an earlier+// attempt whose answer was lost. It is sent even when it changes nothing, as+// such a write may still be on its way: of two writes built on the same etag,+// the server refuses whichever lands second.+const writeProjectInvitees = async (+ project: string,+ policy: IamPolicy,+ invitees: readonly string[],+ earlier: ProjectGrants,+ record: (grants: Record<string, string[]>) => void+) => {+ // The wizard's grants carry no condition; a conditional one is someone+ // else's and stays as it is.+ const isInviteeBinding = (binding: Binding, role: string) =>+ binding.role === role && !binding.condition?.expression;+ const listed = invitees.map(getUserEmailInBinding);+ const roles = INVITEE_PROJECT_ROLES.map((role) => {+ const current = policy.bindings+ .filter((binding) => isInviteeBinding(binding, role))+ .flatMap((binding) => binding.members);+ const mine = earlier[role] ?? [];+ // In the server's order, so a write that changes no member reorders none.+ const members = [+ ...new Set([+ ...current.filter(+ (member) => !mine.includes(member) || listed.includes(member)+ ),+ ...listed,+ ]),+ ];+ // The wizard's after this write: what it added before and still lists,+ // and what it adds now. A member who held the role already is not.+ const added = listed.filter(+ (member) => mine.includes(member) || !current.includes(member)+ );+ return { role, members, mine, added };+ });+ // Kept with the earlier additions until the write is known to have taken+ // them back: its answer may never arrive.+ record(+ Object.fromEntries(+ roles.map(({ role, mine, added }) => [+ role,+ [...new Set([...mine, ...added])],+ ])+ )+ );+ try {+ await useAppStore.getState().updateProjectIamPolicy(+ project,+ {+ ...policy,+ bindings: [+ ...policy.bindings.filter(+ (binding) =>+ !INVITEE_PROJECT_ROLES.some((role) =>+ isInviteeBinding(binding, role)+ )+ ),+ ...roles+ .filter(({ members }) => members.length > 0)+ .map(({ role, members }) =>+ create(BindingSchema, { role, members })+ ),+ ],+ },+ REPORT+ );+ } catch (error) {+ if (refused(error)) {+ record(+ Object.fromEntries(roles.map(({ role, mine }) => [role, [...mine]]))+ );+ }+ throw error;+ }+ record(Object.fromEntries(roles.map(({ role, added }) => [role, added])));+};++// Adds Workspace Member to each invitee. The store's patch replaces a member's+// whole role set, so a role the address already holds is sent along with it,+// taken from the policy the store has just fetched from the server, for the+// same reason as the project's.+const addWorkspaceMembers = (invitees: readonly string[]) => {+ const store = useAppStore.getState();+ return store.patchWorkspaceIamPolicy(+ invitees.map((email) => {+ const member = getUserEmailInBinding(email);+ return {+ member,+ roles: [+ ...new Set([+ ...store.findWorkspaceRolesByMember(member),+ PresetRoleType.WORKSPACE_MEMBER,+ ]),+ ],+ };+ }),+ REPORT+ );+};++type SetupFinishEvents = {+ // Called before the create is sent: its answer may never arrive.+ projectCreateSent: () => void;+ projectCreated: (project: string) => void;+ samplePrepared: () => void;+ // The project's roles the wizard has given, as they stand.+ projectGrants: (grants: Record<string, string[]>) => void;+};++const commitSetup = async (+ input: SetupFinishInput,+ on: SetupFinishEvents+): Promise<SetupFinishResult> => {+ const store = useAppStore.getState();++ try {+ await saveSetupNames(input, input.superseded);+ } catch (error) {+ return { ok: false, stage: "names", error };+ }+ if (input.withoutProject) return { ok: true, project: undefined };++ let project = input.createdProject;+ if (!project) {+ if (input.superseded()) return SUPERSEDED;+ on.projectCreateSent();+ const created = await createOrAdoptProject(input);+ if (typeof created !== "string") {+ return { ok: false, stage: "project", ...created };+ }+ project = created;+ on.projectCreated(project);+ }++ if (input.prepareSample) {+ if (input.superseded()) return SUPERSEDED;+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("sample instance requested", {+ properties: { source: "workspace_setup" },+ })+ );+ try {+ await store.prepareSampleProjectInstance(project);+ } catch (error) {+ return { ok: false, stage: "sample", error };+ }+ on.samplePrepared();+ }++ try {+ const earlier = input.projectGrants;+ if (+ input.invitees.length > 0 ||+ Object.values(earlier).some((members) => members.length > 0)+ ) {+ const policy = await projectServiceClientConnect.getIamPolicy(+ create(GetIamPolicyRequestSchema, { resource: project }),+ callOptions(REPORT)+ );+ if (input.superseded()) return SUPERSEDED;+ await writeProjectInvitees(+ project,+ policy,+ input.invitees,+ earlier,+ on.projectGrants+ );+ }+ // Last, because this write is what sends the invitations: nobody is+ // invited to a project they cannot open yet.+ if (input.invitees.length > 0) {+ await store.fetchWorkspaceIamPolicy(false, REPORT);+ if (input.superseded()) return SUPERSEDED;+ await addWorkspaceMembers(input.invitees);+ }+ } catch (error) {+ return { ok: false, stage: "invitees", error };+ }++ return { ok: true, project };+};++// The wizard's one commit. Creating the project is the only step that cannot+// be repeated, so a retry passes `createdProject`; the others are computed+// from the current answers and from what the server holds.+export const runSetupFinish = async (+ input: SetupFinishInput,+ on: SetupFinishEvents+): Promise<SetupFinishResult> => {+ const result = await commitSetup(input, on);+ // Losing setup while the last request was out leaves its outcome, a failure+ // too, to whoever holds setup next.+ return input.superseded() ? SUPERSEDED : result;+};diff --git a/frontend/src/routes/auth/workspace-setup/inviteEmails.ts b/frontend/src/routes/auth/workspace-setup/inviteEmails.tsnew file mode 100644index 0000000000..ede97a2ff3--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/inviteEmails.ts@@ -0,0 +1,74 @@+type InviteEntry = {+ address: string;+ // Why the entry is shown but not sent.+ problem?: "invalid" | "own";+};++// The server's pattern for an account's email, which is lowercase, with one+// addition: the domain has a dot, as an invitee's address always does.+const EMAIL =+ /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;++const sameAddress = (a: string, b: string) =>+ a.toLowerCase() === b.toLowerCase();++// Separators between addresses, the full-width ones an input method types+// included.+const SEPARATORS = /[,;\n,;、]+/;++// True once `text` holds a character that ends the address before it.+export const endsAnAddress = (text: string) =>+ /\s/.test(text) || SEPARATORS.test(text);++// What a mail client or a sentence wraps an address in.+const unwrap = (token: string) =>+ token+ .trim()+ .replace(/^mailto:/i, "")+ .replace(/^[<("'[]+/, "")+ .replace(/[>)"'\].]+$/, "");++// Adds what was typed or pasted, one entry per address, dropping repeats. A+// recipient copied as `Ann Lee <[email protected]>` is its bracketed address;+// the name beside it is not an entry.+export const addInviteAddresses = (+ existing: readonly string[],+ text: string+): string[] => {+ const next = [...existing];+ for (const recipient of text.split(SEPARATORS)) {+ const bracketed = [...recipient.matchAll(/<([^<>]+)>/g)].map(+ (match) => match[1] ?? ""+ );+ const tokens = bracketed.length > 0 ? bracketed : recipient.split(/\s+/);+ for (const token of tokens) {+ const address = unwrap(token);+ if (address && !next.some((entry) => sameAddress(entry, address))) {+ next.push(address);+ }+ }+ }+ return next;+};++export const describeInviteAddresses = (+ addresses: readonly string[],+ ownerEmail: string+): InviteEntry[] =>+ addresses.map((address) => ({+ address,+ problem: !EMAIL.test(address.toLowerCase())+ ? "invalid"+ : sameAddress(address, ownerEmail)+ ? "own"+ : undefined,+ }));++// The addresses Finish writes, in the lowercase form the server keeps.+export const validInviteAddresses = (+ addresses: readonly string[],+ ownerEmail: string+): string[] =>+ describeInviteAddresses(addresses, ownerEmail)+ .filter((entry) => !entry.problem)+ .map((entry) => entry.address.toLowerCase());diff --git a/frontend/src/routes/auth/workspace-setup/prefill.ts b/frontend/src/routes/auth/workspace-setup/prefill.tsnew file mode 100644index 0000000000..e8c85aab01--- /dev/null+++ b/frontend/src/routes/auth/workspace-setup/prefill.ts@@ -0,0 +1,164 @@+// Local parts that name a mailbox rather than a person.+const SHARED_MAILBOXES = new Set([+ "accounts",+ "admin",+ "administrator",+ "billing",+ "contact",+ "data",+ "dba",+ "dev",+ "devops",+ "engineering",+ "finance",+ "hello",+ "help",+ "hr",+ "info",+ "it",+ "mail",+ "marketing",+ "noreply",+ "office",+ "ops",+ "postmaster",+ "root",+ "sales",+ "security",+ "service",+ "support",+ "team",+ "tech",+ "test",+ "webmaster",+]);++// Mail providers, by the name part of their domains, which says nothing about+// the account's company. Matching the name covers their country domains too+// (yahoo.co.jp, hotmail.co.uk, outlook.fr).+const PUBLIC_MAIL_PROVIDERS = new Set([+ "126",+ "139",+ "163",+ "aliyun",+ "aol",+ "att",+ "btinternet",+ "comcast",+ "daum",+ "duck",+ "fastmail",+ "foxmail",+ "free",+ "gmail",+ "gmx",+ "googlemail",+ "hanmail",+ "hey",+ "hotmail",+ "icloud",+ "laposte",+ "libero",+ "live",+ "mac",+ "mail",+ "me",+ "msn",+ "naver",+ "orange",+ "outlook",+ "pm",+ "proton",+ "protonmail",+ "qq",+ "rediffmail",+ "seznam",+ "sina",+ "sohu",+ "t-online",+ "tuta",+ "tutanota",+ "verizon",+ "web",+ "yahoo",+ "yandex",+ "ymail",+ "zoho",+]);++// Labels that sit between a company and its country code, as in "acme.co.uk".+const SECOND_LEVEL_LABELS = new Set([+ "ac",+ "co",+ "com",+ "edu",+ "go",+ "gov",+ "ne",+ "net",+ "or",+ "org",+]);++// The title the server gives a workspace nobody has named yet. Its letter case+// differs by how the account signed up: "Default workspace" by email,+// "Default Workspace" through an identity provider.+const UNNAMED_WORKSPACE_TITLE = "Default workspace";++const capitalize = (word: string) =>+ word.charAt(0).toUpperCase() + word.slice(1);++const sameText = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();++export const guessDisplayName = (+ email: string,+ title: string | undefined+): string => {+ const localPart = email.split("@")[0] ?? "";+ const given = title?.trim() ?? "";+ // An account created without a name carries its address as one.+ if (given && !sameText(given, email) && !sameText(given, localPart)) {+ return given;+ }+ const base = localPart.split("+")[0] ?? "";+ const words = base.split(/[._-]+/).filter(Boolean);+ const namesNobody =+ !/\p{L}/u.test(base) ||+ SHARED_MAILBOXES.has(words.join("").toLowerCase()) ||+ words.some((word) => SHARED_MAILBOXES.has(word.toLowerCase()));+ return namesNobody ? "" : words.map(capitalize).join(" ");+};++// The company part of the address's domain: the label before the top-level+// domain, or before a second-level one such as "co".+const guessCompany = (email: string): string | undefined => {+ const labels = (email.split("@")[1] ?? "").toLowerCase().split(".");+ labels.pop();+ const last = labels.at(-1);+ if (labels.length > 1 && last && SECOND_LEVEL_LABELS.has(last)) labels.pop();+ const company = labels.at(-1);+ if (!company || PUBLIC_MAIL_PROVIDERS.has(company)) return undefined;+ return company.split("-").map(capitalize).join(" ");+};++type WorkspaceTitleGuess =+ | { kind: "title"; title: string }+ | { kind: "personal"; firstName: string }+ | { kind: "anonymous" };++// A workspace that already has a real name keeps it; otherwise the company+// behind the address names it, and a personal address names it after its owner.+export const guessWorkspaceTitle = (+ email: string,+ displayName: string,+ currentTitle: string | undefined+): WorkspaceTitleGuess => {+ const existing = currentTitle?.trim();+ if (existing && !sameText(existing, UNNAMED_WORKSPACE_TITLE)) {+ return { kind: "title", title: existing };+ }+ const company = guessCompany(email);+ if (company) return { kind: "title", title: company };+ const firstName = displayName.split(/\s+/)[0];+ return firstName ? { kind: "personal", firstName } : { kind: "anonymous" };+};diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsxindex 9af71c63bb..afb4842890 100644--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({| "query-data"| "create-database-change"| "mark-sensitive-data"+ | "just-exploring"| undefined,removeDatabaseMetadataCache: vi.fn(),fetchInstance: vi.fn(),@@ -826,8 +827,11 @@ describe("ProjectDatabasesPage", () => {});});- test("only offers SQL Editor for the query scenario", async () => {- mocks.scenarioId = "query-data";+ test.each([+ "query-data",+ "just-exploring",+ ] as const)("only offers SQL Editor for the %s scenario", async (scenarioId) => {+ mocks.scenarioId = scenarioId;mocks.routerCurrentQuery = { intro: "project-instance-synced" };mocks.visibleDatabases = [{diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsxindex 58cbbcc74e..44e8e65529 100644--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx@@ -52,6 +52,7 @@ import {useProductIntro,} from "@/lib/productIntro";import { normalizeInstanceName } from "@/lib/resourceName";+import { leadsWithQuery } from "@/modules/workspace-setup-guide/scenarios";import { readSelectedGuideScenarioId } from "@/modules/workspace-setup-guide/selection";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";@@ -578,7 +579,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {showSqlEditor: false,showMarkSensitiveData: false,}- : selectedGuideScenarioId === "query-data"+ : leadsWithQuery(selectedGuideScenarioId)? {title: t("db.project-instance-synced-query-data-title"),description: t("db.project-instance-synced-query-data-description"),diff --git a/frontend/src/routes/project/ProjectHomePage.test.tsx b/frontend/src/routes/project/ProjectHomePage.test.tsxindex c7372b9751..f7e3c033fb 100644--- a/frontend/src/routes/project/ProjectHomePage.test.tsx+++ b/frontend/src/routes/project/ProjectHomePage.test.tsx@@ -9,6 +9,7 @@ import { DatabaseSchema$ } from "@/types/proto-es/v1/database_service_pb";import { InstanceResourceSchema } from "@/types/proto-es/v1/instance_service_pb";import { IssueSchema, Issue_Type } from "@/types/proto-es/v1/issue_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";+import { storageKeyWorkspaceSetupGuideScenario } from "@/utils/storage-keys";const mocks = vi.hoisted(() => ({state: {@@ -739,6 +740,21 @@ describe("ProjectHomePage", () => {).toBeNull();});+ test("leads with querying when this browser's setup goal was to query data", async () => {+ localStorage.setItem(+ storageKeyWorkspaceSetupGuideScenario("workspaces/demo", "[email protected]"),+ JSON.stringify("query-data")+ );+ render(<ProjectHomePage projectId="orders" />);+ const next = await screen.findByRole("region", { name: "project.home.next-step" });+ await within(next).findByRole("link", { name: "project.home.query-database" });+ expect(within(next).getAllByRole("link").map((link) => link.textContent)).toEqual([+ "project.home.query-database",+ "project.home.change-database",+ "project.home.members",+ ]);+ });+test("shows database change after database creation, but hides setup after a submitted change", async () => {const accessIssue = create(IssueSchema, {name: "projects/orders/issues/access",diff --git a/frontend/src/routes/project/ProjectHomePage.tsx b/frontend/src/routes/project/ProjectHomePage.tsxindex f9da1a093d..373e493c05 100644--- a/frontend/src/routes/project/ProjectHomePage.tsx+++ b/frontend/src/routes/project/ProjectHomePage.tsx@@ -37,6 +37,7 @@ import {selectHasRunningChat,useAgentStore,} from "@/modules/agent/store/agent";+import { readSelectedGuideScenarioId } from "@/modules/workspace-setup-guide/selection";import { useAppStore } from "@/stores/app";import type { Permission } from "@/types/iam";import {@@ -527,6 +528,7 @@ export function ProjectHomePage({ projectId }: { projectId: string }) {canCreateChange,canQueryDatabase,canManageMembers,+ goal: readSelectedGuideScenarioId(),});const nextStepCopy = (step: ProjectHomeNextStep) => {diff --git a/frontend/src/routes/project/projectHomeNextSteps.test.ts b/frontend/src/routes/project/projectHomeNextSteps.test.tsindex f7d5dfceb9..c7f255c41c 100644--- a/frontend/src/routes/project/projectHomeNextSteps.test.ts+++ b/frontend/src/routes/project/projectHomeNextSteps.test.ts@@ -124,6 +124,27 @@ describe("getProjectHomeNextSteps", () => {).toEqual(["changeDatabase", "queryDatabase"]);});+ test.each([+ ["query-data", ["queryDatabase", "changeDatabase", "members"]],+ ["just-exploring", ["queryDatabase", "changeDatabase", "members"]],+ ["create-database-change", ["changeDatabase", "queryDatabase", "members"]],+ ] as const)("orders the next steps for the goal %s", (goal, steps) => {+ expect(+ getProjectHomeNextSteps({ ...input, database: "present", goal })+ ).toEqual(steps);+ });++ test("does not lead with a query the member cannot run, whatever their goal", () => {+ expect(+ getProjectHomeNextSteps({+ ...input,+ database: "present",+ goal: "query-data",+ canQueryDatabase: false,+ })+ ).toEqual(["changeDatabase", "members"]);+ });+test("only offers querying alongside a database change when SQL Editor is available", () => {expect(getProjectHomeNextSteps({diff --git a/frontend/src/routes/project/projectHomeNextSteps.ts b/frontend/src/routes/project/projectHomeNextSteps.tsindex 973637c7f5..e9a4593ee7 100644--- a/frontend/src/routes/project/projectHomeNextSteps.ts+++ b/frontend/src/routes/project/projectHomeNextSteps.ts@@ -1,3 +1,6 @@+import { leadsWithQuery } from "@/modules/workspace-setup-guide/scenarios";+import type { GuideScenarioId } from "@/modules/workspace-setup-guide/types";+export type ResourceAvailability = "loading" | "present" | "empty" | "unknown";export type ProjectHomeNextStep =@@ -21,6 +24,8 @@ export type ProjectHomeNextStepInput = {canCreateChange: boolean;canQueryDatabase: boolean;canManageMembers: boolean;+ // The setup wizard's answer, known only in the browser that ran it.+ goal?: GuideScenarioId;};export function getProjectHomeNextSteps(@@ -62,9 +67,12 @@ export function getProjectHomeNextSteps((input.change === "not-started" || input.change === "unknown") &&input.canCreateChange) {- steps.push("changeDatabase");- if (input.canQueryDatabase) {- steps.push("queryDatabase");+ if (!input.canQueryDatabase) {+ steps.push("changeDatabase");+ } else if (leadsWithQuery(input.goal)) {+ steps.push("queryDatabase", "changeDatabase");+ } else {+ steps.push("changeDatabase", "queryDatabase");}}diff --git a/frontend/src/stores/app/iam.ts b/frontend/src/stores/app/iam.tsindex 89b74fb696..c0fe904e3a 100644--- a/frontend/src/stores/app/iam.ts+++ b/frontend/src/stores/app/iam.ts@@ -20,7 +20,7 @@ import { ListRolesRequestSchema } from "@/types/proto-es/v1/role_service_pb";import { ALL_USERS_USER_EMAIL, groupBindingPrefix } from "@/types/v1/user";import { getUserListInBinding, isBindingPolicyExpired } from "@/utils/v1/iam";import type { AppSliceCreator, IamSlice } from "./types";-import { bindingMatchesUser, projectWideBindings } from "./utils";+import { bindingMatchesUser, callOptions, projectWideBindings } from "./utils";// Merge a member's role set into a policy clone: drop the member from roles it// no longer holds, add it to roles it gained, and append bindings for brand-new@@ -216,7 +216,7 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({);},- updateProjectIamPolicy: async (project, policy) => {+ updateProjectIamPolicy: async (project, policy, report) => {// Dedupe members within each binding before the write.const deduped = cloneDeep(policy);for (const binding of deduped.bindings) {@@ -233,7 +233,8 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({resource: project,policy: deduped,etag: deduped.etag,- })+ }),+ callOptions(report)).catch(async (error) => {await recoverFromIamPolicyConflict(error, async () => {@@ -277,7 +278,7 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({return updated;},- fetchWorkspaceIamPolicy: async (silent = false) => {+ fetchWorkspaceIamPolicy: async (silent = false, report) => {const resource =get().serverInfo?.workspace ||get().workspace?.name ||@@ -285,7 +286,9 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({`${workspaceNamePrefix}-`;const policy = await workspaceServiceClientConnect.getIamPolicy(createProto(GetIamPolicyRequestSchema, { resource }),- { contextValues: createContextValues().set(silentContextKey, silent) }+ callOptions(report) ?? {+ contextValues: createContextValues().set(silentContextKey, silent),+ });// Prefetch groups referenced by the policy so the derived role/user maps// can expand group members from the same app-store cache.@@ -301,7 +304,7 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({return policy;},- patchWorkspaceIamPolicy: async (batchPatch) => {+ patchWorkspaceIamPolicy: async (batchPatch, report) => {if (batchPatch.length === 0) {return;}@@ -322,7 +325,8 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({resource,policy,etag: policy.etag,- })+ }),+ callOptions(report)).catch(async (error) => {await recoverFromIamPolicyConflict(error, () =>diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.tsindex 8024eb3b39..a092b649f2 100644--- a/frontend/src/stores/app/index.test.ts+++ b/frontend/src/stores/app/index.test.ts@@ -2,7 +2,10 @@ import { create as createProto } from "@bufbuild/protobuf";import { TimestampSchema } from "@bufbuild/protobuf/wkt";import { Code, ConnectError } from "@connectrpc/connect";import { beforeEach, describe, expect, test, vi } from "vitest";-import { silentContextKey } from "@/api/context-key";+import {+ silentContextKey,+ skipErrorNotificationContextKey,+} from "@/api/context-key";import { isValidDatabaseGroupName, UNKNOWN_PROJECT_NAME } from "@/types";import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";import {@@ -1257,12 +1260,10 @@ describe("useAppStore", () => {expect(result).toBe(userA);expect(mocks.getUser).not.toHaveBeenCalled();- expect(mocks.updateUser).toHaveBeenCalledWith(- expect.objectContaining({- user: userA,- allowMissing: true,- })- );+ expect(mocks.updateUser.mock.calls[0][0]).toMatchObject({+ user: userA,+ allowMissing: true,+ });expect(store.getState().usersByName[userA.name]).toBe(userA);});@@ -2384,6 +2385,64 @@ describe("useAppStore", () => {expect(store.getState().projectsByName[projectA.name]).toBe(projectA);});+ test.each([+ { reportedBy: "the caller, on request", report: { byCaller: true } },+ { reportedBy: "the shared error toast, by default", report: undefined },+ ])(+ "leaves a failed write to be reported by $reportedBy",+ async ({ report }) => {+ const policy = createProto(IamPolicySchema, {});+ const workspace = createProto(WorkspaceSchema, {+ name: "workspaces/default",+ });+ mocks.updateUser.mockResolvedValue(userA);+ mocks.updateWorkspace.mockResolvedValue(workspace);+ mocks.createProject.mockResolvedValue(projectA);+ mocks.getIamPolicy.mockResolvedValue(policy);+ mocks.setProjectIamPolicy.mockResolvedValue(policy);+ mocks.setIamPolicy.mockResolvedValue(policy);+ const store = createAppStore();+ const state = store.getState();++ await state.updateUser(+ createProto(UpdateUserRequestSchema, {+ user: userA,+ allowMissing: true,+ }),+ report+ );+ await state.updateWorkspace(workspace, ["title"], report);+ await state.createProject("A", "a", report);+ await state.updateProjectIamPolicy(projectA.name, policy, report);+ await state.fetchWorkspaceIamPolicy(false, report);+ await state.patchWorkspaceIamPolicy(+ [{ member: "user:[email protected]", roles: ["roles/workspaceMember"] }],+ report+ );++ const writes = {+ updateUser: mocks.updateUser,+ updateWorkspace: mocks.updateWorkspace,+ createProject: mocks.createProject,+ setProjectIamPolicy: mocks.setProjectIamPolicy,+ getWorkspaceIamPolicy: mocks.getIamPolicy,+ setWorkspaceIamPolicy: mocks.setIamPolicy,+ };+ expect(+ Object.fromEntries(+ Object.entries(writes).map(([name, write]) => [+ name,+ write.mock.calls[0][1]?.contextValues.get(+ skipErrorNotificationContextKey+ ) ?? false,+ ])+ )+ ).toEqual(+ Object.fromEntries(Object.keys(writes).map((name) => [name, !!report]))+ );+ }+ );+test("checks workspace permission through user, groups, and roles", () => {const store = createAppStore();store.setState({diff --git a/frontend/src/stores/app/instance.ts b/frontend/src/stores/app/instance.tsindex d63627ede6..4ff026fb42 100644--- a/frontend/src/stores/app/instance.ts+++ b/frontend/src/stores/app/instance.ts@@ -1,10 +1,7 @@import { create as createProto } from "@bufbuild/protobuf";import { createContextValues } from "@connectrpc/connect";import { instanceServiceClientConnect } from "@/api";-import {- silentContextKey,- skipErrorNotificationContextKey,-} from "@/api/context-key";+import { silentContextKey } from "@/api/context-key";import { projectNamePrefix } from "@/stores/modules/v1/common";import { Engine, State } from "@/types/proto-es/v1/common_pb";import {@@ -42,7 +39,7 @@ import {} from "@/utils";import { celString, celStringList } from "@/utils/v1/celLiteral";import type { AppSliceCreator, InstanceFilter, InstanceSlice } from "./types";-import { getLabelFilter, toError } from "./utils";+import { callOptions, getLabelFilter, toError } from "./utils";export const getListInstanceFilter = (params: InstanceFilter): string => {const list: string[] = [];@@ -217,12 +214,7 @@ export const createInstanceSlice: AppSliceCreator<InstanceSlice> = (const response =await instanceServiceClientConnect.prepareSampleProjectInstance(createProto(PrepareSampleProjectInstanceRequestSchema, { parent }),- {- contextValues: createContextValues().set(- skipErrorNotificationContextKey,- true- ),- }+ callOptions({ byCaller: true }));const instance = upsertInstances([response])[0];await get()diff --git a/frontend/src/stores/app/project.ts b/frontend/src/stores/app/project.tsindex e77eb5f6d5..5b7cb82eff 100644--- a/frontend/src/stores/app/project.ts+++ b/frontend/src/stores/app/project.ts@@ -24,6 +24,7 @@ import { setProjectAccess } from "./projectAccess";import type { AppSliceCreator, ProjectFilter, ProjectSlice } from "./types";import {buildProjectFilter,+ callOptions,defaultProjectName,getLabelFilter,isMissingOrForbidden,@@ -271,7 +272,7 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {};},- createProject: async (title, resourceId) => {+ createProject: async (title, resourceId, report) => {const project = createProto(ProjectSchema, {title,state: State.ACTIVE,@@ -285,7 +286,8 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {createProto(CreateProjectRequestSchema, {project,projectId: resourceId,- })+ }),+ callOptions(report));upsertProjects([created]);return created;diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex 60efa5245b..b290639873 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -105,6 +105,10 @@ import type { IssueFilter } from "@/types/v1/issue/issue";import type { SQLResultSetV1 } from "@/types/v1/sql";import type { AccessGrantDisplayStatus } from "@/utils";+// How a failed request is reported. A caller that shows the failure itself+// sets `byCaller`, and the global error toast then stays out of it.+export type ErrorReport = { byCaller?: boolean };+export type ProjectListParams = {pageSize: number;pageToken: string;@@ -253,7 +257,8 @@ export type WorkspaceSlice = {loadWorkspaceList: () => Promise<Workspace[]>;updateWorkspace: (workspace: Workspace,- updateMask: string[]+ updateMask: string[],+ report?: ErrorReport) => Promise<Workspace>;switchWorkspace: (workspaceName: string,@@ -376,11 +381,16 @@ export type IamSlice = {getProjectIamPolicy: (project: string) => IamPolicy;updateProjectIamPolicy: (project: string,- policy: IamPolicy+ policy: IamPolicy,+ report?: ErrorReport+ ) => Promise<IamPolicy>;+ fetchWorkspaceIamPolicy: (+ silent?: boolean,+ report?: ErrorReport) => Promise<IamPolicy>;- fetchWorkspaceIamPolicy: (silent?: boolean) => Promise<IamPolicy>;patchWorkspaceIamPolicy: (- batchPatch: { member: string; roles: string[] }[]+ batchPatch: { member: string; roles: string[] }[],+ report?: ErrorReport) => Promise<void>;workspaceRoleMapToUsers: () => Map<string, Set<string>>;workspaceUserMapToRoles: () => Map<string, Set<string>>;@@ -429,7 +439,11 @@ export type ProjectSlice = {orderBy?: string;cache?: boolean;}) => Promise<{ projects: Project[]; nextPageToken?: string }>;- createProject: (title: string, resourceId: string) => Promise<Project>;+ createProject: (+ title: string,+ resourceId: string,+ report?: ErrorReport+ ) => Promise<Project>;updateProject: (project: Project, updateMask: string[]) => Promise<Project>;archiveProject: (project: Project) => Promise<void>;restoreProject: (project: Project) => Promise<void>;@@ -855,7 +869,10 @@ export type UserSlice = {}) => Promise<User>;getUserByIdentifier: (identifier: string) => User | undefined;createUser: (user: User) => Promise<User>;- updateUser: (request: UpdateUserRequest) => Promise<User>;+ updateUser: (+ request: UpdateUserRequest,+ report?: ErrorReport+ ) => Promise<User>;updateEmail: (oldEmail: string, newEmail: string) => Promise<User>;archiveUser: (name: string) => Promise<void>;restoreUser: (name: string) => Promise<User>;diff --git a/frontend/src/stores/app/user.ts b/frontend/src/stores/app/user.tsindex eb1f0cc54f..c280fc9d47 100644--- a/frontend/src/stores/app/user.ts+++ b/frontend/src/stores/app/user.ts@@ -28,7 +28,7 @@ import {import { celString } from "@/utils/v1/celLiteral";import { ensureUserFullName } from "@/utils/v1/user";import type { AppSliceCreator, UserFilter, UserSlice } from "./types";-import { isMissingOrForbidden } from "./utils";+import { callOptions, isMissingOrForbidden } from "./utils";const UNKNOWN_PROJECT_NAME_LEGACY = "projects/-";@@ -212,7 +212,7 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {return response;},- updateUser: async (request) => {+ updateUser: async (request, report) => {const name = request.user?.name || "";if (!request.allowMissing) {const originData = await get().getOrFetchUserByIdentifier({@@ -229,7 +229,8 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {user: request.user,updateMask: request.updateMask,allowMissing: request.allowMissing,- })+ }),+ callOptions(report));set((state) => ({usersByName: { ...state.usersByName, [response.name]: response },diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.tsindex 632a96dce0..760ec704a3 100644--- a/frontend/src/stores/app/utils.ts+++ b/frontend/src/stores/app/utils.ts@@ -1,4 +1,5 @@-import { Code, ConnectError } from "@connectrpc/connect";+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";+import { skipErrorNotificationContextKey } from "@/api/context-key";// The per-resource failures the all-or-nothing BatchGet contract introduces.// Only these are worth a per-name retry; anything else is a real error.@@ -26,7 +27,7 @@ import { isValidInstanceName } from "@/types/v1/instance";import { workspaceCacheScope } from "@/utils/storage-keys";import { celMapField, celString, celStringList } from "@/utils/v1/celLiteral";import { bindingScopesResources } from "@/utils/v1/iam";-import type { AppStoreState } from "./types";+import type { AppStoreState, ErrorReport } from "./types";export const MAX_RECENT_PROJECT = 5;export const MAX_RECENT_VISIT = 10;@@ -273,6 +274,18 @@ export function defaultProjectName(get: () => AppStoreState) {return get().serverInfo?.defaultProject ?? "";}+// Call options for a request the caller reports the failure of itself.+export function callOptions(report: ErrorReport | undefined) {+ return report?.byCaller+ ? {+ contextValues: createContextValues().set(+ skipErrorNotificationContextKey,+ true+ ),+ }+ : undefined;+}+export function isConnectAlreadyExists(error: unknown): error is ConnectError {return error instanceof ConnectError && error.code === Code.AlreadyExists;}diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.tsindex 38bb32fe05..91f49ba191 100644--- a/frontend/src/stores/app/workspace.ts+++ b/frontend/src/stores/app/workspace.ts@@ -54,10 +54,7 @@ import {UploadLicenseRequestSchema,VerifyCheckoutSessionRequestSchema,} from "@/types/proto-es/v1/subscription_service_pb";-import {- UpdateWorkspaceRequestSchema,- type Workspace,-} from "@/types/proto-es/v1/workspace_service_pb";+import { UpdateWorkspaceRequestSchema } from "@/types/proto-es/v1/workspace_service_pb";import {getDateForPbTimestampProtoEs,getTimeForPbTimestampProtoEs,@@ -72,6 +69,7 @@ import {import { colorToHex, hexToColor } from "@/utils";import { formatAbsoluteDateTime } from "@/utils/datetime";import type { AppSliceCreator, WorkspaceSlice } from "./types";+import { callOptions } from "./utils";let workspaceSwitchListenerRegistered = false;@@ -270,12 +268,13 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (return resp.workspaces;},- updateWorkspace: async (workspace: Workspace, updateMask: string[]) => {+ updateWorkspace: async (workspace, updateMask, report) => {const updated = await workspaceServiceClientConnect.updateWorkspace(createProto(UpdateWorkspaceRequestSchema, {workspace,updateMask: createProto(FieldMaskSchema, { paths: updateMask }),- })+ }),+ callOptions(report));set((state) => ({workspace:diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.tsindex a72e5179fc..2bc282fa0a 100644--- a/frontend/src/utils/storage-keys.ts+++ b/frontend/src/utils/storage-keys.ts@@ -71,8 +71,14 @@ export const storageKeyWorkspaceSetupGuideWorkspaceUsage = (scope: string,email: string) => withScope("bb.workspace-setup-guide.workspace-usage", scope, email);+export const storageKeyWorkspaceSetupGuideTeamSize = (+ scope: string,+ email: string+) => withScope("bb.workspace-setup-guide.team-size", scope, email);export const storageKeyWorkspaceSetupFinished = (workspace: string) =>withScope("bb.workspace-setup.finished", workspace);+export const storageKeyWorkspaceSetupDraft = (scope: string, email: string) =>+ withScope("bb.workspace-setup.draft", scope, email);// Workspace-scoped: value keys embed project resource names.export const storageKeyIamRemind = (scope: string, email: string) =>withScope("bb.iam-remind", scope, email);diff --git a/frontend/tests/e2e/AGENTS.md b/frontend/tests/e2e/AGENTS.mdindex 74aa244428..06604ce144 100644--- a/frontend/tests/e2e/AGENTS.md+++ b/frontend/tests/e2e/AGENTS.md@@ -94,6 +94,7 @@ frontend/tests/e2e/| `framework/global-setup.ts` | Starts server before any test runs || `framework/global-teardown.ts` | Stops server after all tests finish || `framework/setup-project.ts` | Auth + instance/database discovery, writes env + auth state |+| `framework/bare-server.ts` | A second server in first-run state, started and stopped by the one spec that needs it |## Adding a New Feature Test Suite@@ -129,6 +130,7 @@ Get the correct port from `getInstance(env.instance)` rather than hardcoding the- **`psql` dependency**: must be on PATH for DDL/DML setup.- **Unix-like OS only**: the sample Postgres uses Unix sockets in `/tmp`.- **Admin credentials**: hardcoded `[email protected]` / `12345678`. The first user created via `/v1/auth/signup` becomes workspace admin, so e2e signs up this fixture.+- **First-run state**: the shared server has two members and a used sample, so it never shows the setup wizard. A spec that needs a workspace with one member and an unused sample starts its own with `startBareServer()` and stops it in `afterAll` (see `workspace-setup/workspace-setup.spec.ts`). That server has no license, so it is for free-plan behavior only.- **DBA fixture**: `[email protected]` / `12345678` is created during `globalSetup` and granted `roles/workspaceDBA`. Used as the second approver by plan-detail approval specs. If a spec needs additional users (developer, QA, etc.), provision them the same way in `mode-start-new-bytebase.ts` — don't assume they exist.## Assertions and regression coveragediff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdindex 283c70104b..d84ae4d795 100644--- a/frontend/tests/e2e/README.md+++ b/frontend/tests/e2e/README.md@@ -104,13 +104,15 @@ frontend/tests/e2e/│ ├── setup-project.ts — auth + discovery (runs as a Playwright setup project)│ ├── seed-test-data.ts — workspace-level baseline seeded once per boot│ ├── sign-in.ts — POST-login helper that captures per-user storageState-│ └── psql.ts — psql-over-Unix-socket helpers for DDL/DML setup+│ ├── psql.ts — psql-over-Unix-socket helpers for DDL/DML setup+│ └── bare-server.ts — a second, first-run server for the spec that needs one├── sql-editor/ — SQL Editor suite (connection, result, tabs, saved query,│ schema, admin-mode, history, jit, permissions,│ workspace-gates, batch, misc) + sql-editor.page.ts├── plan-detail/ — plan detail suite (lifecycle, checks, rollout, sections, tasks)│ + plan-detail.page.ts, plan-helpers.ts├── workspace/ — workspace-level suite (external-URL banner)+├── workspace-setup/ — first-run setup wizard, on a server of its own└── masking-exemption/ — masking exemption suite├── masking-exemption.spec.ts└── masking-exemption.page.tsdiff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex 9bcca8ccfa..412f1683cc 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -869,6 +869,10 @@ export class BytebaseApiClient {return this.request("GET", `/v1/${project}`);}+ async listProjects() {+ return this.request<{ projects?: { name: string; title: string }[] }>("GET", "/v1/projects?pageSize=100&showDeleted=false");+ }+// Access grants (just-in-time). The body is the AccessGrant proto directly// (CreateAccessGrant binds `body: "access_grant"`). `creator` is derived from// the client's own credentials so SearchMyAccessGrants (which filters to thediff --git a/frontend/tests/e2e/framework/bare-server.ts b/frontend/tests/e2e/framework/bare-server.tsnew file mode 100644index 0000000000..d36951711b--- /dev/null+++ b/frontend/tests/e2e/framework/bare-server.ts@@ -0,0 +1,60 @@+import * as fs from "fs";+import * as os from "os";+import * as path from "path";++import type { BytebaseApiClient } from "./api-client";+import {+ ADMIN_EMAIL,+ ADMIN_PASSWORD,+ cleanupOrphans,+ findAvailablePort,+ spawnServer,+ startupTimeoutMs,+ terminateServer,+ waitForAdmin,+} from "./mode-start-new-bytebase";++const PID_FILE = "/tmp/bytebase-e2e-bare-pid";++export interface BareServer {+ baseURL: string;+ adminEmail: string;+ adminPassword: string;+ api: BytebaseApiClient;+ stop: () => Promise<void>;+}++// The hook that calls `startBareServer` needs at least this long, so that a+// slow boot ends in the function's own cleanup and not in a hook timeout.+export const bareServerStartTimeoutMs = () => startupTimeoutMs() + 30_000;++// A second server in first-run state, for a spec the shared one cannot serve:+// its only account is the admin that signed up, it has no project, and its+// sample is unused. It runs on the free plan. The caller owns it and must+// call `stop`; a server left behind by a killed run is removed by the next+// call.+export async function startBareServer(): Promise<BareServer> {+ cleanupOrphans(PID_FILE);+ const port = await findAvailablePort();+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "bytebase-e2e-bare-"));+ const child = spawnServer(port, dataDir, PID_FILE);+ const stop = async () => {+ await terminateServer(child, dataDir);+ fs.rmSync(PID_FILE, { force: true });+ };++ try {+ const baseURL = `http://localhost:${port}`;+ const api = await waitForAdmin(child, baseURL);+ return {+ baseURL,+ adminEmail: ADMIN_EMAIL,+ adminPassword: ADMIN_PASSWORD,+ api,+ stop,+ };+ } catch (error) {+ await stop();+ throw error;+ }+}diff --git a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts b/frontend/tests/e2e/framework/mode-start-new-bytebase.tsindex ad72ecb9cc..9228ebe9c2 100644--- a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts+++ b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts@@ -9,8 +9,8 @@ import { BytebaseApiClient } from "./api-client";const PID_FILE = "/tmp/bytebase-e2e-pid";const DEFAULT_PORT = 18234;const DEFAULT_TIMEOUT = 300000; // 5 minutes — server startup includes embedded Postgres + migrations + sample-instance bring-up-const ADMIN_EMAIL = "[email protected]";-const ADMIN_PASSWORD = "12345678"; // NOSONAR: e2e fixture+export const ADMIN_EMAIL = "[email protected]";+export const ADMIN_PASSWORD = "12345678"; // NOSONAR: e2e fixtureconst ADMIN_TITLE = "Demo";const SAMPLE_PROJECT_ID = "project-sample";const SAMPLE_PROJECT_TITLE = "Sample Project";@@ -41,9 +41,9 @@ function isBytebaseProcess(pid: number): boolean {}}-export function cleanupOrphans(): void {- if (!fs.existsSync(PID_FILE)) return;- const content = fs.readFileSync(PID_FILE, "utf-8").trim().split("\n");+export function cleanupOrphans(pidFile: string = PID_FILE): void {+ if (!fs.existsSync(pidFile)) return;+ const content = fs.readFileSync(pidFile, "utf-8").trim().split("\n");const pid = parseInt(content[0], 10);const dir = content[1];if (Number.isFinite(pid) && pid > 0 && isBytebaseProcess(pid)) {@@ -56,7 +56,7 @@ export function cleanupOrphans(): void {if (dir && fs.existsSync(dir)) {fs.rmSync(dir, { recursive: true, force: true });}- fs.unlinkSync(PID_FILE);+ fs.unlinkSync(pidFile);}function checkPort(port: number): Promise<boolean> {@@ -67,7 +67,9 @@ function checkPort(port: number): Promise<boolean> {server.close();resolve(true);});- server.listen(port, "127.0.0.1");+ // No host, as the server itself binds: macOS lets a 127.0.0.1 bind succeed+ // beside a wildcard listener, which would hand out a running server's port.+ server.listen(port);});}@@ -118,15 +120,20 @@ function isPortListening(port: number): Promise<boolean> {}// Poll until predicate succeeds or deadline passes. On timeout, throws with-// the last underlying error so the cause isn't swallowed.+// the last underlying error so the cause isn't swallowed. `giveUp` ends the+// wait early, with the reason it returns, when succeeding has become+// impossible.async function pollUntil(predicate: () => Promise<void>,deadline: number,intervalMs: number,- timeoutMessage: string+ timeoutMessage: string,+ giveUp?: () => string | undefined): Promise<void> {let lastError: unknown;while (Date.now() < deadline) {+ const reason = giveUp?.();+ if (reason) throw new Error(reason);try {await predicate();return;@@ -149,31 +156,20 @@ export async function findAvailablePort(): Promise<number> {const offsets = [0, 2, 3];for (let i = 0; i < 100; i++) {const checks = await Promise.all(offsets.map((o) => checkPort(port + o)));- if (checks.every((free) => free)) return port;+ // The embedded and sample Postgres listen on Unix sockets only, so a TCP+ // bind cannot see another server's.+ const sockets = await Promise.all(+ [2, 3].map((o) => isPortListening(port + o))+ );+ if (checks.every((free) => free) && sockets.every((used) => !used)) {+ return port;+ }port += 4; // skip past all 3 offsets to avoid re-checking conflicting slots}throw new Error("Could not find available port range for Bytebase");}-export async function startServer(): Promise<{- baseURL: string;- adminEmail: string;- adminPassword: string;- project: string;- instance: string;-}> {- // License is REQUIRED (the suite is enterprise-only). Verify it's present- // BEFORE booting the server, so a missing license fails fast and never- // orphans a server process.- const license = process.env.BYTEBASE_E2E_LICENSE?.trim();- if (!license) {- throw new Error(- "BYTEBASE_E2E_LICENSE is required to run the e2e suite. Set it to a valid " +- "enterprise license JWT (signed by Bytebase's license key) and re-run. " +- "The suite does not run on the free plan.",- );- }-+function findServerBinary(): string {// Check both CWD-relative and repo-root-relative pathsconst candidates = [process.env.BYTEBASE_BIN,@@ -189,13 +185,27 @@ export async function startServer(): Promise<{`Or set BYTEBASE_BIN to the binary path.`);}+ return binPath;+}- const port = await findAvailablePort();- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "bytebase-e2e-"));+export function startupTimeoutMs(): number {+ return parseInt(+ process.env.BYTEBASE_STARTUP_TIMEOUT ?? String(DEFAULT_TIMEOUT),+ 10+ );+}+// Detached, so the server leads a process group `terminateServer` can signal.+// Its Postgres processes run outside that group and stop when the server+// shuts down. `pidFile` records the server for `cleanupOrphans`.+export function spawnServer(+ port: number,+ dataDir: string,+ pidFile: string = PID_FILE+): child_process.ChildProcess {const child = child_process.spawn(- binPath,- ["--port", String(port), "--data", tempDir],+ findServerBinary(),+ ["--port", String(port), "--data", dataDir],{detached: true,stdio: "ignore",@@ -205,45 +215,124 @@ export async function startServer(): Promise<{env: { LANG: "en_US.UTF-8", ...process.env, PG_URL: "" },});-- serverProcess = child;child.unref();+ fs.writeFileSync(pidFile, `${child.pid}\n${dataDir}`);+ return child;+}- // Write PID file for orphan cleanup- fs.writeFileSync(PID_FILE, `${child.pid}\n${tempDir}`);-- const baseURL = `http://localhost:${port}`;- const timeout = parseInt(- process.env.BYTEBASE_STARTUP_TIMEOUT ?? String(DEFAULT_TIMEOUT),- 10- );- const deadline = Date.now() + timeout;+const hasExited = (child: child_process.ChildProcess) =>+ child.exitCode !== null || child.signalCode !== null;- // Phase 1: Poll /healthz+// Waits until `child` serves requests, then signs up the fixture admin, who+// becomes workspace admin as the first account, and logs the client in.+//+// Gives up as soon as `child` has exited. /healthz is asked by port, so+// otherwise a server that died at boot would be polled to the deadline, and+// another server on the same port would be taken for it.+export async function waitForAdmin(+ child: child_process.ChildProcess,+ baseURL: string+): Promise<BytebaseApiClient> {+ const timeout = startupTimeoutMs();+ const exited = () =>+ hasExited(child) ? "Bytebase server exited during startup." : undefined;await pollUntil(async () => {const resp = await fetch(`${baseURL}/healthz`);if (!resp.ok) throw new Error(`/healthz returned ${resp.status}`);},- deadline,+ Date.now() + timeout,500,- `Bytebase server did not become healthy within ${timeout}ms.`+ `Bytebase server did not become healthy within ${timeout}ms.`,+ exited);+ const reason = exited();+ if (reason) throw new Error(reason);- // Phase 2: Signup the first admin. Retry while the server finishes- // migrating its metadata schema (signup returns 4xx until the principal- // table exists). The first signup becomes workspace admin automatically.- const api = new BytebaseApiClient({ baseURL });- await pollUntil(- () => api.signup(ADMIN_EMAIL, ADMIN_PASSWORD, ADMIN_TITLE),- deadline,- 500,- "Failed to signup admin. Server may not be fully initialized."- );-- // Phase 3: Login to obtain a body token for subsequent API calls.- // Signup sets cookies only; this api-client uses bearer tokens.+ // The schema is migrated before the server listens, so signup needs no+ // retry. It sets cookies only; this client uses the bearer token of a login.+ const api = new BytebaseApiClient({+ baseURL,+ credentials: { email: ADMIN_EMAIL, password: ADMIN_PASSWORD },+ });+ await api.signup(ADMIN_EMAIL, ADMIN_PASSWORD, ADMIN_TITLE);await api.login(ADMIN_EMAIL, ADMIN_PASSWORD);+ return api;+}++// Stops `child` with its process group, then removes `dataDir`.+//+// The directory goes only after the server has exited. Deleting it while the+// embedded Postgres is still shutting down makes the checkpointer PANIC+// ("could not fsync pg_xact/0000") and leaves the metadata-Postgres socket+// (/tmp/.s.PGSQL.<PORT+2>) behind, which then trips the next boot's port+// probe. The wait must be asynchronous: Node reaps the child on the event+// loop, so a blocking poll of `kill(pid, 0)` would only ever see a zombie and+// run to its deadline. Bounded (ref'd timers keep the loop alive): a server+// that ignores SIGTERM for 15 s is SIGKILLed as a group and given a short+// grace so the directory is never deleted under a live Postgres.+export async function terminateServer(+ child: child_process.ChildProcess,+ dataDir: string | undefined+): Promise<void> {+ const exited = () => hasExited(child);+ const waitExit = (ms: number) =>+ new Promise<void>((resolve) => {+ if (exited()) {+ resolve();+ return;+ }+ const timer = setTimeout(resolve, ms);+ child.once("exit", () => {+ clearTimeout(timer);+ resolve();+ });+ });+ const signalGroup = (signal: NodeJS.Signals) => {+ try {+ process.kill(-child.pid!, signal);+ } catch {+ /* already dead */+ }+ };+ signalGroup("SIGTERM");+ await waitExit(15_000);+ if (!exited()) {+ signalGroup("SIGKILL");+ await waitExit(5_000);+ }+ if (dataDir && fs.existsSync(dataDir)) {+ fs.rmSync(dataDir, { recursive: true, force: true });+ }+}++export async function startServer(): Promise<{+ baseURL: string;+ adminEmail: string;+ adminPassword: string;+ project: string;+ instance: string;+}> {+ // License is REQUIRED (the suite is enterprise-only). Verify it's present+ // BEFORE booting the server, so a missing license fails fast and never+ // orphans a server process.+ const license = process.env.BYTEBASE_E2E_LICENSE?.trim();+ if (!license) {+ throw new Error(+ "BYTEBASE_E2E_LICENSE is required to run the e2e suite. Set it to a valid " ++ "enterprise license JWT (signed by Bytebase's license key) and re-run. " ++ "The suite does not run on the free plan.",+ );+ }++ const port = await findAvailablePort();+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "bytebase-e2e-"));+ const child = spawnServer(port, tempDir);+ serverProcess = child;++ const baseURL = `http://localhost:${port}`;+ const deadline = Date.now() + startupTimeoutMs();+ const api = await waitForAdmin(child, baseURL);// Phase 3b: Install the enterprise license. Its presence was verified at// the top of startServer (before boot); install it now that the API client@@ -309,48 +398,13 @@ export async function startServer(): Promise<{}export async function stopServer(): Promise<void> {- if (serverProcess?.pid) {- const child = serverProcess;- serverProcess = undefined;- // Wait for the server to actually exit before removing its data- // directory. Deleting it while the embedded Postgres is still shutting down- // makes the checkpointer PANIC ("could not fsync pg_xact/0000") and leaves- // the metadata-Postgres socket (/tmp/.s.PGSQL.<PORT+2>) behind, which then- // trips the next boot's port probe. The wait must be asynchronous: Node- // reaps the child on the event loop, so a blocking poll of `kill(pid, 0)`- // would only ever see a zombie and run to its deadline. Bounded (ref'd- // timers keep the loop alive): a server that ignores SIGTERM for 15 s is- // SIGKILLed as a group and given a short grace so the directory is never- // deleted under a live Postgres.- const exited = () => child.exitCode !== null || child.signalCode !== null;- const waitExit = (ms: number) =>- new Promise<void>((resolve) => {- if (exited()) {- resolve();- return;- }- const timer = setTimeout(resolve, ms);- child.once("exit", () => {- clearTimeout(timer);- resolve();- });- });- const signalGroup = (signal: NodeJS.Signals) => {- try {- process.kill(-child.pid!, signal);- } catch {- /* already dead */- }- };- signalGroup("SIGTERM");- await waitExit(15_000);- if (!exited()) {- signalGroup("SIGKILL");- await waitExit(5_000);- }- }- if (tempDir && fs.existsSync(tempDir)) {- fs.rmSync(tempDir, { recursive: true, force: true });+ const child = serverProcess;+ const dataDir = tempDir;+ serverProcess = undefined;+ if (child?.pid) {+ await terminateServer(child, dataDir);+ } else if (dataDir && fs.existsSync(dataDir)) {+ fs.rmSync(dataDir, { recursive: true, force: true });}if (fs.existsSync(PID_FILE)) {fs.unlinkSync(PID_FILE);diff --git a/frontend/tests/e2e/framework/sign-in.ts b/frontend/tests/e2e/framework/sign-in.tsindex 2d214da4a1..e6d7a7fb2b 100644--- a/frontend/tests/e2e/framework/sign-in.ts+++ b/frontend/tests/e2e/framework/sign-in.ts@@ -1,7 +1,6 @@-import type { Browser } from "@playwright/test";+import type { Browser, BrowserContext } from "@playwright/test";-// Sign a user into a fresh BrowserContext and persist its storageState to-// `storagePath`.+// Signs `context` in as a user of the server at `baseURL`.//// Why POST /v1/auth/login rather than filling the sign-in form: the React// auth form's inputs aren't reliably reachable via role/name selectors, so@@ -10,6 +9,25 @@ import type { Browser } from "@playwright/test";// in the response body — without it the response is a well-formed 200 but// the context has no cookies, so the UI stays logged out and any subsequent// page.goto() bounces to /auth (see backend/api/v1/auth_service.go).+export async function loginBrowserContext(+ context: BrowserContext,+ baseURL: string,+ email: string,+ password: string,+): Promise<void> {+ const resp = await context.request.post(`${baseURL}/v1/auth/login`, {+ data: { email, password, web: true },+ headers: { "Content-Type": "application/json" },+ });+ if (!resp.ok()) {+ throw new Error(+ `login failed for ${email}: ${resp.status()} ${await resp.text()}`,+ );+ }+}++// Sign a user into a fresh BrowserContext and persist its storageState to+// `storagePath`.//// Also pre-warms "/" to set the localStorage flag that suppresses the// "New version" modal before capturing storageState.@@ -22,15 +40,7 @@ export async function signInBrowserAs(): Promise<void> {const context = await browser.newContext();try {- const resp = await context.request.post(`${baseURL}/v1/auth/login`, {- data: { email, password, web: true },- headers: { "Content-Type": "application/json" },- });- if (!resp.ok()) {- throw new Error(- `login failed for ${email}: ${resp.status()} ${await resp.text()}`,- );- }+ await loginBrowserContext(context, baseURL, email, password);const page = await context.newPage();await page.goto(`${baseURL}/`);await page.evaluate(() => {diff --git a/frontend/tests/e2e/workspace-setup/workspace-setup.spec.ts b/frontend/tests/e2e/workspace-setup/workspace-setup.spec.tsnew file mode 100644index 0000000000..bcb95b5a87--- /dev/null+++ b/frontend/tests/e2e/workspace-setup/workspace-setup.spec.ts@@ -0,0 +1,228 @@+// First-run setup wizard (docs/design/onboarding-flow.md).+//+// The wizard is offered only to a workspace's sole member, and its sample is+// single-use, so the shared e2e server (two members, sample used) cannot show+// it. This spec boots a server of its own in first-run state and walks one+// journey on it, in the only order that keeps the wizard reachable: the skip,+// a finish without a project and the own-instance path use no sample; the+// sample path goes last.+//+// That server is self-hosted, so the journey sees self-hosted wording: the+// skip, an optional project name, a sample that runs on this server, and a+// team screen with no list of people. Cloud's invitations, and retries whose member writes lost their+// answers, are covered by the wizard's unit tests, and each goal's step order+// by the project home's.++import { expect, type Page, test } from "@playwright/test";+import {+ type BareServer,+ bareServerStartTimeoutMs,+ startBareServer,+} from "../framework/bare-server";+import { loginBrowserContext } from "../framework/sign-in";++test.setTimeout(420_000);+test.use({+ // The shared suite's signed-in state belongs to another server.+ storageState: { cookies: [], origins: [] },+ // Without these an action on a missing element waits out the whole test.+ actionTimeout: 15_000,+ navigationTimeout: 30_000,+});++let server: BareServer;++test.beforeAll(async () => {+ // The file-level timeout does not cover hooks.+ test.setTimeout(bareServerStartTimeoutMs());+ server = await startBareServer();+});++test.afterAll(async () => {+ await server?.stop();+});++const continueButton = (page: Page) =>+ page.getByRole("button", { name: "Continue", exact: true });+const backButton = (page: Page) =>+ page.getByRole("button", { name: "Back", exact: true });++const openWizard = async (page: Page) => {+ await page.goto(`${server.baseURL}/auth/setup`);+ await expect(+ page.getByRole("heading", { name: "Set up your workspace" })+ ).toBeVisible();+};++const choice = (page: Page, title: string) =>+ page.locator("label", { hasText: title }).getByRole("radio");++const nextStep = (page: Page) =>+ page.getByRole("region", { name: "Next step" });++const projectNames = async () =>+ ((await server.api.listProjects()).projects ?? []).map(({ name }) => name);++// Lets the next matching request reach the server, then answers the page with+// a server error: the work is done and its answer is lost. Resolves once the+// page has that answer.+const loseAnswerOnce = async (page: Page, method: string, act: () => Promise<void>) => {+ await page.route(+ `**/bytebase.v1.${method}`,+ async (route) => {+ await route.fetch();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ code: "internal", message: "injected" }),+ });+ },+ { times: 1 }+ );+ const lost = page.waitForResponse(+ (response) => response.url().endsWith(method) && response.status() === 500,+ { timeout: 240_000 }+ );+ await act();+ await lost;+};++test("first-run setup: skip, no project, own instance, then the sample", async ({+ page,+ context,+}) => {+ await loginBrowserContext(+ context,+ server.baseURL,+ server.adminEmail,+ server.adminPassword+ );++ await test.step("I'll do this later saves the names and creates no project", async () => {+ const projectsBefore = await projectNames();+ await openWizard(page);+ await expect(page.getByLabel(/^Your name/)).toHaveValue("Demo");+ await page.getByLabel(/^Your name/).fill("Dana");+ await page.getByLabel("Workspace name").fill("Acme");+ await continueButton(page).click();++ await expect(continueButton(page)).toBeDisabled();+ await expect(page.getByText("Pick one to continue")).toBeVisible();+ await page.getByText("Not sure yet, just exploring").click();+ await continueButton(page).click();++ // A name shows the database choice; the skip still makes no project.+ await page.getByLabel(/^Project name/).fill("Drafts");+ await expect(page.getByText(/running on this server/)).toBeVisible();+ await expect(page.getByText(/7 days/)).toHaveCount(0);+ await expect(page.getByText(/Bytebase Cloud/)).toHaveCount(0);+ await page.getByRole("button", { name: "I'll do this later" }).click();++ await page.waitForURL(/\/projects\?/);+ expect(await projectNames()).toEqual(projectsBefore);+ });++ await test.step("Finish without a project name saves the answers and creates no project", async () => {+ const projectsBefore = await projectNames();+ await openWizard(page);+ await continueButton(page).click();+ await page.getByText("Not sure yet, just exploring").click();+ await continueButton(page).click();++ await expect(+ page.getByText("Leave it empty to create a project later.")+ ).toBeVisible();+ await expect(page.getByText("Start with the sample database")).toHaveCount(0);+ await continueButton(page).click();+ await page.getByText("2–10", { exact: true }).click();+ await page.getByRole("button", { name: "Finish", exact: true }).click();++ await page.waitForURL(/\/projects\?/);+ expect(await projectNames()).toEqual(projectsBefore);+ });++ await test.step("the own-instance path keeps every answer on Back and lands on Connect an instance", async () => {+ await openWizard(page);+ // Setup ended each time before, so these names are the ones it saved.+ await expect(page.getByLabel(/^Your name/)).toHaveValue("Dana");+ await expect(page.getByLabel("Workspace name")).toHaveValue("Acme");+ // A name only the draft holds, so Back cannot show it from the server.+ await page.getByLabel("Workspace name").fill("Acme Data");+ await continueButton(page).click();+ await page.getByText("Plan, review and roll out a database change").click();+ await continueButton(page).click();++ await page.getByLabel("Project name").fill("Payments");+ const chosenId = await page+ .getByText(/^payments-[a-z0-9]{4}$/)+ .innerText();+ await page.getByText("Connect my own instance after setup").click();+ await continueButton(page).click();++ await page.getByText("2–10", { exact: true }).click();+ await expect(page.getByRole("textbox")).toHaveCount(0);++ await backButton(page).click();+ await expect(page.getByLabel("Project name")).toHaveValue("Payments");+ await expect(page.getByText(chosenId)).toBeVisible();+ await expect(+ choice(page, "Connect my own instance after setup")+ ).toHaveAttribute("aria-checked", "true");+ await backButton(page).click();+ await expect(+ choice(page, "Plan, review and roll out a database change")+ ).toHaveAttribute("aria-checked", "true");+ await backButton(page).click();+ await expect(page.getByLabel("Workspace name")).toHaveValue("Acme Data");+ await continueButton(page).click();+ await continueButton(page).click();+ await continueButton(page).click();+ await expect(choice(page, "2–10")).toHaveAttribute("aria-checked", "true");++ await page.getByRole("button", { name: "Finish", exact: true }).click();++ await page.waitForURL(new RegExp(`/projects/${chosenId}$`));+ await expect(+ nextStep(page).getByRole("link", { name: "Connect an instance" })+ ).toBeVisible();+ });++ await test.step("the sample path recovers from a create whose answer was lost and leads with the goal", async () => {+ const projectsBefore = await projectNames();+ await openWizard(page);+ await continueButton(page).click();+ // The step before stored the change goal, so a query-first landing below+ // can only come from this answer.+ await page.getByText("Query data with guardrails").click();+ await continueButton(page).click();++ await page.getByLabel("Project name").fill("Orders");+ const chosenId = await page.getByText(/^orders-[a-z0-9]{4}$/).innerText();+ await expect(+ choice(page, "Start with the sample database")+ ).toHaveAttribute("aria-checked", "true");+ await continueButton(page).click();++ await page.getByText("2–10", { exact: true }).click();++ // The project is created and the answer is lost.+ await loseAnswerOnce(page, "ProjectService/CreateProject", () =>+ page.getByRole("button", { name: "Finish", exact: true }).click()+ );+ await expect(page.getByText("Could not create Orders.")).toBeVisible();++ // The retry takes that project as its own and prepares the sample.+ await page.getByRole("button", { name: "Try again" }).click();++ await page.waitForURL(new RegExp(`/projects/${chosenId}$`));+ await expect(nextStep(page).getByRole("link").first()).toHaveText(+ "Query a database"+ );+ await expect(+ nextStep(page).getByRole("link", { name: "Change a database" })+ ).toBeVisible();+ expect((await projectNames()).sort()).toEqual(+ [...projectsBefore, `projects/${chosenId}`].sort()+ );+ });+});