diff --git a/AGENTS.md b/AGENTS.md index c959190..a31fe2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,7 +119,7 @@ These are product rules, not implementation details. A change that breaks one ne - Removing a Service or Project stops it first and deletes its logs. The Project's folder is never touched. **Coding agents** -- Each app bundles the `localhost` command of its own version. Connect your agents (Settings, the command palette, the first-run empty state) adds a `localhost` MCP server running it, and the localhost-mcp skill, to Claude Code, Cursor and Codex, only at the locations each agent documents. +- Each app bundles the `localhost` command of its own version. Connect your agents (Settings, the command palette, the empty state, the Get started checklist) adds a `localhost` MCP server running it, and the localhost-mcp skill, to Claude Code, Cursor and Codex, only at the locations each agent documents. - Claude Code's servers change through its `claude mcp` command when it is installed, else by editing `~/.claude.json`. `npx @getlocalhost/cli mcp install` (`packages/cli/`) writes the same entries from a terminal, under the same rules, and Claude Desktop's too; its JSON and TOML editors mirror the core's, so change them together. Cursor reads Claude Code's and Codex's skill folders, so it gets its own copy only when neither has one. - An update asks before disconnecting connected agents, as it asks before stopping Services; then their `localhost mcp` ends. - Nothing is written until the user clicks, after seeing the file and the entry. Only localhost's own entries change, the rest of the file byte for byte; each file is backed up before localhost first edits it; Disconnect removes only localhost's entries. A file localhost can't parse is reported, never rewritten. @@ -131,6 +131,7 @@ These are product rules, not implementation details. A change that breaks one ne - Closing the window keeps the app and its Services running; the menu bar or tray shows them. Quitting asks first when anything is active, then stops everything in parallel, whoever started it. - The apps and `localhost mcp` drive one shared core, so they see the same Runs, on Windows too. When a client disconnects, the core stops the Runs nobody needs any more: none while an app is connected, else those no remaining client started (with their Dependencies). It exits once no client has been connected for 10 s. - Updates are offered, never installed unasked: a check at launch and every few hours (off in Settings), a notice, then Update Now and Restart to Update. Restarting to update stops every Service first, like quitting, after listing them, and retires the shared core so the new version starts its own. A `.deb` or `.rpm` only links to the release. Builds without the updater's public key never check. +- The first launch of someone new shows a short welcome (Project, Service, Port) ending in Add Project…, then a Get started checklist in the sidebar ticked from real state, until complete or closed. Both are kept in the app's settings, shown once, and never to someone who opened localhost before or already has Projects. Nothing else opens by itself at launch. - Each active Run is recorded on disk (pid, process group, start time). At the next launch, survivors are offered as Orphans: Stop them (default) or Leave them. **Machines** diff --git a/README.md b/README.md index ea180c5..97eefcc 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ Shortcuts are written for macOS; on Linux and Windows use Ctrl for ⌘ and Alt f ### 1. Add a Project -Press **⌘N** (or the **+** in the sidebar) and choose your project's folder. localhost fills in a name and a **Key** (a short handle such as `my-saas`, used in logs and by the command line), then scans the folder and lists what it found: +Press **⌘N** (or choose **New Project…** from the **+** in the sidebar) and choose your project's folder. The first time you open localhost, a short welcome explains Projects, Services and Ports and ends here, then a **Get started** checklist in the sidebar follows you to your first running Service. localhost fills in a name and a **Key** (a short handle such as `my-saas`, used in logs and by the command line), then scans the folder and lists what it found: - **Node**: `package.json` scripts, run with your package manager (`pnpm run dev`, …). Known dev servers get their default port, passed as `$PORT`. - **Docker Compose**: one `Infra` Service running the whole file (`docker compose up`, in the foreground), or one per Compose service (`docker compose up `) if you'd rather. In the review you can also merge Suggestions into one Service and pick what each starts after. @@ -316,7 +316,7 @@ localhost mcp | Cursor | `~/.cursor/mcp.json` | `~/.cursor/skills/localhost-mcp/`, unless Claude Code's or Codex's folder has it (Cursor reads those too) | | Codex | `~/.codex/config.toml` | `~/.agents/skills/localhost-mcp/` | -The entry is a server named `localhost` that runs the command bundled with the app (`localhost.app/Contents/Helpers/localhost` on macOS, `localhost.exe` beside the app on Windows, `/usr/bin/localhost` from the `.deb` and `.rpm`, a copy in localhost's data folder for the AppImage) with `mcp`, so the agent always runs the same version as the app. Only localhost's own entry changes: every other server and setting stays as it was. With Claude Code installed, localhost runs `claude mcp add-json` / `claude mcp remove` instead of editing `~/.claude.json` itself. The app opens this screen by itself once, at its first launch. Restart to Update asks before it disconnects connected agents, along with stopping your Services, so the update can replace the command they run. Each file is backed up to `agent-backups/` in localhost's data folder before the first change, connecting again changes nothing, and **Disconnect** removes only localhost's entry and skill. If an agent's `localhost` server runs another command, such as `~/.cargo/bin/localhost`, the app offers **Update**. +The entry is a server named `localhost` that runs the command bundled with the app (`localhost.app/Contents/Helpers/localhost` on macOS, `localhost.exe` beside the app on Windows, `/usr/bin/localhost` from the `.deb` and `.rpm`, a copy in localhost's data folder for the AppImage) with `mcp`, so the agent always runs the same version as the app. Only localhost's own entry changes: every other server and setting stays as it was. With Claude Code installed, localhost runs `claude mcp add-json` / `claude mcp remove` instead of editing `~/.claude.json` itself. After your first Project, the **Get started** checklist in the sidebar offers it too. Restart to Update asks before it disconnects connected agents, along with stopping your Services, so the update can replace the command they run. Each file is backed up to `agent-backups/` in localhost's data folder before the first change, connecting again changes nothing, and **Disconnect** removes only localhost's entry and skill. If an agent's `localhost` server runs another command, such as `~/.cargo/bin/localhost`, the app offers **Update**. **Or from a terminal**, with the app installed: diff --git a/apps/desktop/src-tauri/src/agents.rs b/apps/desktop/src-tauri/src/agents.rs index 29615da..79acb02 100644 --- a/apps/desktop/src-tauri/src/agents.rs +++ b/apps/desktop/src-tauri/src/agents.rs @@ -76,14 +76,6 @@ async fn blocking(work: impl FnOnce() -> T + Send + 'static) tauri::async_runtime::spawn_blocking(work).await.expect("the agents' work doesn't panic") } -/// Whether Connect your agents should open by itself at this launch: once, -/// the first time localhost runs with it. -#[tauri::command] -#[specta::specta] -pub fn take_connect_agents_offer(state: tauri::State<'_, crate::AppState>) -> bool { - state.settings.take_agents_offer() -} - /// Each agent and where it stands. #[tauri::command] #[specta::specta] diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index ab40c24..83811fd 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -154,6 +154,8 @@ fn specta_builder() -> tauri_specta::Builder { wsl::wsl_distros, settings::settings, settings::save_settings, + settings::onboarding, + settings::save_onboarding, logs::open_log, logs::close_log, logs::clear_logs, @@ -171,7 +173,6 @@ fn specta_builder() -> tauri_specta::Builder { telemetry::set_telemetry_enabled, telemetry::telemetry_notice_pending, telemetry::acknowledge_telemetry_notice, - agents::take_connect_agents_offer, agents::agent_statuses, agents::connect_agent, agents::disconnect_agent, diff --git a/apps/desktop/src-tauri/src/settings.rs b/apps/desktop/src-tauri/src/settings.rs index 64d2cf7..006a389 100644 --- a/apps/desktop/src-tauri/src/settings.rs +++ b/apps/desktop/src-tauri/src/settings.rs @@ -63,9 +63,35 @@ struct Stored { /// Whether closing the window has said that localhost keeps running (`lifecycle`). #[serde(default)] has_explained_close: bool, - /// Whether Connect your agents has opened by itself, once, at a launch. + /// Whether Connect your agents opened by itself at a launch, as versions + /// before the welcome did: also a sign the app was opened before. #[serde(default)] has_offered_agents: bool, + /// The first-run welcome and checklist; `None` until the first launch + /// that has them decides. + #[serde(default, skip_serializing_if = "Option::is_none")] + onboarding: Option, +} + +/// Where the user is in the first run: whether the welcome was finished +/// or skipped, whether the Get started checklist is over (dismissed, +/// complete, or never shown to someone who used localhost before), and +/// whether a Service has been Running, which the checklist keeps ticked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", default)] +pub struct Onboarding { + pub has_seen_welcome: bool, + pub is_checklist_done: bool, + pub has_started_service: bool, +} + +/// What the first run starts from: the saved record, if any, and whether +/// this app was opened before the welcome existed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct OnboardingLaunch { + pub onboarding: Option, + pub has_opened_before: bool, } pub struct SettingsStore { @@ -107,18 +133,21 @@ impl SettingsStore { } } - /// Whether Connect your agents should open by itself: only the first - /// time this is asked, remembered from then on (for this session only if - /// the file can't be written). - pub fn take_agents_offer(&self) -> bool { - let stored = self.stored.lock().unwrap().clone(); - if stored.has_offered_agents { - return false; + pub fn onboarding_launch(&self) -> OnboardingLaunch { + let stored = self.stored.lock().unwrap(); + OnboardingLaunch { + onboarding: stored.onboarding, + has_opened_before: stored.has_offered_agents || stored.has_explained_close, } - if self.write(Stored { has_offered_agents: true, ..stored }).is_err() { - self.stored.lock().unwrap().has_offered_agents = true; + } + + /// Remembers the first run's progress; for this session only if the + /// file can't be written, so the welcome never shows twice in one. + pub fn set_onboarding(&self, onboarding: Onboarding) { + let stored = Stored { onboarding: Some(onboarding), ..self.stored.lock().unwrap().clone() }; + if self.write(stored).is_err() { + self.stored.lock().unwrap().onboarding = Some(onboarding); } - true } fn write(&self, stored: Stored) -> Result<(), LocalhostError> { @@ -164,6 +193,19 @@ pub fn save_settings(state: tauri::State<'_, AppState>, settings: Settings) -> C Ok(()) } +/// Where the first run stands, and whether localhost was used before it existed. +#[tauri::command] +#[specta::specta] +pub fn onboarding(state: tauri::State<'_, AppState>) -> OnboardingLaunch { + state.settings.onboarding_launch() +} + +#[tauri::command] +#[specta::specta] +pub fn save_onboarding(state: tauri::State<'_, AppState>, onboarding: Onboarding) { + state.settings.set_onboarding(onboarding); +} + #[cfg(test)] mod tests { use super::*; @@ -203,6 +245,33 @@ mod tests { let _ = std::fs::remove_dir_all(folder); } + #[test] + fn remembers_the_first_run_and_who_opened_localhost_before_it() { + let folder = std::env::temp_dir().join(format!("localhost-settings-onboarding-{}", std::process::id())); + let path = folder.join("settings.json"); + let store = SettingsStore::open(Some(path.clone())); + assert_eq!(store.onboarding_launch(), OnboardingLaunch { onboarding: None, has_opened_before: false }); + + let onboarding = Onboarding { has_seen_welcome: true, ..Onboarding::default() }; + store.set_onboarding(onboarding); + store.save(Settings { log_font_size: 14, ..Settings::default() }).unwrap(); + let reopened = SettingsStore::open(Some(path)); + assert_eq!(reopened.onboarding_launch().onboarding, Some(onboarding)); + assert_eq!(reopened.get().log_font_size, 14); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn an_earlier_version_s_file_counts_as_opened_before() { + let folder = std::env::temp_dir().join(format!("localhost-settings-earlier-{}", std::process::id())); + let path = folder.join("settings.json"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(&path, r#"{"logFontSize":12,"hasOfferedAgents":true}"#).unwrap(); + let launch = SettingsStore::open(Some(path)).onboarding_launch(); + assert_eq!(launch, OnboardingLaunch { onboarding: None, has_opened_before: true }); + let _ = std::fs::remove_dir_all(folder); + } + #[test] fn missing_fields_take_their_defaults() { let settings: Settings = serde_json::from_str(r#"{"editorCommand":"zed"}"#).unwrap(); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 9aee571..cc40208 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -18,6 +18,7 @@ import { startMachines, useMachines } from "./machines"; import { loadHome, tildePath } from "./paths"; import { onPerfMeasurement, runPerfMeasurement } from "./perf"; import { allServices, noService, type ServiceSelection, type SidebarSelection } from "./selection"; +import { PROJECT_CONCEPT } from "./onboarding"; import { loadSettings } from "./settings"; import type { CoreView } from "./core"; import type { Navigator } from "./palette"; @@ -174,9 +175,12 @@ function MainWindow({ view }: { view: CoreView }) {
} - title="No Projects" - description="Add a project folder to get started." - isStacked + title="Add Your First Project" + description={PROJECT_CONCEPT} + links={[ + { label: "Import Project…", onClick: () => void importProject() }, + { label: "Connect Your Agents…", onClick: () => showSheet({ kind: "connectAgents" }) }, + ]} tip={ showSheet({ kind: "addProject" })}> Add Project… - -
diff --git a/apps/desktop/src/actions.ts b/apps/desktop/src/actions.ts index 1e3b35b..0f67e6a 100644 --- a/apps/desktop/src/actions.ts +++ b/apps/desktop/src/actions.ts @@ -9,6 +9,8 @@ import { type Result, } from "./bindings"; import { listenerKey } from "./listeners"; +import { startOnboarding } from "./onboarding"; +import { currentCore } from "./store"; import { currentUi, setProgress, setStoppingListener, showAlert, showSheet } from "./ui"; // What the main window's buttons do, on this computer or, given its id, @@ -73,7 +75,7 @@ export async function stopListener(details: ListenerDetails) { /** * What the user must hear about at launch: unreadable Project files, then - * Orphans. The first launch also opens Connect your agents, once. + * Orphans. The first launch also opens the welcome, once. */ export async function runLaunchChecks() { const result = await commands.launchChecks(); @@ -81,7 +83,9 @@ export async function runLaunchChecks() { const { unreadableFiles, orphans } = result.data; if (unreadableFiles.length > 0) showAlert({ kind: "unreadableFiles", files: unreadableFiles }); if (orphans.length > 0 && !isAskingAboutOrphans()) showAlert({ kind: "orphans", orphans }); - if (!currentUi().sheet && (await commands.takeConnectAgentsOffer())) showSheet({ kind: "connectAgents" }); + const core = currentCore(); + if (core.phase !== "ready") return; + if ((await startOnboarding(core.view.projects.length)) && !currentUi().sheet) showSheet({ kind: "welcome" }); } /** A WSL distro found Orphans as it connected: asks about them, unless the question is already up. */ diff --git a/apps/desktop/src/bindings.ts b/apps/desktop/src/bindings.ts index 0a75c18..ed99789 100644 --- a/apps/desktop/src/bindings.ts +++ b/apps/desktop/src/bindings.ts @@ -473,6 +473,15 @@ async saveSettings(settings: Settings) : Promise> { else return { status: "error", error: e as any }; } }, +/** + * Where the first run stands, and whether localhost was used before it existed. + */ +async onboarding() : Promise { + return await TAURI_INVOKE("onboarding"); +}, +async saveOnboarding(onboarding: Onboarding) : Promise { + await TAURI_INVOKE("save_onboarding", { onboarding }); +}, /** * Streams `source` over `batches`: what is buffered first, then new * lines; on another Machine (`machine_id`), through its connection. @@ -589,13 +598,6 @@ async telemetryNoticePending() : Promise { async acknowledgeTelemetryNotice() : Promise { await TAURI_INVOKE("acknowledge_telemetry_notice"); }, -/** - * Whether Connect your agents should open by itself at this launch: once, - * the first time localhost runs with it. - */ -async takeConnectAgentsOffer() : Promise { - return await TAURI_INVOKE("take_connect_agents_offer"); -}, /** * Each agent and where it stands. */ @@ -1360,6 +1362,18 @@ summary: string; isConnected: boolean; * It waits for the user to connect it again. */ needsUser: boolean; projects: Project[]; statuses: StatusView[]; projectStates: ProjectState[] } +/** + * Where the user is in the first run: whether the welcome was finished + * or skipped, whether the Get started checklist is over (dismissed, + * complete, or never shown to someone who used localhost before), and + * whether a Service has been Running, which the checklist keeps ticked. + */ +export type Onboarding = { hasSeenWelcome: boolean; isChecklistDone: boolean; hasStartedService: boolean } +/** + * What the first run starts from: the saved record, if any, and whether + * this app was opened before the welcome existed. + */ +export type OnboardingLaunch = { onboarding: Onboarding | null; hasOpenedBefore: boolean } /** * Who or what requested a state-changing action. * diff --git a/apps/desktop/src/components/EmptyState.module.css b/apps/desktop/src/components/EmptyState.module.css index feb5157..4746334 100644 --- a/apps/desktop/src/components/EmptyState.module.css +++ b/apps/desktop/src/components/EmptyState.module.css @@ -42,6 +42,27 @@ max-width: 220px; } +/* Quieter actions: a row of links under the main one. */ +.links { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 4px 14px; + margin-top: 4px; +} + +.link { + padding: 0; + border: none; + background: transparent; + color: var(--accent-text); + font-size: 12px; +} + +.link:hover { + text-decoration: underline; +} + .tip { margin: 4px 0 0; font-size: 12px; diff --git a/apps/desktop/src/components/EmptyState.tsx b/apps/desktop/src/components/EmptyState.tsx index 52cd273..c3ec5df 100644 --- a/apps/desktop/src/components/EmptyState.tsx +++ b/apps/desktop/src/components/EmptyState.tsx @@ -9,18 +9,29 @@ type Props = { children?: ReactNode; /** The buttons one above the other at one width, for more than two. */ isStacked?: boolean; + /** Quieter actions under the buttons, as links. */ + links?: { label: string; onClick: () => void }[]; /** A line under the buttons that teaches a shortcut, e.g. a `KeyTip`. */ tip?: ReactNode; }; /** A column with nothing to show: an icon, a title, a line and actions. */ -export function EmptyState({ icon, title, description, children, isStacked = false, tip }: Props) { +export function EmptyState({ icon, title, description, children, isStacked = false, links, tip }: Props) { return (
{icon}

{title}

{description}

{children &&
{children}
} + {links && ( +
+ {links.map((link) => ( + + ))} +
+ )} {tip}
); diff --git a/apps/desktop/src/components/GetStarted.module.css b/apps/desktop/src/components/GetStarted.module.css new file mode 100644 index 0000000..030fb57 --- /dev/null +++ b/apps/desktop/src/components/GetStarted.module.css @@ -0,0 +1,98 @@ +/* The Get started checklist, a sidebar notice like the update's. Ticks use + * the accent: green belongs to Service State. */ + +.checklist { + display: grid; + gap: 6px; + margin: 0 10px 10px; + padding: 9px 10px 10px 11px; + border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent); + border-radius: 8px; + background: color-mix(in srgb, var(--accent) 8%, var(--surface-raised)); +} + +.header { + display: flex; + align-items: center; + gap: 6px; +} + +.title { + flex: 1; + margin: 0; + font-size: 13px; + font-weight: 600; +} + +.count { + font: 500 11px var(--font-mono); +} + +.close { + display: grid; + padding: 2px; + border: none; + border-radius: 4px; + background: transparent; + color: var(--text-tertiary); +} + +.close:hover { + background: var(--fill); + color: var(--text); +} + +.items { + display: grid; + gap: 3px; + margin: 0; + padding: 0; + list-style: none; +} + +.items li { + display: flex; + align-items: center; + gap: 8px; + min-height: 20px; + font-size: 12px; +} + +.mark { + display: grid; + flex: none; + place-items: center; + width: 13px; + height: 13px; + border: 1.5px solid var(--text-tertiary); + border-radius: 50%; +} + +.done .mark { + border-color: var(--accent); + background: var(--accent); + color: var(--on-accent); +} + +.label { + color: var(--text-secondary); +} + +.action { + padding: 0; + border: none; + background: transparent; + color: var(--text); + font-size: 12px; + font-weight: 500; + text-align: left; +} + +.action:hover { + color: var(--accent-text); + text-decoration: underline; +} + +.optional { + font-weight: 400; +} diff --git a/apps/desktop/src/components/GetStarted.tsx b/apps/desktop/src/components/GetStarted.tsx new file mode 100644 index 0000000..9aebef7 --- /dev/null +++ b/apps/desktop/src/components/GetStarted.tsx @@ -0,0 +1,124 @@ +import { useEffect, useState } from "react"; +import { commands, type Id } from "../bindings"; +import type { CoreView } from "../core"; +import { + CHECKLIST_TITLE, + type ChecklistItem, + checklistItems, + hasRunningService, + isAnyAgentConnected, + isChecklistShown, + updateOnboarding, + useOnboarding, +} from "../onboarding"; +import { showSheet, useUi } from "../ui"; +import { CheckIcon, ClearIcon } from "./Icons"; +import styles from "./GetStarted.module.css"; + +type Props = { + view: CoreView; + /** The Project shown in the window, where Add a service goes first. */ + selectedProjectId: Id | null; + onSelectProject: (projectId: Id) => void; +}; + +/** + * The Get started checklist, at the foot of the sidebar once there is a + * Project: each row ticks from what is true, an open row takes the user + * there. It goes away for good when every row is ticked or it is closed. + */ +export function GetStarted({ view, selectedProjectId, onSelectProject }: Props) { + const onboarding = useOnboarding(); + const isShown = onboarding !== null && isChecklistShown(onboarding, view); + const hasConnectedAgent = useHasConnectedAgent(isShown); + const isRunning = hasRunningService(view); + const items = onboarding ? checklistItems(view, onboarding, hasConnectedAgent) : []; + const isComplete = items.length > 0 && items.every((item) => item.isDone); + + useEffect(() => { + if (isShown && isRunning && !onboarding?.hasStartedService) updateOnboarding({ hasStartedService: true }); + }, [isShown, isRunning, onboarding]); + useEffect(() => { + if (isShown && isComplete) updateOnboarding({ isChecklistDone: true }); + }, [isShown, isComplete]); + + if (!isShown || isComplete) return null; + const doneCount = items.filter((item) => item.isDone).length; + const act = (item: ChecklistItem) => { + if (item.step === "agents") { + showSheet({ kind: "connectAgents" }); + return; + } + const selected = view.projects.find((project) => project.id === selectedProjectId); + if (item.step === "service") { + const target = selected?.services.length === 0 ? selected : view.projects.find((project) => project.services.length === 0); + if (target) showSheet({ kind: "detectServices", projectId: target.id }); + } else if (item.step === "start") { + const target = selected?.services.length ? selected : view.projects.find((project) => project.services.length > 0); + if (target) onSelectProject(target.id); + } + }; + + return ( +
+
+

{CHECKLIST_TITLE}

+ + {doneCount} of {items.length} + + +
+
    + {items.map((item) => ( +
  • + + {item.isDone ? ( + + {item.title} + , done + + ) : ( + + )} +
  • + ))} +
+
+ ); +} + +/** + * Whether any agent has localhost's server, read while the checklist shows + * and again each time a sheet closes, as Connect your agents is one. + */ +function useHasConnectedAgent(isShown: boolean): boolean { + const { sheet } = useUi(); + const [isConnected, setIsConnected] = useState(false); + const isSheetOpen = sheet !== null; + useEffect(() => { + if (!isShown || isSheetOpen) return; + let isCurrent = true; + void commands.agentStatuses().then((agents) => isCurrent && setIsConnected(isAnyAgentConnected(agents))); + return () => { + isCurrent = false; + }; + }, [isShown, isSheetOpen]); + return isConnected; +} diff --git a/apps/desktop/src/components/Onboarding.test.tsx b/apps/desktop/src/components/Onboarding.test.tsx new file mode 100644 index 0000000..d6f54a7 --- /dev/null +++ b/apps/desktop/src/components/Onboarding.test.tsx @@ -0,0 +1,96 @@ +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { viewFromSnapshot } from "../core"; +import { resetOnboarding, startOnboarding } from "../onboarding"; +import { project, service, status } from "../test/fixtures"; +import { currentUi, resetUi } from "../ui"; +import { GetStarted } from "./GetStarted"; +import { Welcome } from "./Welcome"; + +const commands = vi.hoisted(() => ({ + onboarding: vi.fn(), + saveOnboarding: vi.fn(async () => null), + agentStatuses: vi.fn(async () => [] as { connection: string }[]), +})); +vi.mock("../bindings", () => ({ commands })); + +const fresh = { hasSeenWelcome: false, isChecklistDone: false, hasStartedService: false }; + +async function launch(onboarding = fresh) { + commands.onboarding.mockResolvedValue({ onboarding, hasOpenedBefore: false }); + await act(() => startOnboarding(0)); +} + +afterEach(() => { + resetOnboarding(); + resetUi(); + vi.clearAllMocks(); +}); + +describe("Welcome", () => { + it("walks through Project, Service and Port, and ends in Add Project…", async () => { + await launch(); + render(); + expect(screen.getByRole("heading", { name: "A project is a folder" })).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Continue" })); + expect(screen.getByRole("heading", { name: "A service is a command that keeps running" })).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Continue" })); + expect(screen.getByRole("heading", { name: "The port tells localhost it’s up" })).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "Add Project…" })); + expect(currentUi().sheet).toEqual({ kind: "addProject" }); + expect(commands.saveOnboarding).toHaveBeenLastCalledWith({ ...fresh, hasSeenWelcome: true }); + }); + + it("is skipped for good from any step, Escape too", async () => { + await launch(); + render(); + fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" }); + expect(currentUi().sheet).toBeNull(); + expect(commands.saveOnboarding).toHaveBeenLastCalledWith({ ...fresh, hasSeenWelcome: true }); + }); +}); + +describe("GetStarted", () => { + const shop = project("Shop", 0, [service("Web")]); + const blog = project("Blog", 1); + + it("ticks what is done and opens what isn't", async () => { + await launch({ ...fresh, hasSeenWelcome: true }); + const view = viewFromSnapshot({ projects: [blog], statuses: [], projectStates: [] }); + render(); + + expect(screen.getByText("1 of 4")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Add a service" })); + expect(currentUi().sheet).toEqual({ kind: "detectServices", projectId: blog.id }); + fireEvent.click(screen.getByRole("button", { name: "Connect your agents (optional)" })); + expect(currentUi().sheet).toEqual({ kind: "connectAgents" }); + }); + + it("remembers the first Running Service, and goes away once every row is ticked", async () => { + await launch({ ...fresh, hasSeenWelcome: true }); + commands.agentStatuses.mockResolvedValue([{ connection: "connected" }]); + const view = viewFromSnapshot({ projects: [shop], statuses: [status(shop.services[0].id, "running")], projectStates: [] }); + const { container } = render(); + + await waitFor(() => expect(container.innerHTML).toBe("")); + expect(commands.saveOnboarding).toHaveBeenCalledWith({ hasSeenWelcome: true, hasStartedService: true, isChecklistDone: false }); + expect(commands.saveOnboarding).toHaveBeenLastCalledWith({ hasSeenWelcome: true, hasStartedService: true, isChecklistDone: true }); + }); + + it("closes for good", async () => { + await launch({ ...fresh, hasSeenWelcome: true }); + const view = viewFromSnapshot({ projects: [shop], statuses: [], projectStates: [] }); + const { container } = render(); + fireEvent.click(screen.getByRole("button", { name: "Hide Get Started" })); + expect(container.innerHTML).toBe(""); + expect(commands.saveOnboarding).toHaveBeenLastCalledWith({ ...fresh, hasSeenWelcome: true, isChecklistDone: true }); + }); + + it("shows nothing to someone who used localhost before", async () => { + await launch({ hasSeenWelcome: true, isChecklistDone: true, hasStartedService: false }); + const view = viewFromSnapshot({ projects: [shop], statuses: [], projectStates: [] }); + const { container } = render(); + expect(container.innerHTML).toBe(""); + }); +}); diff --git a/apps/desktop/src/components/ServicesColumn.tsx b/apps/desktop/src/components/ServicesColumn.tsx index 5761c78..7d651da 100644 --- a/apps/desktop/src/components/ServicesColumn.tsx +++ b/apps/desktop/src/components/ServicesColumn.tsx @@ -6,6 +6,7 @@ import { type CoreView, serviceStatus } from "../core"; import type { ServiceSelection } from "../selection"; import { isActive, isManual, isWarning, projectServicesSummary, rowSummary, rowSummaryHelp, serviceRowLabel } from "../status"; import { SHORTCUTS, shortcutLabel } from "../keyboard"; +import { SERVICE_CONCEPT } from "../onboarding"; import { showAlert, showSheet } from "../ui"; import { EmptyState } from "./EmptyState"; import { ArrowUpRightIcon, LayersIcon, PlayIcon, PlusIcon, StopIcon, TerminalIcon } from "./Icons"; @@ -51,7 +52,7 @@ export function ServicesColumn({ project, view, selection, onSelect, place = thi } title="No Services" - description="A service is a command that runs in this project, like “pnpm dev”." + description={SERVICE_CONCEPT} > +