diff --git a/CLAUDE.md b/CLAUDE.md index 8fafdb6..aa77db7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,14 +16,14 @@ Planning tool for beginners building web apps with AI builders. A deterministic ## Map - `data/` is the product's knowledge. `src/engine/load.ts` parses it with `schema.ts`; `integrity.ts` holds the cross-file checks `data.test.ts` enforces. -- `src/engine/talk.ts` builds the brief for talking one part through (connection, setup, checks, cost, facts, alternatives with verdicts, the note), answers from it without Claude (`answerFromFacts`), and drafts notes. `src/ai/talk.ts` asks Claude with that brief; `src/app/api/talk` falls back to the facts. `src/components/AskPanel.tsx` is the one place to talk to AI: a chat pane docked on the left of the canvas (Cmd+K, the Ask button, double-click, right-click "Ask about this"), one conversation per plan, with starters when it's empty and a composer whose answerer menu sends each message to a terminal agent, a built-in AI (with a model picker beside it), or StackWise's facts. On a window 1100px or wider a left panel (Overview, Parts, Checklist, Project, Learn) floats beside it (`.ws[data-ask="open"] .ws-float--left`); narrower than that, opening one closes the other (`roomForBoth`, `openPanel`, `toggleAsk` in Workspace). While the pane opens or closes, `data-settling` on `.ws` turns on 240ms transitions for the canvas, bar, dock, sheet and panel, so nothing pops; dragging the pane's edge stays immediate. `NoteEditor.tsx` is the note, in Details and in a connection. +- `src/engine/talk.ts` builds the brief for talking one part through (connection, setup, checks, cost, facts, alternatives with verdicts, the note), answers from it without Claude (`answerFromFacts`), and drafts notes. `src/ai/talk.ts` asks Claude with that brief; `src/app/api/talk` falls back to the facts. `src/components/AskPanel.tsx` is the one place to talk to AI: a chat pane docked on the left of the canvas (Cmd+K, the Ask button, double-click, right-click "Ask about this"), one conversation per plan, with starters when it's empty and a composer whose answerer menu sends each message to a terminal agent, a built-in AI (with a model picker beside it), or StackWise's facts. The model bubble shows the model's name with a note (`1M`, `plan`); through Claude Code it reads Claude Code's own setting, alias or id (`describeAgentModel` in `answerers.ts`), lists every model StackWise knows and the context window, and writes the pick back the same way. The bar's nav buttons go to Projects, Settings and the docs. Its header is a sidebar's: the hide toggle first (after the traffic lights in the app), then back and forward (the router's history), and at the right Past chats and New chat; no title. New chat empties the pane: it sets `plan.chatSince`, and agents' messages and changes from before it stay out of the current chat (the shared plan's log is untouched). The old conversation goes to `plan.pastChats` with copies of what agents said in it (20 at most, titled by its first message, browser-only like `chat`); the newest three stay whole and older ones compact to their questions and the first sentence of each answer (`compactSummary`). Past chats reopens one, putting the current one away the same way; a compacted one comes back as its summary. The bar beside it keeps the StackWise mark; everything on the bar sits in the left cluster except the AI pill, Ask and Export. On a window 1100px or wider a left panel (Overview, Parts, Checklist, Project) floats beside it (`.ws[data-ask="open"] .ws-float--left`); narrower than that, opening one closes the other (`roomForBoth`, `openPanel`, `toggleAsk` in Workspace). While the pane opens or closes, `data-settling` on `.ws` turns on 240ms transitions for the canvas, bar, dock, sheet and panel, so nothing pops; dragging the pane's edge stays immediate. `NoteEditor.tsx` is the note, in Details and in a connection. - `src/engine/wiring.ts` turns a stack into connections and the environment variables that travel along each one (names, where each value comes from, whether the browser can read it), plus the `.env` file text. It never holds a value. - `src/engine/evaluate.ts` produces verdicts. `score.ts` ranks and searches (branch and bound, tested against brute force; domains rank on first-year and renewal price, payments on the fee from a $20 sale). `cost.ts` adds yearly and one-time costs (domains, `planning.json` `fees`) and counts a shared plan once (`shared_plans`, or one option in two parts). `followups.ts` picks questions. `stats.ts` turns facts into the stats on cards, nodes, Details, Compare and the strip above the canvas. `cost.ts`, `spec.ts`, `checklist.ts`, `decisions.ts`, `share.ts`, `staleness.ts`, `summary.ts`, `prefill.ts` do what their names say. - `data/logos.json` says where each logo comes from (Simple Icons slug or the service's site); `scripts/logos.ts` fetches them into `public/logos/`, which is committed. `Logo` in `src/components/ui.tsx` falls back to a letter if a file is missing. - `src/ai/` is server-only: `config.ts` (model, client, errors), `providers.ts` (the registry of built-in AIs: Claude, OpenAI, Gemini, and Ollama on this computer; each has a key name, a model name (`STACKWISE_MODEL`, `OPENAI_MODEL`, ...) and the models Settings offers; adding a model is one entry; Ollama stays off until `OLLAMA_MODEL` is set; answers are checked against the same Zod schemas). The Claude model is `aiModel()` in `config.ts`, read on every call so a pick in Settings applies at once, `prefill.ts`, `explain.ts`, `talk.ts` (each has a Claude path and a `provider*` path), `rate-limit.ts`. Routes in `src/app/api/` take an optional `provider`, pick the first with a key (Claude first) when it's left out, and always fall back to keywords or a template. -- `src/components/store.ts` is all plan state as a pure reducer (plans, undo/redo, import, migration from v1); `usePlans.ts` wires it to the engine. `answerers.ts` is the one list of who can answer (terminal agents, built-in AIs, StackWise facts), read by `ConnectPanel.tsx` (the first screen and the connection pill in the top bar), and `AskPanel.tsx`. `templates.ts` holds the starting points by kind of app (web, iOS, Android, both, AI, store, internal tool), applied with `applyTemplate`. `AddPart.tsx` is the n8n-style picker (A key, the + in the dock and on the app card). `Workspace.tsx` puts the canvas full screen and floats everything over it: the top bar, the dock, one left panel (Overview, Parts, Checklist, Learn), Details on the right, the planner sheet, the Ask panel, and the right-click menus (built there, rendered by `ContextMenu.tsx`). +- `src/components/store.ts` is all plan state as a pure reducer (plans, undo/redo, import, migration from v1); `usePlans.ts` wires it to the engine. `answerers.ts` is the one list of who can answer (terminal agents, built-in AIs, StackWise facts), read by `ConnectPanel.tsx` (the first screen and the connection pill in the top bar), and `AskPanel.tsx`. `templates.ts` holds the starting points by kind of app (web, iOS, Android, both, AI, store, internal tool), applied with `applyTemplate`. `AddPart.tsx` is the n8n-style picker (A key, the + in the dock and on the app card). `Workspace.tsx` puts the canvas full screen and floats everything over it: the top bar, the dock, one left panel (Overview, Parts, Checklist, Project), Details on the right, the planner sheet, the Ask panel, and the right-click menus (built there, rendered by `ContextMenu.tsx`). - `src/local/` is this computer: `home.ts` (`~/.stackwise` or `STACKWISE_HOME`: `profile.json`, `library.json`, `plans/`, `isDesktop`, `MCP_URL`), `scan.ts` (projects found one level under the profile's folders), `agents.ts` (which coding agents are installed, from `which` and `--version`, and whether Claude Code points at StackWise, read from `~/.claude.json`). Routes: `/api/profile`, `/api/library` (the browser store's copy of every plan goes to disk; `src/components/library.ts` merges the two, newest per plan wins, and `savedStore.ts` pushes and pulls), `/api/projects`, `/api/agents` (connect runs `claude mcp add --transport http --scope user stackwise `). -- `src/components/Shell.tsx` and `src/app/shell.css` are the sidebar pages: `/projects` (`ProjectsView.tsx`: your plans, found projects, examples; rendered on the server from `readDiskLibrary` and `readMe` in `src/local/`, then the browser's copy of the store joins in with `adoptLibrary`, so the page comes up whole), `/settings` (`SettingsView.tsx`: sections picked from a list on the left and kept in the URL hash: Account, General, Appearance, Models (who answers in Ask; a key and a model per built-in AI, both saved through `/api/keys`), Agents (coding agent cards, Connect, the MCP server)), `/learn` (`LearnView.tsx`, with its table of contents where Settings has its section list), and `/review`. The canvas stays full screen on `/`. +- `src/components/Shell.tsx` and `src/app/shell.css` are the sidebar pages: `/projects` (`ProjectsView.tsx`: your plans, found projects, examples; rendered on the server from `readDiskLibrary` and `readMe` in `src/local/`, then the browser's copy of the store joins in with `adoptLibrary`, so the page comes up whole), `/settings` (`SettingsView.tsx`: sections picked from a list on the left and kept in the URL hash: Account, General, Appearance, Models (who answers in Ask; a key and a model per built-in AI, both saved through `/api/keys`), Agents (coding agent cards, Connect, the MCP server)), `/docs` (`src/app/docs/`: one document in two groups. Learn first, from `data/learn.json`: Start here (the layers), Parts of an app (one entry per part, `#part-`), Glossary (`#term-`); then the project's docs, the README and docs/*.md rendered with `marked` on the server, one section per file, headings given ids and shown as chips (folded past 16), links to other docs rewritten to their section; `electron/pack.cjs` copies the Markdown into the bundle so the page works in the app; `/learn` redirects there and the hash comes along), and `/review`. A page's own sections (Settings' Account, General...; the docs' files) go in the sidebar under the pages through `Shell`'s `sections` prop. The canvas stays full screen on `/`. - `electron/main.cjs` starts the standalone server (packaged: `Resources/standalone/server.js` run with `ELECTRON_RUN_AS_NODE`; in development, `pnpm dev`), waits for it, opens the window and the menu bar item, and kills the server's process group on quit. `preload.cjs` sets `html[data-desktop]`, which the CSS uses for the title bar inset. `after-pack.cjs` copies the standalone into the bundle; `electron/package.json` is the builder project (no dependencies, so only four files are packed). - `src/engine/layers.ts` is the four layers around the app (runs, people, data, outside): `layerOf`, `layeredLayout` (tidy up) and `layerBox` (the zone drawn behind each layer, a `zone` node in `PlanCanvas.tsx` that nothing can select or drag). - `src/engine/narrate.ts` turns two moments of a plan into the chat's narration of a change: what changed, as if the person typed it, then what it did (parts and why, checks that appeared or went away, verdict, cost), from `planDiff` and the facts alone. `Workspace` keeps the last moment in a ref and posts the two turns on every plan change (not on a plan switch). @@ -67,8 +67,9 @@ Planning tool for beginners building web apps with AI builders. A deterministic - The canvas fits only after React Flow has measured every node (`AutoFit` reads the store) and never zooms past 100%. Fitting on `useNodesInitialized` alone ran before new nodes had sizes and left the canvas zoomed in on the old ones. Parts are spaced evenly among the visible ones, on an ellipse that grows with their count, until someone moves them. - Node positions are middles (`nodeOrigin={[0.5, 0.5]}`), but React Flow hands back the top left corner in `onNodeDragStop`, so `land()` adds half the measured size. Without that every part hops up and left by half its size as it lands. Controls inside a node need `nodrag` (and `nowheel` for anything that scrolls) or pressing them starts a drag. - Moving a part and tidying up are not undoable, like checking a box: undo stays about the plan. `plan.layout` is per plan, lives only in the browser, and is not in `SharedPlan`, so Claude can't move things. +- Chat text in the pane goes through `src/components/chatText.ts`: headings (# lines, all-bold lines, short lines in capitals), lists, code fences, **bold** and `code`, as data the pane turns into elements, never HTML. A reply over about 130 words or 12 lines folds behind "Show more". Agent activity shows as a card only when it changed the plan or the project (`isChangeActivity`: update_plan, a merged plan file, files written); its lookups in StackWise fold into one quiet "Checked StackWise: ..." line per run, each summary once (`foldLookups`). Paired agents are told to write for the narrow pane (`REPLY_STYLE` in `pairing.ts`, carried by the pair prompt, `send_message`'s description and every message `wait_for_message` returns, so a session started before a change still gets it). - Two-way agent chat: messages live in the shared plan record (`~/.stackwise/plans/.json`, `messages` and `agents`), not in the browser store. `wait_for_message` polls the file every second for up to 4 minutes; `/api/mcp` stays in JSON response mode, so the HTTP request just stays open (progress pings only reach stdio clients). A wait records a `waitId`, and an older call for the same agent gives up without taking messages once a newer one starts. Test it with `curl` against `/api/mcp` (`tools/call` works without `initialize` in stateless mode). -- The built-in AI's conversation is one per plan (`plan.chat`, each turn tagged `about`), migrated from the old per-part `threads`. `/api/talk` gets only the last 20 turns about the same part. `factsOnly` on `/api/talk` and `/api/explain` makes "StackWise facts" in the Answering menu skip Claude even with a key. +- The built-in AI's conversation is one per plan (`plan.chat`, each turn tagged `about`), migrated from the old per-part `threads`; New chat moves it to `plan.pastChats`. `/api/talk` gets only the last 20 turns about the same part. `factsOnly` on `/api/talk` and `/api/explain` makes "StackWise facts" in the Answering menu skip Claude even with a key. - Notes are part of `SharedPlan` (`notes`, defaulting to `{}` so older links and plan files still open) and go everywhere a plan goes. The built-in AI's conversation (`plan.chat`) stays in the browser. Typing a note (`editNote`) isn't undoable; accepting a suggested note or switch (`useNote`, `useSwap`) is. - Claude never replays earlier turns as assistant messages in `/api/talk`: each question is one request with the transcript as data, so trimming or clearing a conversation can't break thinking-block rules. A suggested switch must be one of `swappable(brief)` (the schema is an enum), and the page recomputes its verdict with the rules before showing it. - Lines are a custom `wire` edge that reads live node positions (`useInternalNode`) and finds its own ends (`src/components/wire.ts`), so nodes carry one hidden source and one hidden target handle. Labels are HTML buttons in `EdgeLabelRenderer` with `nodrag nopan`. @@ -94,5 +95,8 @@ Planning tool for beginners building web apps with AI builders. A deterministic - Side panels are 380px (Details) and 360px (left), 330px under 900px. Anything new in Details or the palette needs to wrap; long URLs and env var names in the checklist use `overflow-wrap: anywhere`. - Never run `claude mcp get` or `claude mcp list` from inside the server: Claude Code health-checks StackWise's MCP address while answering, and the request that spawned it is holding the server, so both wait forever. `/api/agents` reads `~/.claude.json` instead, and every other spawn is async. - The Mac app: `extraResources` in electron-builder leaves out `node_modules`, so `after-pack.cjs` copies the standalone into the bundle itself. pnpm's symlinks have to stay symlinks (Node resolves a package's dependencies from where the link points; copied as plain folders, next loses `@swc/helpers`), so `pack.cjs` copies with `cp -R` and makes every absolute link relative. Test the packaged server from outside the repo (copy the .app somewhere else first): inside it, a missing `node_modules` resolves to the repo's and hides the problem. +- Next's output file tracing follows every `fs` read it can evaluate, and copies what it finds into the standalone build. Two shapes bite. A known folder with a variable file (`path.join(process.cwd(), doc.file)`, the docs page) traces the whole working folder: `.git`, `release/` with the last dmg, `CLAUDE.local.md`, and the dmg went from 135 MB to 555 MB. A folder it can't see (a parameter, the home folder) becomes a `**/` glob over the repo, which matched the copies of `data/` inside `release/`, the empty `.git` and the old `.stackwise/`. So: the docs read starts from `docsRoot()` in `src/app/docs/page.tsx`, a lookup the bundler can't fold and the tracer can't evaluate (a plain `x || process.cwd()` was folded back to `process.cwd()`); `next.config.ts` excludes `.git`, `release/` and `.stackwise/` from every trace in standalone mode; `pack.cjs` copies `data/`, `public/`, the docs and README itself and fails the build if `.git` or `release` turn up in the standalone. Run `pnpm app:build` as one command: `node electron/pack.cjs | tail` followed by `&&` hides its exit code and the builder packs the bad folder. +- In the app a 48px strip across the top of the window (`html[data-desktop] .ws::before`) is the drag handle. It's `pointer-events: none`: at z-index 29 it sat over the chat pane's header and took the hide button's clicks. The drag region still comes from its box, with the no-drag controls under it (`.ws-bar > *`, `.ws-ask__top > *`) cut out. In full screen macOS hides the traffic lights: `main.cjs` sends `fullscreen` on the window's full-screen events and `preload.cjs` sets `data-fullscreen`, which drops the bars' insets (`display-mode: fullscreen` is the fallback). +- Checking the app window over its debug port (`pnpm exec electron . --remote-debugging-port=9222`, scripts in the session's scratchpad): while the window is hidden behind others, CSS animations don't advance (the chat pane sits a full width off-screen at the slide-in's first frame) and CDP mouse events aren't processed. Finish animations first (`document.getAnimations().forEach((a) => a.finish())`), hit-test with `elementFromPoint`, and drive controls with `.click()`; a real click needs the window in front. - The Mac app's window loads its page only after the server answers `/api/status`, and retries a load that fails. A `loadURL` sent while the server was still starting failed with ECONNREFUSED, and Electron shows nothing for a failed load: a blank gray window that never recovers. The window is created visible; created hidden and shown on `ready-to-show`, a page that never painted never fired it. - The browser store is a cache of `~/.stackwise`; the files are the record. A plan an agent changed (`updatedBy: "claude"`, newer) isn't overwritten by the browser's older copy, and deleting a plan has to go to disk too (`deletePlanOnDisk`), or it comes back on the next pull. Nothing is pushed to disk before the page has pulled the library once (`synced` in `savedStore.ts`): a fresh browser's blank starting plan, saved a moment after mount, used to land in the library as one more "Untitled app". A plan made on the Projects page is flushed (`flushStore`) before the canvas opens it, or the canvas's pull would drop it as blank. diff --git a/README.md b/README.md index f68ce54..4e53d4d 100644 --- a/README.md +++ b/README.md @@ -58,23 +58,23 @@ Everything works without an API key. For an AI that reads your description, answ ## Five minutes in -1. **Projects.** The first page: your plans, the projects StackWise found under your folders (plan one in a click), and examples to open. -2. **Describe your app**, or pick a kind of app (web, iOS, Android, both, AI app, online store, internal tool). Confirm each guess; StackWise shows the exact words behind every one. Only the follow-up questions that would change the plan are asked. Pick a priority (spend $0, launch fast, learn, ready to grow), an audience size and your builder. -3. **Read the canvas.** Your app in the middle, with its parts in four layers: where it runs (hosting, domain), people (login, payments, email, a phone app), data (database, files, background jobs), and outside services (AI, scraping, data sources, automations, analytics, monitoring). A check on a line means the connection works, `!` a warning, a cross that it doesn't, `?` that a fact is missing. A light flows along the lines that work. Drag any part where you want it; Tidy up puts the layers back. -4. **Click anything.** A card opens Details: why it was picked, every check with its reason and fix, the cost at your size, a comparison with the alternatives, and the facts behind it with their sources. A line shows what travels on it: the environment variables your code reads to reach that service. Right-click for everything else: ask, swap, let StackWise pick, learn, build this with your agent. -5. **Ask** (Cmd+K). A chat pane beside the canvas, one conversation per plan. Pick who answers in the composer: a coding agent in your terminal, a built-in AI with a key (and which of its models), or StackWise's own facts, which need nothing. -6. **The dock.** Overview (problems, close calls, accounts, cost at every size), Parts (every service by part, dragged onto the canvas; 101 options, 80 fully researched), Checklist (accounts, keys and build steps to tick off) and Learn (what each part of an app is, what matters when choosing, a glossary). -7. **Settings.** Account (your name, where plans live), General (what a new plan starts with, the folders StackWise looks in), Appearance, Models (who answers in Ask; a key and a model per built-in AI) and Agents (your coding agents, one Connect button for Claude Code, and the MCP server's status). -8. **Build it.** Connect your agent and tell it to build from the plan, or export a project pack: the spec, setup, decisions, tasks with their tests, `.env.example`, and for Claude Code an agent per part, skills and `.mcp.json`. +1. Projects. The first page: your plans, the projects StackWise found under your folders (plan one in a click), and examples to open. +2. Describe your app, or pick a kind of app (web, iOS, Android, both, AI app, online store, internal tool). Confirm each guess; StackWise shows the exact words behind every one. Only the follow-up questions that would change the plan are asked. Pick a priority (spend $0, launch fast, learn, ready to grow), an audience size and your builder. +3. Read the canvas. Your app in the middle, with its parts in four layers: where it runs (hosting, domain), people (login, payments, email, a phone app), data (database, files, background jobs), and outside services (AI, scraping, data sources, automations, analytics, monitoring). A check on a line means the connection works, `!` a warning, a cross that it doesn't, `?` that a fact is missing. A light flows along the lines that work. Drag any part where you want it; Tidy up puts the layers back. +4. Click anything. A card opens Details: why it was picked, every check with its reason and fix, the cost at your size, a comparison with the alternatives, and the facts behind it with their sources. A line shows what travels on it: the environment variables your code reads to reach that service. Right-click for everything else: ask, swap, let StackWise pick, learn, build this with your agent. +5. Ask (Cmd+K). A chat pane beside the canvas, one conversation per plan. Pick who answers in the composer: a coding agent in your terminal, a built-in AI with a key (and which of its models), or StackWise's own facts, which need nothing. +6. The dock. Overview (problems, close calls, accounts, cost at every size), Parts (every service by part, dragged onto the canvas; 101 options, 80 fully researched) and Checklist (accounts, keys and build steps to tick off). +7. Settings. Account (your name, where plans live), General (what a new plan starts with, the folders StackWise looks in), Appearance, Models (who answers in Ask; a key and a model per built-in AI) and Agents (your coding agents, one Connect button for Claude Code, and the MCP server's status). +8. Build it. Connect your agent and tell it to build from the plan, or export a project pack: the spec, setup, decisions, tasks with their tests, `.env.example`, and for Claude Code an agent per part, skills and `.mcp.json`. ## How it works -1. **Facts.** Every service is a JSON file in `data/options/` with facts a person can check: a free plan's limit, a price, whether it can push live updates to browsers. Each fact has a source URL, the date it was checked, and a status. New facts are drafts until someone reviews them on `/review`. -2. **Rules.** `data/rules/` say what the facts mean together: a host that falls asleep can't run background jobs; a framework that renders on the server needs a host that runs servers; two Firebase parts share one project. A rule reads at most two parts, and a missing fact makes a check "unknown", never "works". -3. **Search.** For your answers, size and priority, StackWise scores every stack (branch and bound, tested against brute force) and shows the best one with its close calls, so you see what nearly won and why. -4. **The canvas** is a view of that result. Swap a part and the rules run again; every line's mark is a verdict, not a drawing. -5. **AI, optionally**, has three jobs: read your description (its guesses must quote words that are really there), explain the computed plan, and draft new facts for review. It never decides compatibility. -6. **Your agent** gets the plan over MCP: the same engine, 15 tools, no verdicts of its own. +1. Facts. Every service is a JSON file in `data/options/` with facts a person can check: a free plan's limit, a price, whether it can push live updates to browsers. Each fact has a source URL, the date it was checked, and a status. New facts are drafts until someone reviews them on `/review`. +2. Rules. `data/rules/` say what the facts mean together: a host that falls asleep can't run background jobs; a framework that renders on the server needs a host that runs servers; two Firebase parts share one project. A rule reads at most two parts, and a missing fact makes a check "unknown", never "works". +3. Search. For your answers, size and priority, StackWise scores every stack (branch and bound, tested against brute force) and shows the best one with its close calls, so you see what nearly won and why. +4. The canvas is a view of that result. Swap a part and the rules run again; every line's mark is a verdict, not a drawing. +5. AI, optionally, has three jobs: read your description (its guesses must quote words that are really there), explain the computed plan, and draft new facts for review. It never decides compatibility. +6. Your agent gets the plan over MCP: the same engine, 15 tools, no verdicts of its own. On disk: diff --git a/data/learn.json b/data/learn.json index 540c246..977277e 100644 --- a/data/learn.json +++ b/data/learn.json @@ -82,7 +82,7 @@ "what": "Your app's own address, like yourapp.com, instead of the free one your host gives you.", "why": "People trust and remember a real name, and email services need a verified domain to send as you.", "choosing": [ - "The renewal price, not just the discounted first year.", + "The renewal price, after the discounted first year.", "Is WHOIS privacy free?", "Can you manage DNS records in the same account for free?", "How easy is it to transfer out later?" @@ -147,7 +147,7 @@ "why": "Uploads need a durable home and a way to serve them only to the people allowed to see them.", "choosing": [ "Can browsers upload straight to storage with a signed URL?", - "Does it charge for downloads (egress), not just storage?", + "Does it charge for downloads (egress) as well as storage?", "Are files served through a CDN?", "How do you keep private files private?" ], @@ -174,7 +174,7 @@ ], "watch_for": [ "Putting the secret key in browser code.", - "Unlocking access on the checkout redirect instead of the webhook. Redirects get skipped; webhooks arrive.", + "Granting access on the checkout redirect instead of the webhook. Redirects get skipped; webhooks arrive.", "Not verifying webhook signatures, so anyone can fake a payment." ], "terms": ["merchant-of-record", "sales-tax", "subscription", "secret-key", "publishable-key", "webhook", "environment-variable", "portability"], @@ -275,7 +275,7 @@ "why": "It replaces guesses with numbers: are people finding the app, and where do they give up?", "choosing": [ "Does it use cookies? That decides whether you need a consent banner.", - "Can it track events like sign-ups, not just page views?", + "Can it track events like sign-ups as well as page views?", "Is the free plan permanent or a trial?", "Can you export your data if you switch?" ], @@ -316,7 +316,7 @@ "what": "Whether your app could also ship as a phone app in the App Store or Google Play.", "why": "Phone apps are built differently, and not every login or database service works from one.", "choosing": [ - "Do your login and database have phone SDKs, not just web ones?", + "Do your login and database have phone SDKs as well as web ones?", "React Native (shares patterns with web code) or fully native?", "What do store rules say about your payments?", "Does sign-in with Google or Apple work inside the app?" @@ -430,7 +430,7 @@ "webhook": { "term": "Webhook", "plain": "A message another service sends to your server when something happens, like a payment succeeding.", - "matters": "Unlocking what someone paid for usually depends on handling this message correctly.", + "matters": "Giving people what they paid for depends on handling this message correctly.", "read_more": [{ "title": "What are webhooks?", "url": "https://zapier.com/blog/what-are-webhooks/", "source": "Zapier" }] }, "relational-database": { @@ -566,7 +566,7 @@ "app-store": { "term": "App store", "plain": "Apple's App Store or Google Play. Both review every app, including how it takes payments and handles data.", - "matters": "Shipping a phone app means planning for review, not just finishing the code.", + "matters": "Shipping a phone app means planning for the store review as well as finishing the code.", "read_more": [{ "title": "App Review Guidelines: payments", "url": "https://developer.apple.com/app-store/review/guidelines/#payments", "source": "Apple Developer" }] }, "oauth": { @@ -634,7 +634,7 @@ "event": { "term": "Event", "plain": "One action someone takes, like signing up or clicking Buy, tracked on its own.", - "matters": "Events tell you whether a feature is used, not just visited." + "matters": "Events tell you whether a feature is used, where page views only say it was opened." }, "cookie-consent": { "term": "Cookie consent", diff --git a/docs/DATA.md b/docs/DATA.md index 76e583b..137f417 100644 --- a/docs/DATA.md +++ b/docs/DATA.md @@ -27,10 +27,10 @@ Everything StackWise knows is in `data/`. Changes go through pull requests, and } ``` -- **Facts** must use a key from `data/facts.json` and a value of the type it defines. -- **Coverage.** `full` promises every fact listed in the slot's `required_facts` (in `data/slots.json`). `partial` options still appear in the palette, marked "not verified yet", and are never auto-picked. -- **Null.** For `first_paid_usd_month`, null means "no monthly plan" on a `full` option. Everywhere else, null means unverified. Facts of type `number` (a domain's prices, a payment service's card fee) can't be null on a `full` option. -- **Provider** groups options that share an account (Supabase database, auth and storage all use `supabase`). Providers listed in `planning.json` under `no_account_providers` don't count as accounts. +- Facts must use a key from `data/facts.json` and a value of the type it defines. +- Coverage. `full` promises every fact listed in the slot's `required_facts` (in `data/slots.json`). `partial` options still appear in the palette, marked "not verified yet", and are never auto-picked. +- Null. For `first_paid_usd_month`, null means "no monthly plan" on a `full` option. Everywhere else, null means unverified. Facts of type `number` (a domain's prices, a payment service's card fee) can't be null on a `full` option. +- Provider groups options that share an account (Supabase database, auth and storage all use `supabase`). Providers listed in `planning.json` under `no_account_providers` don't count as accounts. ## Rules @@ -72,17 +72,17 @@ Every option needs a logo. Each entry says where it comes from, and `pnpm build: } ``` -- **`simple-icons`** draws the brand's mark from the [Simple Icons](https://simpleicons.org) package in its brand color. Near-white brand colors are drawn in ink so they show on white cards. Prefer this when the brand is there. -- **`site`** takes the icon the company's own website declares: apple-touch-icon first, then SVG, then the largest icon, then `/favicon.ico`, then Google's favicon service for sites that refuse scripted requests. Icons marked for dark mode are skipped because they're usually white. +- `simple-icons` draws the brand's mark from the [Simple Icons](https://simpleicons.org) package in its brand color. Near-white brand colors are drawn in ink so they show on white cards. Prefer this when the brand is there. +- `site` takes the icon the company's own website declares: apple-touch-icon first, then SVG, then the largest icon, then `/favicon.ico`, then Google's favicon service for sites that refuse scripted requests. Icons marked for dark mode are skipped because they're usually white. - To add or fix one, write the entry with only `from` and `slug` or `url`, then run `pnpm build:logos -- --only ` and look at it in the palette. `draft:option` fetches the site icon for a new service on its own. - The files are committed, so the app never loads a logo from another site. Logos are trademarks of their owners and are shown only to identify each service. ## Costs beyond the monthly plan -- **Domains** are billed yearly from `com_first_year_usd` and `com_renewal_usd`. They're ranked on those two prices, since no domain is free. -- **Payment services** are ranked on the fee they keep from a typical $20 sale (`card_fee_percent` and `card_fee_fixed_usd`), since none has a monthly plan. -- **`planning.json` `fees`** are costs that come with a part whatever fills it, like the Apple Developer Program for a phone app. Each has a price, `year` or `once`, and a source. -- **`planning.json` `shared_plans`** lists providers whose one paid plan covers every part they fill (Supabase's database, login and storage), so the plan is counted once. The same option in two parts (PostHog for analytics and error monitoring) is always counted once. +- Domains are billed yearly from `com_first_year_usd` and `com_renewal_usd`. They're ranked on those two prices, since no domain is free. +- Payment services are ranked on the fee they keep from a typical $20 sale (`card_fee_percent` and `card_fee_fixed_usd`), since none has a monthly plan. +- `planning.json` `fees` are costs that come with a part whatever fills it, like the Apple Developer Program for a phone app. Each has a price, `year` or `once`, and a source. +- `planning.json` `shared_plans` lists providers whose one paid plan covers every part they fill (Supabase's database, login and storage), so the plan is counted once. The same option in two parts (PostHog for analytics and error monitoring) is always counted once. ## Stats @@ -104,9 +104,9 @@ Neither one marks a fact `verified`. Only a person does. The review page does this one fact at a time: run `pnpm dev`, open `/review` (or "Review facts" in the plan menu), and work down the list with J and K, Y for "Matches the source" and N for "Something's off". -- **What comes first.** The facts the default plans rest on: StackWise plans every template and the Pitchwell example, and for each option they end up with it lists the facts the rules and the ranking read (the part's `required_facts` and the score's criteria). The facts used by the most defaults are at the top. "All" adds every other fact of a fully researched option. The Overview says how many facts behind the open plan are reviewed. -- **"Matches the source"** sets `status` to `"verified"` and adds `"reviewed": ""` under it. Nothing else in the file changes, so the diff is those two lines. -- **"Something's off"** leaves the fact a draft (a verified one goes back to draft) and saves your note in `.stackwise/review-flags.json`, which is gitignored. Fix `value` and `note`, update `retrieved`, then confirm it on the page, which clears the flag. +- What comes first. The facts the default plans rest on: StackWise plans every template and the Pitchwell example, and for each option they end up with it lists the facts the rules and the ranking read (the part's `required_facts` and the score's criteria). The facts used by the most defaults are at the top. "All" adds every other fact of a fully researched option. +- "Matches the source" sets `status` to `"verified"` and adds `"reviewed": ""` under it. Nothing else in the file changes, so the diff is those two lines. +- "Something's off" leaves the fact a draft (a verified one goes back to draft) and saves your note in `.stackwise/review-flags.json`, which is gitignored. Fix `value` and `note`, update `retrieved`, then confirm it on the page, which clears the flag. - `pnpm check:sources --apply` drops `reviewed` from any fact whose value it changes, since the review was of the old value. - The page and `/api/review` only answer StackWise's own page on this computer, and `STACKWISE_PAIRING=off` turns the route off. @@ -116,38 +116,38 @@ By hand it's the same: open the `source`, and if it still says what `value` and All facts are drafts. Research agents wrote the service files on 2026-09-15 and flagged these: -- **Render and Railway `free_plan_commercial_use: false`** was inferred ("not for production", "we recommend Pro"), not taken from an explicit ban. -- **Render `first_paid_usd_month` ($7)** came from third-party trackers because the pricing page wouldn't load for the agent. -- **Lemon Squeezy** relies on secondary sources (its site blocked automated reads) and is in maintenance mode after the Stripe acquisition. -- **Google Gemini `free_plan_covers`** is null because Google doesn't publish fixed free limits, which is why it's `partial`. -- **Fly.io** has no free plan and no monthly plan since 2024; the null price is intentional. -- **Supabase key names**: current quickstarts use `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`. The storage file was corrected to match. -- **MongoDB Atlas `mobile_sdk: false`**: Atlas Device SDK reached end of life on 2025-09-30. -- **Supabase Auth `builtin_email_production_ready: false`**: its built-in email is capped at a few messages an hour and marked not for production. -- **Amazon SES and SendGrid `free_plan_covers: "none"`**: SES's free tier is now time-limited for new accounts, and SendGrid's permanent free plan was replaced by a trial. SES also starts in a sandbox that can only email verified addresses. -- **Postmark's free plan** is 100 emails a month, meant for testing. -- **Upstash QStash `long_running: false`**: it calls your own endpoint, so your host's request time limit still applies, unlike Inngest and Trigger.dev. -- **Expo's free plan** caps builds per month and blocks further builds instead of charging. -- **App store fees in `mobile-app-store-fees`**: $99 a year for the Apple Developer Program and a one-time $25 for Google Play, with sources in the rule. +- Render and Railway `free_plan_commercial_use: false` was inferred ("not for production", "we recommend Pro"), not taken from an explicit ban. +- Render `first_paid_usd_month` ($7) came from third-party trackers because the pricing page wouldn't load for the agent. +- Lemon Squeezy relies on secondary sources (its site blocked automated reads) and is in maintenance mode after the Stripe acquisition. +- Google Gemini `free_plan_covers` is null because Google doesn't publish fixed free limits, which is why it's `partial`. +- Fly.io has no free plan and no monthly plan since 2024; the null price is intentional. +- Supabase key names: current quickstarts use `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`. The storage file was corrected to match. +- MongoDB Atlas `mobile_sdk: false`: Atlas Device SDK reached end of life on 2025-09-30. +- Supabase Auth `builtin_email_production_ready: false`: its built-in email is capped at a few messages an hour and marked not for production. +- Amazon SES and SendGrid `free_plan_covers: "none"`: SES's free tier is now time-limited for new accounts, and SendGrid's permanent free plan was replaced by a trial. SES also starts in a sandbox that can only email verified addresses. +- Postmark's free plan is 100 emails a month, meant for testing. +- Upstash QStash `long_running: false`: it calls your own endpoint, so your host's request time limit still applies, unlike Inngest and Trigger.dev. +- Expo's free plan caps builds per month and blocks further builds instead of charging. +- App store fees in `mobile-app-store-fees`: $99 a year for the Apple Developer Program and a one-time $25 for Google Play, with sources in the rule. Flagged in the second research round (scraping, domains, analytics, error monitoring, hosting costs, PayPal and Polar): -- **Render's free plan changed.** Render's 2026 pricing update cut the free workspace's bandwidth from 100 GB to 5 GB a month, so `free_plan_covers` moved from `up_to_1000` to `up_to_100`. Starter compute is still $7/month; more bandwidth needs the $25 Pro workspace. -- **Railway `custom_domain_free: false`**: the pricing page says the Free plan gets 0 custom domains, while a forum moderator said 1. -- **Vercel, Netlify and Cloudflare `free_plan_sleeps: false`**: request-based functions have cold starts but the app itself never pauses; Fly.io and Cloudflare `custom_domain_free` were inferred from the absence of any domain fee. -- **Polar `first_paid_usd_month: null`**: its paid tiers only lower the fee and are optional. Polar, Lemon Squeezy and Paddle all list 5% + 50 cents. -- **Scraping free plans** are credits, mapped to audience sizes by judgment: Firecrawl (1,000 credits a month), Apify ($5 of monthly credit, 1,000 to 25,000 pages), ScrapingBee (a one-time 1,000-credit trial, not stated as one-time on the page). -- **Browserbase `ai_ready_output: true`** comes from its separate Fetch API, not the hosted browser itself, and its price per 1,000 pages uses Browserbase's own "100 hours is roughly 3,000 page tasks". -- **Jina Reader is `partial`**: its Reader price is behind a login. -- **Vercel Domains is `partial`**: its prices only show in a live search that blocked automated use. -- **Namecheap's $11.28 first year** is a standing sale (list $14.98); Cloudflare's community docs mention a wholesale price increase on 2026-11-01. -- **Monitoring free plans**: Sentry, Rollbar and Honeybadger allow 5,000 errors a month; LogRocket's pricing page now shows only a 14-day trial; Sentry's $29 monthly price was corroborated by trackers because the page only rendered the yearly price; Rollbar's $9 came from its official pricing-for-agents page. -- **Google Analytics `cookies: required`** reflects the standard gtag.js setup; Google's docs say the libraries can run without cookies. +- Render's free plan changed. Render's 2026 pricing update cut the free workspace's bandwidth from 100 GB to 5 GB a month, so `free_plan_covers` moved from `up_to_1000` to `up_to_100`. Starter compute is still $7/month; more bandwidth needs the $25 Pro workspace. +- Railway `custom_domain_free: false`: the pricing page says the Free plan gets 0 custom domains, while a forum moderator said 1. +- Vercel, Netlify and Cloudflare `free_plan_sleeps: false`: request-based functions have cold starts but the app itself never pauses; Fly.io and Cloudflare `custom_domain_free` were inferred from the absence of any domain fee. +- Polar `first_paid_usd_month: null`: its paid tiers only lower the fee and are optional. Polar, Lemon Squeezy and Paddle all list 5% + 50 cents. +- Scraping free plans are credits, mapped to audience sizes by judgment: Firecrawl (1,000 credits a month), Apify ($5 of monthly credit, 1,000 to 25,000 pages), ScrapingBee (a one-time 1,000-credit trial, not stated as one-time on the page). +- Browserbase `ai_ready_output: true` comes from its separate Fetch API, not the hosted browser itself, and its price per 1,000 pages uses Browserbase's own "100 hours is roughly 3,000 page tasks". +- Jina Reader is `partial`: its Reader price is behind a login. +- Vercel Domains is `partial`: its prices only show in a live search that blocked automated use. +- Namecheap's $11.28 first year is a standing sale (list $14.98); Cloudflare's community docs mention a wholesale price increase on 2026-11-01. +- Monitoring free plans: Sentry, Rollbar and Honeybadger allow 5,000 errors a month; LogRocket's pricing page now shows only a 14-day trial; Sentry's $29 monthly price was corroborated by trackers because the page only rendered the yearly price; Rollbar's $9 came from its official pricing-for-agents page. +- Google Analytics `cookies: required` reflects the standard gtag.js setup; Google's docs say the libraries can run without cookies. Found while building the wiring view on 2026-09-15: -- **Twelve researched options have setup steps but name no environment variable**, so the canvas can only say "no environment variable is written down" for them: Cloudflare R2, Crawlee, Expo, Fathom Analytics, Firebase Auth, Firestore, Flutter, Google Analytics 4, LogRocket, Native (Swift and Kotlin), Plausible and Umami Cloud. Firebase and R2 certainly need keys, and the analytics services need a site or measurement id. The names belong in the `env` array of the setup step that hands you the value, taken from the official quickstart. Hosts, frameworks and domain registrars are different: they hold your variables or need none, so an empty list is right for them. -- **Honeybadger `NEXT_PUBLIC_HONEYBADGER_API_KEY`** is public by design (a write-only project key), as Honeybadger's Next.js guide names it. +- Twelve researched options have setup steps but name no environment variable, so the canvas can only say "no environment variable is written down" for them: Cloudflare R2, Crawlee, Expo, Fathom Analytics, Firebase Auth, Firestore, Flutter, Google Analytics 4, LogRocket, Native (Swift and Kotlin), Plausible and Umami Cloud. Firebase and R2 need keys, and the analytics services need a site or measurement id. The names belong in the `env` array of the setup step that hands you the value, taken from the official quickstart. Hosts, frameworks and domain registrars are different: they hold your variables or need none, so an empty list is right for them. +- Honeybadger `NEXT_PUBLIC_HONEYBADGER_API_KEY` is public by design (a write-only project key), as Honeybadger's Next.js guide names it. The framework files (`nextjs`, `react-vite`, `sveltekit`) and `sqlite-file` were written by Claude from each project's docs; their links were checked and all resolve, but the facts are still drafts. diff --git a/docs/DEMO.md b/docs/DEMO.md index 42c0115..f36f5ab 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -2,7 +2,7 @@ One run through StackWise for a video, a class or an interview. It works with no API key and no agent connected; the steps that need Claude Code say so. -**Before you start:** `pnpm dev`, open http://localhost:4310 in a fresh browser profile (or clear site data), and skip Connect. +**Before you start:** open StackWise (the Mac app, or `pnpm dev` and http://localhost:4310), press **New project** on the Projects page, and leave the chat pane open on the left: it narrates every change as you go. ## 0:00 The problem (15 seconds) @@ -20,20 +20,20 @@ One run through StackWise for a video, a class or an interview. It works with no ## 0:35 Read the plan (25 seconds) 1. The canvas: the app in the middle, a card per part, a line per connection with a check. -2. The pill at the top: monthly cost and how many problems. +2. The toolbar at the top: monthly cost and how many problems. The chat pane on the left has already written up what the plan did with each answer. 3. Click **Stripe**. Details shows the stats at this size, the fee per sale, and the check "You handle sales tax", with its source. ## 1:00 Break it on purpose (20 seconds) 1. Right-click **Firestore**, **Switch to**, **SQLite file**. Hosting quietly moves from Netlify to Fly.io: SQLite keeps its data in a file, so StackWise re-plans the host to one with a permanent disk. 2. Right-click **Fly.io**, **Switch to**, **Netlify**, to force the bad pairing. The line between them turns red: "Your data would disappear". Netlify gives the app no permanent disk, so anything people save is lost on the next deploy. The fix and the sources are in Details. -3. Press Cmd+Z twice. It's back. +3. Press Cmd+Z twice. It's back. Each step is in the chat as a line from you and an explanation from the facts. "No AI decided that. A rule read two facts, the host's disk and where the database keeps its data, each with a source, and the search picked around it until I forced it." ## 1:20 Ask (15 seconds) -Right-click **Stripe**, **Ask about this**, and click **Which keys does it need?** The answer comes from StackWise's own facts: the variable names, where each value comes from, and which one the browser can read. +Right-click **Stripe**, **Ask about this**, and press **Which keys does it need?** in the chat pane. With the provider set to StackWise (no AI), the answer comes from StackWise's own facts: the variable names, where each value comes from, and which one the browser can read. Switch the provider bubble to Claude to have a model explain the same brief. ## 1:35 Hand it to a builder (25 seconds) @@ -47,4 +47,4 @@ Right-click **Stripe**, **Ask about this**, and click **Which keys does it need? ## Longer version -Open **All applications** from the plan menu and **Open example** on Pitchwell: a dozen parts, a note on every one, and one warning to walk through. Turn on **Advanced tools** (the wrench in the dock) to show a second service in one part and a line drawn between two parts. +On the **Projects** page, open the Pitchwell example: a dozen parts, a note on every one, and one warning to walk through. Turn on **Advanced tools** (the wrench in the dock) to show a second service in one part and a line drawn between two parts. Settings, Models shows how a key and a model are set per provider; Settings, Agents connects Claude Code in one press. diff --git a/docs/LEARNING.md b/docs/LEARNING.md index b6b9205..aea2563 100644 --- a/docs/LEARNING.md +++ b/docs/LEARNING.md @@ -21,22 +21,27 @@ Facts about services live in JSON files; rules read those facts to decide whethe | 9 | `src/engine/summary.ts`, `src/ai/explain.ts` | The plan brief, explained by a template or by Claude. | | 10 | `src/engine/spec.ts`, `decisions.ts`, `checklist.ts` | The spec pack, the decision record and the build checklist. | | 10b | `src/engine/wiring.ts` | What runs along each line: the environment variables the app reads to reach each service, and the `.env` file text. | -| 10c | `src/engine/talk.ts`, `src/ai/talk.ts` | Talking one part through: the brief for that part, answers from StackWise's facts, or Claude answering from the brief. | -| 11 | `src/components/store.ts` | Every saved plan, undo and redo, share links and imports, as a pure reducer. | -| 12 | `src/components/*` | The workspace: planner, canvas, options, details, Learn, Checklist. | -| 13 | `scripts/*` | Evals, the source checker and the option drafter. | +| 10c | `src/engine/talk.ts`, `src/ai/talk.ts` | Talking one part through: the brief for that part, answers from StackWise's facts, or a model answering from the brief. | +| 10d | `src/engine/buildplan.ts`, `testplan.ts` | The canvas as ordered build tasks, and a test plan for each: what to check, how to keep the real service out, what not to test. | +| 10e | `src/engine/narrate.ts` | What a change did, for the chat pane: the parts that changed and why, the checks that appeared or went away, the cost before and after. | +| 10f | `src/engine/layers.ts` | The four layers the canvas groups parts into: where it runs, people, data, outside services. | +| 11 | `src/components/store.ts` | Every saved plan, undo and redo, share links and imports, as a pure reducer; `~/.stackwise` on disk is the record (`src/local/`). | +| 12 | `src/components/*`, `src/app/*` | The workspace (canvas, chat pane, panels) and the pages (Projects, Settings, Learn, Documentation, Review). | +| 13 | `src/mcp/*` | The MCP server: 15 tools over the engine, pairing with a coding agent, shared plans. | +| 14 | `electron/*` | The Mac app around it all. | +| 15 | `scripts/*` | Evals, the source checker and the option drafter. | ## Following one app through Say the description is: *"A booking app for my barber shop. Customers log in, pick a time, pay a deposit, and upload a photo of the haircut they want. They get a reminder email the day before, and the shop can chat with them."* -1. **Pre-fill.** The planner posts the description to `/api/prefill`. With an API key, Claude answers each question and must quote the words behind every yes or no; `acceptAnswers` throws out any quote that isn't really in the description. Without a key, `prefillFromKeywords` matches keywords instead: "booking" for *saves data*, "log in" for *login*, "pay" for *users pay*, "upload" for *uploads*, "email" for *sends email*, "reminder" for *scheduled tasks*, "chat" for *live updates*. -2. **Confirm.** Guesses show as answers but stay marked, with their evidence. "Looks right, build my plan" confirms them all. Until then the canvas says it's a preview. -3. **Needed slots.** `neededSlots` turns yes answers into parts: login adds Login and Database, paying adds Payments, uploads add File storage, email adds Email, your own address adds Domain name, pulling data from other websites adds Web scraping, and wanting usage numbers or error alerts adds Analytics or Error monitoring. Framework and Hosting are always needed. Background jobs and a phone app are optional parts you add yourself. -4. **Search.** `recommend` tries combinations of fully researched options for those parts and keeps the best total. A blocked pair costs 1000 points, so it loses unless nothing else works. -5. **Verdicts.** For the winning plan, `evaluatePlan` runs every rule. If the host can't run scheduled jobs and there's no jobs service, "No built-in way to run things on a schedule" appears; drag a jobs service onto the canvas and it clears. -6. **Canvas.** Each card shows the worst verdict touching that part. The line from the app shows that part's own checks. Problems between two parts get their own dashed line. -7. **Leaving.** The spec pack lists the stack with its strongest reasons, turns every warning and note with builder guidance into a rule, orders the build, renames environment variables for your framework, and writes a decision record for every part. The Checklist panel tracks the same steps as you do them. +1. Pre-fill. The planner posts the description to `/api/prefill`. With an API key, Claude answers each question and must quote the words behind every yes or no; `acceptAnswers` throws out any quote that isn't really in the description. Without a key, `prefillFromKeywords` matches keywords instead: "booking" for *saves data*, "log in" for *login*, "pay" for *users pay*, "upload" for *uploads*, "email" for *sends email*, "reminder" for *scheduled tasks*, "chat" for *live updates*. +2. Confirm. Guesses show as answers but stay marked, with their evidence. "Looks right, build my plan" confirms them all. Until then the canvas says it's a preview. +3. Needed slots. `neededSlots` turns yes answers into parts: login adds Login and Database, paying adds Payments, uploads add File storage, email adds Email, your own address adds Domain name, pulling data from other websites adds Web scraping, and wanting usage numbers or error alerts adds Analytics or Error monitoring. Framework and Hosting are always needed. Background jobs and a phone app are optional parts you add yourself. +4. Search. `recommend` tries combinations of fully researched options for those parts and keeps the best total. A blocked pair costs 1000 points, so it loses unless nothing else works. +5. Verdicts. For the winning plan, `evaluatePlan` runs every rule. If the host can't run scheduled jobs and there's no jobs service, "No built-in way to run things on a schedule" appears; drag a jobs service onto the canvas and it clears. +6. Canvas. Each card shows the worst verdict touching that part, in one of four layers around the app. The line from the app shows that part's own checks. Problems between two parts get their own dashed line. Every change lands in the chat pane as a line from you and an explanation from the facts (`narrate.ts`). +7. Leaving. The spec pack lists the stack with its strongest reasons, turns every warning and note with builder guidance into a rule, orders the build, renames environment variables for your framework, and writes a decision record for every part. The Checklist panel tracks the same steps as you do them. ## Ideas to be able to explain @@ -66,10 +71,10 @@ Say the description is: *"A booking app for my barber shop. Customers log in, pi ## Try it yourself -1. **Flip a fact.** In `data/options/netlify.json`, set `scheduled_jobs` to `false`, refresh, and plan something with a daily email. Watch the schedule warning appear, then drag Inngest into Background jobs and watch it clear. Put the fact back. -2. **Break the data on purpose.** Delete `persistent_disk` from `data/options/render.json` and run `pnpm check:data`. Read the failure, then restore it. -3. **Add a rule.** Add a capability rule that warns when `needs: ["users_pay"]` and `payments.subscriptions` is `false`. Write its test in `evaluate.test.ts` first. -4. **Grade the baseline.** Write three cases in `evals/prefill-cases.json` and run `pnpm eval:prefill --keywords-only`. +1. Flip a fact. In `data/options/netlify.json`, set `scheduled_jobs` to `false`, refresh, and plan something with a daily email. Watch the schedule warning appear, then drag Inngest into Background jobs and watch it clear. Put the fact back. +2. Break the data on purpose. Delete `persistent_disk` from `data/options/render.json` and run `pnpm check:data`. Read the failure, then restore it. +3. Add a rule. Add a capability rule that warns when `needs: ["users_pay"]` and `payments.subscriptions` is `false`. Write its test in `evaluate.test.ts` first. +4. Grade the baseline. Write three cases in `evals/prefill-cases.json` and run `pnpm eval:prefill --keywords-only`. ## Questions to answer in your own words diff --git a/docs/MCP.md b/docs/MCP.md index 8fc3731..31c163d 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -323,8 +323,8 @@ Other builders get the spec, setup, tasks, decisions and plan file, without the ## Troubleshooting -- **ECONNREFUSED, or Claude Code lists StackWise as failed**: StackWise isn't open, or the address uses `localhost`. Open the app (or run `stackwise`), then press Connect in Settings again, which rewrites the address. -- **"No plan is shared yet"**: open Ask, send the agent a message, or pick "Share this plan with agents" in the Answering menu. -- **Claude Code doesn't list StackWise's tools**: `claude mcp list`. For a project exported from a source checkout, check that `.mcp.json` points at StackWise's folder and that `pnpm` is on your PATH. -- **Try the stdio command yourself**: `CLAUDE_PROJECT_DIR=/path/to/project pnpm --silent --dir /path/to/stackwise mcp` prints "StackWise MCP server running" to stderr and waits for input. -- **Start over**: quit StackWise and delete `~/.stackwise/plans/`. Your profile and library stay. +- ECONNREFUSED, or Claude Code lists StackWise as failed: StackWise isn't open, or the address uses `localhost`. Open the app (or run `stackwise`), then press Connect in Settings again, which rewrites the address. +- "No plan is shared yet": open Ask, send the agent a message, or pick "Share this plan with agents" in the Answering menu. +- Claude Code doesn't list StackWise's tools: `claude mcp list`. For a project exported from a source checkout, check that `.mcp.json` points at StackWise's folder and that `pnpm` is on your PATH. +- Try the stdio command yourself: `CLAUDE_PROJECT_DIR=/path/to/project pnpm --silent --dir /path/to/stackwise mcp` prints "StackWise MCP server running" to stderr and waits for input. +- Start over: quit StackWise and delete `~/.stackwise/plans/`. Your profile and library stay. diff --git a/electron/main.cjs b/electron/main.cjs index f76c875..98af973 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -82,6 +82,10 @@ function createWindow() { backgroundColor: "#f5f5f7", webPreferences: { preload: path.join(__dirname, "preload.cjs"), contextIsolation: true, sandbox: true }, }); + // In full screen macOS hides the traffic lights; the page drops the room it leaves for them (preload.cjs sets data-fullscreen). + const tellFullScreen = () => win && !win.isDestroyed() && win.webContents.send("fullscreen", win.isFullScreen()); + for (const event of ["enter-full-screen", "leave-full-screen", "enter-html-full-screen", "leave-html-full-screen"]) win.on(event, tellFullScreen); + win.webContents.on("did-finish-load", tellFullScreen); // The window is visible from the start. Created hidden and shown on ready-to-show, its page // stayed in the hidden state on macOS 26: no layout, no paint, a blank gray window. // Links to other sites open in the browser, never in this window. @@ -168,7 +172,7 @@ function appMenu() { { role: "editMenu" }, { role: "viewMenu" }, { role: "windowMenu" }, - { label: "Help", submenu: [{ label: "Documentation", click: () => shell.openExternal("https://github.com/Mikey-Ku/StackWise#readme") }, { label: "Learn", click: () => (showWindow(), win && win.loadURL(`${URL}/learn`)) }] }, + { label: "Help", submenu: [{ label: "Documentation", click: () => (showWindow(), win && win.loadURL(`${URL}/docs`)) }, { label: "StackWise on GitHub", click: () => shell.openExternal("https://github.com/Mikey-Ku/StackWise") }] }, ]), ); } diff --git a/electron/pack.cjs b/electron/pack.cjs index 32ac251..087250e 100644 --- a/electron/pack.cjs +++ b/electron/pack.cjs @@ -27,8 +27,20 @@ for (const [from, to] of [ fs.rmSync(path.join(out, to), { recursive: true, force: true }); fs.cpSync(path.join(root, from), path.join(out, to), { recursive: true, dereference: true }); } +// The Documentation page reads the repo's Markdown, so it comes along (the text, not the images). +fs.mkdirSync(path.join(out, "docs"), { recursive: true }); +fs.copyFileSync(path.join(root, "README.md"), path.join(out, "README.md")); +for (const name of fs.readdirSync(path.join(root, "docs")).filter((f) => f.endsWith(".md"))) fs.copyFileSync(path.join(root, "docs", name), path.join(out, "docs", name)); // Nothing of the person's goes into the bundle: no keys, no state. for (const stray of [".env.local", ".env", ".stackwise"]) fs.rmSync(path.join(out, stray), { recursive: true, force: true }); +// Next's file tracing follows fs reads it can evaluate. A read of `path.join(process.cwd(), )` +// once traced the whole repo into the standalone (`.git`, `release/` with the last dmg, private +// notes) and the dmg grew four times. If any of these is here, a page is reading files that way. +const leaked = [".git", "release", "CLAUDE.local.md", "CLAUDE.md", "evals", "scripts", "electron"].filter((name) => fs.existsSync(path.join(out, name))); +if (leaked.length) { + console.error(`The standalone build contains the repo (${leaked.join(", ")}): a page reads files from process.cwd() with a variable path, so Next traced the whole folder. Read through a root the tracer can't evaluate (see docsRoot in src/app/docs/page.tsx).`); + process.exit(1); +} let relinked = 0; const bad = []; diff --git a/electron/preload.cjs b/electron/preload.cjs index b0857fc..b92428e 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -1,6 +1,12 @@ -// Runs in the page before StackWise loads, with no access to Node. It marks the page as being -// inside the Mac app, so the top bars leave room for the window's traffic lights and can be -// dragged (globals.css and shell.css read data-desktop). +// Runs in the page before StackWise loads, with no access to Node beyond Electron's own bridge. +// It marks the page as being inside the Mac app, so the top bars leave room for the window's +// traffic lights and can be dragged (globals.css and shell.css read data-desktop), and relays +// whether the window is in full screen, where macOS hides the traffic lights and that room goes. +const { ipcRenderer } = require("electron"); + document.addEventListener("DOMContentLoaded", () => { document.documentElement.dataset.desktop = "mac"; }); +ipcRenderer.on("fullscreen", (_event, on) => { + document.documentElement?.toggleAttribute("data-fullscreen", Boolean(on)); +}); diff --git a/next.config.ts b/next.config.ts index 81244af..701c997 100644 --- a/next.config.ts +++ b/next.config.ts @@ -2,13 +2,26 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { // The Mac app runs the built site as a standalone server (electron/main.cjs). pnpm build stays as it is. - ...(process.env.STACKWISE_STANDALONE ? { output: "standalone" as const, outputFileTracingRoot: __dirname } : {}), + ...(process.env.STACKWISE_STANDALONE + ? { + output: "standalone" as const, + outputFileTracingRoot: __dirname, + // Next copies into the standalone every file a page's fs reads can be traced to. A read whose + // folder it can't evaluate (a project folder, the home folder) becomes a `**/` glob over + // this repo, which matched the copies of data/ inside release/ (the last app build), the empty + // .git and the old .stackwise. None of that belongs in the app; pack.cjs copies data/ itself. + outputFileTracingExcludes: { "*": [".git/**", "**/.git", "release/**", ".stackwise/**"] }, + } + : {}), devIndicators: false, // next dev would otherwise write its own AGENTS.md and CLAUDE.md blocks into this repo. agentRules: false, - // The applications page became Projects. + // The applications page became Projects; Learn joined the Documentation page (the hash, #part- or #term-, comes along). async redirects() { - return [{ source: "/apps", destination: "/projects", permanent: true }]; + return [ + { source: "/apps", destination: "/projects", permanent: true }, + { source: "/learn", destination: "/docs", permanent: true }, + ]; }, // No other site may show StackWise in a frame: a page could otherwise trick clicks on Start or Export. async headers() { diff --git a/package.json b/package.json index c35f9b6..c246f11 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "@xyflow/react": "^12.11.0", "fflate": "^0.8.3", "html-to-image": "1.11.11", + "marked": "^18.1.1", "next": "16.3.4", "react": "19.2.8", "react-dom": "19.2.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b69eff8..daf7285 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -124,6 +124,9 @@ importers: html-to-image: specifier: 1.11.11 version: 1.11.11 + marked: + specifier: ^18.1.1 + version: 18.1.1 next: specifier: 16.3.4 version: 16.3.4(@babel/core@7.29.7(supports-color@7.2.0))(@types/node@25.9.6)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -2599,6 +2602,11 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + marked@18.1.1: + resolution: {integrity: sha512-zEGgrtUG8crk+TrMacJSVABU4DYDDkS8uqgU3ohrn/2fW9C2AEfUrO3m6IhpIpQpl7YcVpiXXC9cSMWDANT3dg==} + engines: {node: '>= 20'} + hasBin: true + matcher@3.0.0: resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} engines: {node: '>=10'} @@ -6251,6 +6259,8 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + marked@18.1.1: {} + matcher@3.0.0: dependencies: escape-string-regexp: 4.0.0 diff --git a/src/app/docs/DocsView.tsx b/src/app/docs/DocsView.tsx new file mode 100644 index 0000000..5560d3b --- /dev/null +++ b/src/app/docs/DocsView.tsx @@ -0,0 +1,284 @@ +"use client"; + +import { Fragment, useEffect, useState, type ReactNode } from "react"; +import { Shell, type Me, type ShellSections } from "@/components/Shell"; +import type { Learn, LearnLink, SlotId } from "@/engine/schema"; + +/** + * The documentation, as one document. First how a web app fits together, in plain words, from + * data/learn.json (start here, the parts of an app, the glossary); then the repo's own Markdown + * docs. Every section has the same shape: a title, the file it comes from, its headings as chips, + * the body. The sidebar lists the sections in two groups and follows the one in view. The hash + * picks a section (/docs#mcp), a part (#part-database) or a term (#term-api). + */ + +type SlotEntry = NonNullable; +export type LearnPart = SlotEntry & { id: SlotId; label: string }; +export type LearnTerm = Learn["terms"][string] & { id: string; usedIn: { id: SlotId; label: string }[] }; +export type StartHere = NonNullable; +export interface LearnContent { + startHere: StartHere | null; + parts: LearnPart[]; + terms: LearnTerm[]; +} + +export interface Doc { + id: string; + title: string; + file: string; + html: string; + headings: { id: string; text: string }[]; +} + +type Heading = { id: string; text: string }; + +/** Past this many headings (the decisions, the glossary), the contents fold up behind a line. */ +const MANY_HEADINGS = 16; +const LEARN_FILE = "data/learn.json"; + +function Contents({ headings, label, noun = "headings" }: { headings: Heading[]; label: string; noun?: string }) { + if (headings.length < 2) return null; + const nav = ( + + ); + if (headings.length <= MANY_HEADINGS) return nav; + return ( +
+ + Contents, {headings.length} {noun} + + {nav} +
+ ); +} + +function DocSection({ id, title, file, headings, noun, children }: { id: string; title: string; file: string; headings: Heading[]; noun?: string; children: ReactNode }) { + return ( +
+
+

{title}

+ + {file} + +
+ + {children} +
+ ); +} + +function Reading({ links }: { links: LearnLink[] }) { + return ( +
+

Further reading

+ +
+ ); +} + +function StartHereSection({ start }: { start: StartHere }) { + return ( + +
+

{start.title}

+

{start.summary}

+
    + {start.layers.map((layer, i) => ( +
  1. + {i + 1} +
    +

    {layer.name}

    +

    {layer.plain}

    +

    {layer.rule}

    +
    +
  2. + ))} +
+ {start.read_more.length > 0 && } +
+
+ ); +} + +function PartsSection({ parts, termNames }: { parts: LearnPart[]; termNames: Map }) { + return ( + ({ id: `part-${p.id}`, text: p.label }))} noun="parts"> +
+

What each part does, how to pick one, the mistakes beginners make, and the best places to read more.

+ {parts.map((part, i) => ( +
+

Part {String(i + 1).padStart(2, "0")}

+

+ + {part.label} + +

+

{part.what}

+
+

Why you need it

+

{part.why}

+
+
+
+

How to choose

+
    + {part.choosing.map((line) => ( +
  • {line}
  • + ))} +
+
+
+

Common mistakes

+
    + {part.watch_for.map((line) => ( +
  • {line}
  • + ))} +
+
+
+ {part.terms.length > 0 && ( +
+

Key terms

+ +
+ )} + {part.read_more.length > 0 && } +
+ ))} +
+
+ ); +} + +function GlossarySection({ terms }: { terms: LearnTerm[] }) { + return ( + ({ id: `term-${t.id}`, text: t.term }))} noun="terms"> +
+

The words you'll meet in docs, dashboards and AI answers.

+
+ {terms.map((t) => ( +
+
+ + {t.term} + +
+
+

{t.plain}

+

+ Why it matters {t.matters} +

+ {(t.read_more.length > 0 || t.usedIn.length > 0) && ( +
+ {t.usedIn.length > 0 && ( + + Used in{" "} + {t.usedIn.map((p, i) => ( + + {i > 0 && ", "} + {p.label} + + ))} + + )} + {t.read_more.map((link) => ( + + {link.source}: {link.title} + + ))} +
+ )} +
+
+ ))} +
+
+
+ ); +} + +export default function DocsView({ me, learn, docs, repo }: { me: Me | null; learn: LearnContent; docs: Doc[]; repo: string }) { + const learnItems = [ + ...(learn.startHere ? [{ id: "start-here", label: "Start here" }] : []), + ...(learn.parts.length > 0 ? [{ id: "parts", label: "Parts of an app" }] : []), + ...(learn.terms.length > 0 ? [{ id: "glossary", label: "Glossary" }] : []), + ]; + const ids = [...learnItems.map((i) => i.id), ...docs.map((d) => d.id)]; + const idKey = ids.join(" "); + const [active, setActive] = useState(ids[0] ?? "start-here"); + const termNames = new Map(learn.terms.map((t) => [t.id, t.term])); + + // The sidebar follows the section in view. + useEffect(() => { + const sections = idKey + .split(" ") + .map((id) => document.getElementById(id)) + .filter((el): el is HTMLElement => Boolean(el)); + if (sections.length === 0) return; + const observer = new IntersectionObserver( + (entries) => { + const seen = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top); + if (seen[0]) setActive(seen[0].target.id); + }, + { rootMargin: "-20% 0px -70% 0px" }, + ); + for (const el of sections) observer.observe(el); + return () => observer.disconnect(); + }, [idKey]); + + const item = (id: string, label: string) => ({ id, label, href: `/docs#${id}`, active: active === id }); + const sidebar: ShellSections[] = [ + { title: "Learn", items: learnItems.map((i) => item(i.id, i.label)) }, + { title: "Project", items: docs.map((d) => item(d.id, d.title)) }, + ].filter((group) => group.items.length > 0); + + return ( + +
+
+

Documentation

+

+ How a web app fits together, in plain words, then the project's own docs. The same files as in the repo, read from this copy of StackWise; edit them on{" "} + + GitHub + + . +

+
+
+ {learn.startHere && } + {learn.parts.length > 0 && } + {learn.terms.length > 0 && } + {docs.map((doc) => ( + + {/* The repo's own Markdown, rendered on the server; nothing here comes from a person's input. */} +
+ + ))} + + ); +} diff --git a/src/app/docs/docs.css b/src/app/docs/docs.css new file mode 100644 index 0000000..9648fc3 --- /dev/null +++ b/src/app/docs/docs.css @@ -0,0 +1,441 @@ +/* The documentation page: the repo's Markdown as readable documents, one section per file. */ +.doc { + display: flex; + flex-direction: column; + gap: 18px; + max-width: 780px; + padding-top: 28px; + border-top: 0.5px solid var(--ws-glass-line); + scroll-margin-top: 24px; +} +.doc:first-of-type { + padding-top: 0; + border-top: 0; +} +.doc__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 8px 16px; +} +.doc__title { + margin: 0; + font-size: 19px; + font-weight: 700; + letter-spacing: -0.02em; +} +.doc__file code { + color: var(--mk-text-faint); + font-family: var(--mk-font-mono); + font-size: 12px; +} +.doc__toc { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.doc__toc a { + padding: 3px 9px; + border-radius: 999px; + background: var(--ws-fill); + color: var(--mk-text-muted); + font-size: 12px; + text-decoration: none; +} +.doc__toc a:hover { + background: var(--ws-fill-hover); + color: var(--mk-text); +} +.doc__contents summary { + cursor: pointer; + color: var(--mk-text-muted); + font-size: 13px; + user-select: none; +} +.doc__contents[open] summary { + margin-bottom: 10px; +} + +/* The body: the Markdown's own structure, in the app's type, the same size as the other pages' text. */ +.doc__body { + font-size: 14px; + line-height: 1.5; + overflow-wrap: anywhere; +} +.doc__body > :first-child { + margin-top: 0; +} +.doc__body h2 { + margin: 0 0 6px; + font-size: 17px; + font-weight: 700; + letter-spacing: -0.02em; +} +.doc__body h3 { + margin: 28px 0 8px; + font-size: 15.5px; + font-weight: 650; + letter-spacing: -0.01em; + scroll-margin-top: 24px; +} +.doc__body h4 { + margin: 22px 0 6px; + font-size: 14px; + font-weight: 650; + scroll-margin-top: 24px; +} +.doc__body h5, +.doc__body h6 { + margin: 18px 0 4px; + font-size: 14px; + font-weight: 650; +} +.doc__body p { + margin: 0 0 14px; +} +.doc__body ul, +.doc__body ol { + margin: 0 0 14px; + padding-left: 1.4em; +} +.doc__body li { + margin: 4px 0; +} +.doc__body li > p { + margin: 0; +} +.doc__body a { + color: var(--mk-accent); + text-decoration: none; +} +.doc__body a:hover { + text-decoration: underline; +} +.doc__body strong { + font-weight: 650; +} +.doc__body code { + padding: 1px 5px; + border-radius: 5px; + background: var(--mk-surface-sunk); + font-family: var(--mk-font-mono); + font-size: 0.86em; +} +.doc__body pre { + margin: 0 0 16px; + padding: 12px 14px; + overflow-x: auto; + border-radius: 12px; + background: var(--mk-surface-sunk); + font-size: 12.5px; + line-height: 1.5; +} +.doc__body pre code { + padding: 0; + background: transparent; + font-size: inherit; +} +.doc__body blockquote { + margin: 0 0 14px; + padding: 2px 14px; + border-left: 3px solid var(--mk-line-strong); + color: var(--mk-text-muted); +} +.doc__body table { + width: 100%; + margin: 0 0 18px; + border-collapse: collapse; + font-size: 13.5px; + line-height: 1.45; +} +.doc__body th, +.doc__body td { + padding: 8px 10px; + border-bottom: 0.5px solid var(--ws-glass-line); + text-align: left; + vertical-align: top; +} +.doc__body th { + color: var(--mk-text-muted); + font-weight: 600; +} +.doc__body img { + max-width: 100%; + height: auto; + margin: 4px 0 16px; + border-radius: 12px; + border: 0.5px solid var(--ws-glass-line); +} +.doc__body hr { + margin: 24px 0; + border: 0; + border-top: 0.5px solid var(--ws-glass-line); +} +.doc__body p:has(> img:only-child) { + text-align: center; +} +/* The text keeps its size at every width; only the columns change. */ + +/* ---------- The Learn sections (data/learn.json), in the same body style ---------- */ +.doc__body .doc-lead { + margin: 0 0 14px; + font-weight: 500; + color: var(--mk-text); + text-wrap: pretty; +} +.doc-eyebrow { + margin: 0 0 6px; + font-size: 13px; + font-weight: 600; + color: var(--accent); +} +.doc-block { + margin-top: 24px; +} +.doc-block > p { + margin: 0; + color: var(--mk-text-muted); +} +.doc__body .doc-label { + margin: 0 0 10px; + font-size: 13px; + font-weight: 600; + letter-spacing: 0.01em; + color: var(--mk-text-muted); +} +.doc-anchor { + color: inherit !important; +} +.doc-anchor:hover { + text-decoration: none !important; +} + +/* One part: its own block under the section, with the heading the deep links point at. */ +.doc-part { + margin-top: 32px; + padding-top: 28px; + border-top: 0.5px solid var(--ws-glass-line); + scroll-margin-top: 24px; +} +.doc__body .doc-part h3 { + margin-top: 0; +} + +.doc-grid { + margin-top: 24px; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} +.doc-card { + padding: 18px 20px 16px; + border-radius: var(--mk-radius-lg); + background: var(--mk-surface); + border: 1px solid var(--mk-line); + box-shadow: var(--mk-shadow-1); +} +.doc-card--warn { + background: color-mix(in srgb, var(--mk-warn) 5%, var(--mk-surface)); + border-color: color-mix(in srgb, var(--mk-warn) 22%, var(--mk-line)); +} +.doc__body .doc-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 10px; +} +.doc__body .doc-list li { + position: relative; + margin: 0; + padding-left: 26px; + line-height: 1.5; +} +.doc-list li::before { + content: ""; + position: absolute; + left: 0; + top: 3px; + width: 16px; + height: 16px; + border-radius: 50%; + background-position: center; + background-repeat: no-repeat; + background-size: 10px; +} +.doc-list--check li::before { + background-color: var(--mk-accent-soft); + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M2 5.2 4.1 7.2 8 3' fill='none' stroke='%23007aff' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); +} +.doc-list--warn li::before { + background-color: var(--mk-warn-soft); + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M5 2.2v3.4' stroke='%23e07b00' stroke-width='1.6' stroke-linecap='round'/%3E%3Ccircle cx='5' cy='7.7' r='0.9' fill='%23e07b00'/%3E%3C/svg%3E"); +} + +/* Further reading: a card per link, the publisher above the title. */ +.doc__body .doc-links { + list-style: none; + margin: 0; + padding: 0; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 12px; +} +.doc__body .doc-links li { + margin: 0; +} +.doc__body .doc-link { + position: relative; + display: flex; + flex-direction: column; + gap: 4px; + height: 100%; + padding: 12px 38px 12px 14px; + border-radius: var(--mk-radius-lg); + border: 1px solid var(--mk-line); + background: var(--mk-surface); + color: var(--mk-text); + text-decoration: none; + transition: + border-color var(--mk-dur-fast) var(--mk-ease), + box-shadow var(--mk-dur-fast) var(--mk-ease); +} +.doc__body .doc-link:hover { + border-color: color-mix(in srgb, var(--accent) 45%, var(--mk-line)); + box-shadow: var(--mk-shadow-1); + text-decoration: none; +} +.doc-link__source { + font-size: 12px; + font-weight: 600; + color: var(--mk-text-muted); +} +.doc-link__title { + font-weight: 500; + line-height: 1.35; +} +.doc-link__arrow { + position: absolute; + right: 12px; + top: 14px; + color: var(--mk-text-faint); +} +.doc-link:hover .doc-link__arrow { + color: var(--accent); +} + +/* Start here: the layers, numbered. */ +.doc__body .doc-layers { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 12px; +} +.doc__body .doc-layer { + display: grid; + grid-template-columns: 32px minmax(0, 1fr); + gap: 16px; + margin: 0; + padding: 16px 20px; + border-radius: var(--mk-radius-lg); + background: var(--mk-surface); + border: 1px solid var(--mk-line); + box-shadow: var(--mk-shadow-1); +} +.doc-layer__num { + display: grid; + place-items: center; + width: 32px; + height: 32px; + border-radius: 50%; + background: var(--mk-accent-soft); + color: var(--accent); + font-weight: 700; + font-size: 14px; +} +.doc__body .doc-layer__name { + margin: 4px 0; + font-size: 14px; + font-weight: 600; + letter-spacing: -0.01em; +} +.doc__body .doc-layer p { + margin: 0; + line-height: 1.5; + color: var(--mk-text-muted); +} +.doc__body .doc-layer .doc-layer__rule { + margin-top: 8px; + color: var(--mk-text); + font-weight: 500; +} + +/* The glossary: a definition list, each term the target of a deep link. */ +.doc__body .doc-terms { + margin: 0; + border-top: 1px solid var(--mk-line); +} +.doc-term { + display: grid; + grid-template-columns: 180px minmax(0, 1fr); + gap: 24px; + padding: 18px 0; + border-bottom: 1px solid var(--mk-line); + scroll-margin-top: 24px; +} +.doc-term:target { + margin: 0 -16px; + padding: 18px 16px; + border-radius: var(--mk-radius-lg); + background: var(--mk-accent-soft); + border-bottom-color: transparent; +} +.doc-term dt { + font-weight: 600; + letter-spacing: -0.01em; +} +.doc-term dd { + margin: 0; +} +.doc__body .doc-term dd p { + margin: 0; + line-height: 1.5; +} +.doc-term__matters { + margin-top: 8px !important; + color: var(--mk-text-muted); +} +.doc-term__label { + font-weight: 600; + color: var(--mk-text); +} +.doc-term__foot { + display: flex; + flex-wrap: wrap; + gap: 6px 16px; + margin-top: 10px; + font-size: 13px; + color: var(--mk-text-muted); +} +.doc-term__foot a { + color: var(--mk-text-muted); +} +.doc-term__foot a:hover { + color: var(--accent); +} + +@media (max-width: 720px) { + .doc-grid { + grid-template-columns: minmax(0, 1fr); + } + .doc-term { + grid-template-columns: minmax(0, 1fr); + gap: 6px; + } + .doc-term:target { + margin: 0; + padding: 18px 12px; + } +} diff --git a/src/app/docs/page.tsx b/src/app/docs/page.tsx new file mode 100644 index 0000000..a6511be --- /dev/null +++ b/src/app/docs/page.tsx @@ -0,0 +1,128 @@ +import fs from "node:fs"; +import path from "node:path"; +import type { Metadata } from "next"; +import { Marked, type Tokens } from "marked"; +import { loadCatalog } from "@/engine/load"; +import { readMe } from "@/local/home"; +import DocsView, { type Doc, type LearnContent, type LearnPart, type LearnTerm } from "./DocsView"; +import "../shell.css"; +import "./docs.css"; + +export const metadata: Metadata = { + title: "Documentation | StackWise", + description: "How a web app fits together, in plain words: every part, how to choose one, the mistakes beginners make, a glossary. Then StackWise's own docs: the overview, the MCP tools, the facts and rules, the decisions and the demo.", +}; + +// The docs are files in the repo (data/learn.json, the Markdown); read them on every request so an edit shows on refresh. +export const dynamic = "force-dynamic"; + +/** + * Where the Markdown is: the working folder (the repo, or the standalone folder in the Mac app, + * where pack.cjs copies the files). Written this way on purpose: Next's output file tracing + * follows every `fs.readFileSync(path.join(process.cwd(), ...))` it can evaluate, and with a + * variable file name it traced the whole working folder into the standalone build (the git + * history, the last dmg, private notes). A plain `a || process.cwd()` was folded back to + * `process.cwd()` by the bundler; a lookup in an array is something neither it nor the tracer + * evaluates, so the read traces nothing and pack.cjs copies the files itself. + */ +const docsRoot = () => [process.env.STACKWISE_DOCS_ROOT, process.cwd()].find(Boolean) as string; + +/** The project's documents, in reading order. Each is a Markdown file in the repo, shown as one section. */ +const DOCS: { id: string; title: string; file: string }[] = [ + { id: "overview", title: "Overview", file: "README.md" }, + { id: "mcp", title: "MCP and agents", file: "docs/MCP.md" }, + { id: "data", title: "Facts and rules", file: "docs/DATA.md" }, + { id: "how", title: "How it works", file: "docs/LEARNING.md" }, + { id: "decisions", title: "Decisions", file: "docs/DECISIONS.md" }, + { id: "demo", title: "The demo", file: "docs/DEMO.md" }, +]; + +const REPO = "https://github.com/Mikey-Ku/StackWise"; +const RAW = "https://raw.githubusercontent.com/Mikey-Ku/StackWise/main"; + +const slug = (text: string) => + text + .toLowerCase() + .replace(/<[^>]+>/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, ""); + +/** + * A link inside a doc: another doc becomes its section here (its own anchors too), a repo file + * opens on GitHub, the web stays the web. Heading ids carry the document's id, so a `#heading` + * link inside a document points at that document's heading. + */ +function rewriteHref(href: string, from: string): string { + if (/^(https?:|mailto:)/.test(href)) return href; + const [file, anchor] = href.split("#"); + if (!file) return `#${from}-${anchor ?? ""}`; + const clean = file.replace(/^(\.\.?\/)+/, ""); + const doc = DOCS.find((d) => d.file === clean || d.file === `docs/${clean}`); + if (doc) return `/docs#${anchor ? `${doc.id}-${anchor}` : doc.id}`; + return `${REPO}/blob/main/${clean.replace(/^\//, "")}`; +} + +/** An image in a doc: the app's own icon is served by the app; anything else in the repo comes from GitHub. */ +const imageSrc = (href: string) => (/^(https?:|data:)/.test(href) ? href : href.replace(/^\.?\//, "") === "src/app/icon.svg" ? "/icon.svg" : `${RAW}/${href.replace(/^\.?\//, "")}`); + +function render(id: string, markdown: string): { html: string; headings: { id: string; text: string }[] } { + const headings: { id: string; text: string }[] = []; + const marked = new Marked({ gfm: true }); + marked.use({ + renderer: { + heading({ tokens, depth }: Tokens.Heading) { + const text = this.parser.parseInline(tokens); + const anchor = `${id}-${slug(text)}`; + if (depth === 2) headings.push({ id: anchor, text: text.replace(/<[^>]+>/g, "") }); + // The file's own title is the section's title in the sidebar; inside, start one level down. + const level = Math.min(6, depth + 1); + return `${text}\n`; + }, + link({ href, title, tokens }: Tokens.Link) { + const text = this.parser.parseInline(tokens); + const to = rewriteHref(href, id); + const external = /^https?:/.test(to); + return `${text}`; + }, + image({ href, title, text }: Tokens.Image) { + return `${text}`; + }, + }, + }); + // GitHub's blocks (light and dark screenshots) are plain HTML in the file: keep the + // light one. Raw tags point at files in the repo too, so their src gets the same treatment. + const source = markdown + .replace(/[\s\S]*?(]*>)[\s\S]*?<\/picture>/g, "$1") + .replace(/(]*?src=")([^"]+)(")/g, (_m, before: string, src: string, after: string) => `${before}${imageSrc(src)}${after}`); + const html = marked.parse(source) as string; + return { html, headings }; +} + +/** The teaching content from data/learn.json: the layers to start with, one entry per part, the glossary. */ +function learnContent(): LearnContent { + const catalog = loadCatalog(); + const { learn } = catalog; + const parts: LearnPart[] = catalog.slots.flatMap((slot) => { + const entry = learn.slots[slot.id]; + return entry ? [{ id: slot.id, label: slot.label, ...entry }] : []; + }); + // Each term lists the parts that use it, so the glossary links back to them. + const terms: LearnTerm[] = Object.entries(learn.terms) + .map(([id, t]) => ({ id, ...t, usedIn: parts.filter((p) => p.terms.includes(id)).map((p) => ({ id: p.id, label: p.label })) })) + .sort((a, b) => a.term.localeCompare(b.term, "en", { sensitivity: "base" })); + return { startHere: learn.start_here ?? null, parts, terms }; +} + +export default function DocsPage() { + const docs: Doc[] = DOCS.flatMap((doc) => { + let text: string; + try { + text = fs.readFileSync(path.join(docsRoot(), doc.file), "utf8"); + } catch { + return []; + } + const { html, headings } = render(doc.id, text); + return [{ id: doc.id, title: doc.title, file: doc.file, html, headings }]; + }); + return ; +} diff --git a/src/app/globals.css b/src/app/globals.css index 59be2eb..6758f71 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1039,7 +1039,7 @@ body { right: 0; left: 0; display: grid; - grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; height: var(--bar-h); @@ -1059,7 +1059,7 @@ body { height: var(--bar-h); } .ws-bar__side--end { - grid-column: 3; + grid-column: 2; justify-self: end; gap: 4px; } @@ -1099,11 +1099,14 @@ body { background: var(--ws-fill); } +/* The summary follows the plan and the nav in the left cluster; only the actions sit at the right. */ .ws-summary { display: inline-flex; - grid-column: 2; align-items: center; gap: 10px; + min-width: 0; + margin-left: 6px; + overflow: hidden; height: 32px; padding: 0 14px; border: 0; @@ -1657,16 +1660,12 @@ body { .ws[data-ask="open"] .ws-sheet-wrap { left: var(--ask-w); } -.ws[data-ask="open"] .ws-bar, -html[data-desktop] .ws[data-ask="open"] .ws-bar { +/* Beside the pane the bar keeps its mark; the traffic lights are in the pane's header in the app. */ +.ws[data-ask="open"] .ws-bar { left: var(--ask-w); - padding-left: 12px; - grid-template-columns: auto minmax(0, 1fr) auto; } -.ws[data-ask="open"] .ws-summary { - justify-self: center; - max-width: 100%; - overflow: hidden; +html[data-desktop] .ws[data-ask="open"] .ws-bar { + padding-left: 12px; } /* Beside the pane the AI pill keeps its dot and name; the state is in the title and the popover. */ .ws[data-ask="open"] .ws-connpill__state:not(.is-cta) { @@ -1707,7 +1706,11 @@ html[data-desktop] .ws[data-ask="open"] .ws-bar { transition: none; } } -/* In the Mac app the traffic lights sit in the pane's top row, or in the bar when the pane is closed. */ +/* The pane's header, like a sidebar's: the hide toggle (after the traffic lights in the app), then new chat at the right. */ +.ws-ask__spacer { + flex: 1; + min-width: 0; +} html[data-desktop] .ws-ask__top { padding-left: 84px; } @@ -1736,17 +1739,6 @@ html[data-desktop] .ws-ask__top { padding: 0 10px 0 12px; } /* The header: the plan's name, then new chat and hide as plain icons, like a sidebar's own controls. */ -.ws-ask__plan { - flex: 1; - min-width: 0; - overflow: hidden; - padding: 0 4px; - color: var(--mk-text); - font-size: 0.93em; - font-weight: 600; - text-overflow: ellipsis; - white-space: nowrap; -} .ws-ask__top .ws-iconbtn { width: 28px; height: 28px; @@ -1782,9 +1774,16 @@ html[data-desktop] .ws-ask__top { cursor: pointer; } .ws-answerer--model { - color: var(--mk-text-muted); + color: var(--mk-text); font-weight: 500; } +.ws-answerer--model.is-placeholder { + color: var(--mk-text-muted); +} +.ws-answerer__note { + color: var(--mk-text-muted); + font-weight: 400; +} .ws-ask__ctx { display: inline-grid; flex: none; @@ -1843,10 +1842,69 @@ html[data-desktop] .ws-ask__top { gap: 4px; color: var(--mk-accent); } -.ws-turn__meta { +/* A message the agent hasn't picked up yet is a little quieter; its state is in the tooltip. */ +.ws-turn--to-agent.is-waiting { + opacity: 0.72; +} +/* A message's text (chatText.ts): headings, lists, bold, code, and a fold for long replies. */ +.ws-rich { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} +.ws-rich.is-folded { + max-height: 15em; + overflow: hidden; + -webkit-mask-image: linear-gradient(#000 65%, transparent); + mask-image: linear-gradient(#000 65%, transparent); +} +.ws-rich__h { + margin-top: 4px !important; + font-weight: 650; +} +.ws-rich__h.is-caps { + color: var(--mk-text-muted); + font-size: 0.78em; + letter-spacing: 0.05em; +} +.ws-rich li + li { + margin-top: 3px; +} +.ws-rich code { + padding: 0 4px; + border-radius: 4px; + background: var(--ws-fill); + font-family: var(--mk-font-mono); + font-size: 0.88em; + overflow-wrap: anywhere; +} +.ws-turn--you .ws-rich code { + background: rgba(255, 255, 255, 0.18); +} +.ws-rich pre { + margin: 0; + padding: 8px 10px; + overflow-x: auto; + border-radius: 8px; + background: var(--ws-fill); + font-family: var(--mk-font-mono); + font-size: 0.85em; + white-space: pre; +} +.ws-rich__more { + align-self: flex-start; margin-top: 2px; - color: rgba(255, 255, 255, 0.75); - font-size: 11px; + padding: 0; + border: 0; + background: none; + color: var(--mk-accent); + font: inherit; + font-size: 0.9em; + cursor: pointer; +} +.ws-rich__more:hover { + text-decoration: underline; } .ws-files { display: flex; @@ -1877,6 +1935,14 @@ html[data-desktop] .ws-ask__top { margin: 0; padding-left: 1.1em; } +/* The agent's lookups in StackWise: one quiet line, not a card. */ +.ws-lookup { + margin: 0; + padding: 0 2px; + color: var(--mk-text-faint); + font-size: 0.82em; + line-height: 1.45; +} .ws-connect { display: flex; flex-direction: column; @@ -3544,7 +3610,9 @@ html[data-desktop] .ws-ask__top { } /* ---------- v1: inside the Mac app (electron/preload.cjs sets data-desktop) ---------- */ -/* The window has no title bar: the top strip drags it, and the bar sits past the traffic lights. */ +/* The window has no title bar: the top strip drags it, and the bar sits past the traffic lights. + The strip takes no clicks: it sat over the chat pane's header and ate the hide button's. The + drag region comes from its box, and the no-drag controls under it are cut out of that region. */ html[data-desktop] .ws::before { content: ""; position: absolute; @@ -3553,12 +3621,24 @@ html[data-desktop] .ws::before { right: 0; left: 0; height: 48px; + pointer-events: none; -webkit-app-region: drag; } html[data-desktop] .ws-bar { padding-left: 98px; -webkit-app-region: drag; } +/* Full screen hides the traffic lights, so the room for them goes (preload.cjs sets data-fullscreen; the media query is the fallback). */ +html[data-desktop][data-fullscreen] .ws-bar, +html[data-desktop][data-fullscreen] .ws-ask__top { + padding-left: 12px; +} +@media (display-mode: fullscreen) { + html[data-desktop] .ws-bar, + html[data-desktop] .ws-ask__top { + padding-left: 12px; + } +} html[data-desktop] .ws-bar > *, html[data-desktop] .ws-ask__top > * { -webkit-app-region: no-drag; diff --git a/src/app/learn/LearnView.tsx b/src/app/learn/LearnView.tsx deleted file mode 100644 index 4023b89..0000000 --- a/src/app/learn/LearnView.tsx +++ /dev/null @@ -1,382 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { Fragment, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react"; -import { Shell, type Me } from "@/components/Shell"; -import type { Learn, LearnLink, SlotId } from "@/engine/schema"; - -type SlotEntry = NonNullable; -export type LearnPart = SlotEntry & { id: SlotId; label: string }; -export type LearnTerm = Learn["terms"][string] & { id: string; usedIn: { id: SlotId; label: string }[] }; -type StartHere = NonNullable; - -const partHaystack = (p: LearnPart) => [p.label, p.what, p.why, ...p.choosing, ...p.watch_for, ...p.read_more.map((l) => `${l.title} ${l.source}`)].join(" ").toLowerCase(); -const termHaystack = (t: LearnTerm) => [t.id, t.term, t.plain, t.matters].join(" ").toLowerCase(); -const startHaystack = (s: StartHere) => [s.title, s.summary, ...s.layers.flatMap((l) => [l.name, l.plain, l.rule])].join(" ").toLowerCase(); - -/** Wraps each match of the search in , so people see why a section is still showing. */ -function Hi({ text, q }: { text: string; q: string }) { - if (!q) return <>{text}; - const parts = text.split(new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "ig")); - return ( - <> - {parts.map((part, i) => (i % 2 === 1 ? {part} : {part}))} - - ); -} - -function ReadMore({ links }: { links: LearnLink[] }) { - return ( - - ); -} - -function Toc({ parts, active, showStart, showGlossary, onPick }: { parts: LearnPart[]; active: string; showStart: boolean; showGlossary: boolean; onPick?: () => void }) { - const item = (id: string, label: ReactNode, index?: number) => ( -
  • - - {index !== undefined && {String(index + 1).padStart(2, "0")}} - {label} - -
  • - ); - return ( - - ); -} - -export function LearnView({ me, startHere, parts, terms, sourceCount }: { me: Me | null; startHere: StartHere | null; parts: LearnPart[]; terms: LearnTerm[]; sourceCount: number }) { - const [query, setQuery] = useState(""); - const [active, setActive] = useState("start-here"); - const pendingHash = useRef(null); - const searchRef = useRef(null); - const mobileToc = useRef(null); - const q = query.trim().toLowerCase(); - - const termNames = useMemo(() => new Map(terms.map((t) => [t.id, t.term])), [terms]); - const shownParts = useMemo(() => (q ? parts.filter((p) => partHaystack(p).includes(q)) : parts), [parts, q]); - const shownTerms = useMemo(() => (q ? terms.filter((t) => termHaystack(t).includes(q)) : terms), [terms, q]); - const showStart = Boolean(startHere) && (!q || startHaystack(startHere!).includes(q)); - const partIndex = useMemo(() => new Map(parts.map((p, i) => [p.id, i])), [parts]); - - // "/" jumps to the search box, like most docs sites. - useEffect(() => { - const onKey = (e: KeyboardEvent) => { - const target = e.target as HTMLElement | null; - if (e.key !== "/" || e.metaKey || e.ctrlKey || target?.closest("input, textarea, [contenteditable]")) return; - e.preventDefault(); - searchRef.current?.focus(); - }; - window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); - }, []); - - // Highlight the section being read: the last one whose top has passed just under the sticky bars. - useEffect(() => { - let frame = 0; - const update = () => { - frame = 0; - const line = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) + 16 || 96; - let current = ""; - for (const section of document.querySelectorAll("[data-toc]")) { - if (section.getBoundingClientRect().top <= line) current = section.id; - else break; - } - setActive(current || document.querySelector("[data-toc]")?.id || ""); - }; - const onScroll = () => { - if (!frame) frame = requestAnimationFrame(update); - }; - onScroll(); - window.addEventListener("scroll", onScroll, { passive: true }); - window.addEventListener("resize", onScroll); - return () => { - cancelAnimationFrame(frame); - window.removeEventListener("scroll", onScroll); - window.removeEventListener("resize", onScroll); - }; - }, [shownParts, showStart, shownTerms.length]); - - // A term link clicked while searching clears the search first, then scrolls once the term is back. - useEffect(() => { - const hash = pendingHash.current; - if (q || !hash) return; - pendingHash.current = null; - document.getElementById(hash.slice(1))?.scrollIntoView({ block: "start" }); - history.replaceState(null, "", hash); - }, [q]); - - const jump = (e: MouseEvent) => { - if (!q) return; - e.preventDefault(); - pendingHash.current = e.currentTarget.getAttribute("href"); - setQuery(""); - }; - - const closeMobileToc = () => { - if (mobileToc.current) mobileToc.current.open = false; - }; - - const nothing = q && !showStart && shownParts.length === 0 && shownTerms.length === 0; - - return ( - -
    - - Skip to content - - -
    - - -
    -
    -

    StackWise Learn

    -

    The parts of a web app, in plain words

    -

    What each part does, how to pick one, the mistakes beginners make, and the best places to read more. Written for people building with AI tools.

    -
      -
    • - {parts.length} parts -
    • -
    • - {terms.length} terms -
    • -
    • - {sourceCount} sources -
    • -
    -
    - - setQuery(e.target.value)} - /> - -
    - {q && ( -

    - {shownParts.length} {shownParts.length === 1 ? "part" : "parts"} and {shownTerms.length} {shownTerms.length === 1 ? "term" : "terms"} match “{query.trim()}”. -

    - )} -
    - -
    - On this page - 0} onPick={closeMobileToc} /> -
    - - {nothing && ( -
    -

    Nothing matches “{query.trim()}”.

    - -
    - )} - - {startHere && showStart && ( -
    -

    Start here

    -

    - -

    -

    - -

    -
      - {startHere.layers.map((layer, i) => ( -
    1. - {i + 1} -
      -

      - -

      -

      - -

      -

      - -

      -
      -
    2. - ))} -
    - {startHere.read_more.length > 0 && ( -
    -

    Further reading

    - -
    - )} -
    - )} - - {shownParts.map((part) => ( -
    -

    Part {String((partIndex.get(part.id) ?? 0) + 1).padStart(2, "0")}

    -

    - - - -

    -

    - -

    - -
    -

    Why you need it

    -

    - -

    -
    - -
    -
    -

    How to choose

    -
      - {part.choosing.map((line) => ( -
    • - -
    • - ))} -
    -
    -
    -

    Common mistakes

    -
      - {part.watch_for.map((line) => ( -
    • - -
    • - ))} -
    -
    -
    - - {part.terms.length > 0 && ( -
    -

    Key terms

    - -
    - )} - - {part.read_more.length > 0 && ( -
    -

    Further reading

    - -
    - )} -
    - ))} - - {shownTerms.length > 0 && ( -
    -

    Reference

    -

    Glossary

    -

    The words you'll meet in docs, dashboards and AI answers.

    -
    - {shownTerms.map((t) => ( -
    -
    - - - -
    -
    -

    - -

    -

    - Why it matters -

    - {(t.read_more.length > 0 || t.usedIn.length > 0) && ( -
    - {t.usedIn.length > 0 && ( - - Used in{" "} - {t.usedIn.map((p, i) => ( - - {i > 0 && ", "} - - {p.label} - - - ))} - - )} - {t.read_more.map((link) => ( - - {link.source}: {link.title} - - - ))} -
    - )} -
    -
    - ))} -
    -
    - )} - -
    -

    Links go to the original publishers and open in a new tab. StackWise checks your plan against sourced facts; these pages explain the ideas behind those checks.

    - - Back to your plan - -
    -
    -
    -
    -
    - ); -} diff --git a/src/app/learn/learn.css b/src/app/learn/learn.css deleted file mode 100644 index 114b329..0000000 --- a/src/app/learn/learn.css +++ /dev/null @@ -1,640 +0,0 @@ -/* The Learn page (/learn): a docs-style page with a sticky table of contents. It reads the theme's - tokens (theme-apple.css over mk-ui.css), so light and dark follow the system like the planner. - The planner locks the body for its full-screen canvas; this page scrolls normally. */ - -html:has(.learn), -body:has(.learn) { - height: auto; - overflow: visible; -} -html:has(.learn) { - scroll-padding-top: 24px; -} -@media (prefers-reduced-motion: no-preference) { - html:has(.learn) { - scroll-behavior: smooth; - } -} - -/* Inside the shell (sidebar, scrolling page), with the table of contents where Settings has its section list. */ -.learn { - --learn-top-h: 0px; - --learn-toc-w: 196px; - color: var(--mk-text); - overflow-wrap: break-word; -} -.learn a { - color: inherit; -} -.learn mark { - background: color-mix(in srgb, var(--accent) 22%, transparent); - color: inherit; - border-radius: 3px; - padding: 0 1px; -} - -.learn-skip { - position: absolute; - left: 12px; - top: -48px; - z-index: 20; - padding: 8px 12px; - border-radius: var(--mk-radius); - background: var(--mk-surface); - box-shadow: var(--mk-shadow-2); -} -.learn-skip:focus { - top: 12px; -} - -/* ---------- Layout ---------- */ -.learn-shell { - display: grid; - grid-template-columns: var(--learn-toc-w) minmax(0, 1fr); - gap: 40px; - align-items: start; -} -.learn-main { - min-width: 0; - max-width: 780px; - padding: 0 0 48px; -} - -/* ---------- Table of contents ---------- */ -.learn-toc__inner { - position: sticky; - top: 44px; - max-height: calc(100vh - 60px); - overflow-y: auto; - padding: 0 8px 24px 0; - overscroll-behavior: contain; -} -.learn-toc__heading { - margin: 20px 0 6px; - padding: 0 10px; - font-size: 12px; - font-weight: 600; - color: var(--mk-text-muted); -} -.learn-toc__list { - list-style: none; - margin: 0; - padding: 0; - display: grid; - gap: 1px; -} -.learn-toc__link { - display: flex; - align-items: baseline; - gap: 10px; - padding: 7px 10px; - border-radius: 10px; - font-size: 14px; - font-weight: 500; - line-height: 1.35; - color: var(--mk-text) !important; - text-decoration: none; - transition: - background var(--mk-dur-fast) var(--mk-ease), - color var(--mk-dur-fast) var(--mk-ease); -} -.learn-toc__link:hover { - background: var(--ws-fill); - color: var(--mk-text) !important; -} -.learn-toc__link.is-active { - background: var(--ws-fill-strong, var(--ws-fill)); - color: var(--mk-text) !important; - font-weight: 600; -} -.learn-toc__num { - flex: none; - width: 18px; - font-family: var(--mk-font-mono); - font-size: 11px; - color: var(--mk-text-faint); -} -.learn-toc__link.is-active .learn-toc__num { - color: inherit; -} - -.learn-toc-mobile { - display: none; -} - -/* ---------- Hero and search ---------- */ -.learn-hero { - padding-bottom: 36px; - border-bottom: 1px solid var(--mk-line); -} -.learn-eyebrow { - margin: 0 0 8px; - font-size: 13px; - font-weight: 600; - color: var(--accent); - letter-spacing: 0; -} -.learn-title { - margin: 0; - font-family: var(--mk-font-display); - font-size: clamp(30px, 4.6vw, 44px); - line-height: 1.08; - font-weight: 700; - letter-spacing: -0.03em; - text-wrap: balance; -} -.learn-lead { - margin: 16px 0 0; - max-width: 62ch; - font-size: 18px; - line-height: 1.5; - color: var(--mk-text-muted); - text-wrap: pretty; -} -.learn-stats { - list-style: none; - margin: 20px 0 0; - padding: 0; - display: flex; - flex-wrap: wrap; - gap: 8px; -} -.learn-stats li { - padding: 4px 12px; - border-radius: var(--mk-radius-full); - background: var(--ws-fill); - font-size: 13px; - color: var(--mk-text-muted); -} -.learn-stats strong { - color: var(--mk-text); - font-weight: 600; -} -.learn-search { - position: relative; - margin-top: 28px; - max-width: 520px; - color: var(--mk-text-faint); -} -.learn-search > svg { - position: absolute; - left: 14px; - top: 50%; - transform: translateY(-50%); - pointer-events: none; -} -.learn .learn-search__input { - --mk-ctl-h: 44px; - width: 100%; - padding-left: 40px; - padding-right: 44px; - font-size: 16px; - border-radius: var(--mk-radius-lg); - background: var(--mk-surface); - box-shadow: var(--mk-shadow-1); -} -.learn-search__kbd { - position: absolute; - right: 12px; - top: 50%; - transform: translateY(-50%); - min-width: 22px; - padding: 1px 6px; - border: 1px solid var(--mk-line-strong); - border-radius: 6px; - font-family: var(--mk-font-mono); - font-size: 12px; - text-align: center; - color: var(--mk-text-muted); - background: var(--mk-surface-2); -} -.learn-search__input:focus + .learn-search__kbd, -.learn-search__input:not(:placeholder-shown) + .learn-search__kbd { - display: none; -} -.learn-search__count { - margin: 12px 0 0; - font-size: 14px; - color: var(--mk-text-muted); -} -.learn-empty { - margin-top: 40px; - padding: 28px; - border: 1px dashed var(--mk-line-strong); - border-radius: var(--mk-radius-lg); - text-align: center; - color: var(--mk-text-muted); -} -.learn-empty p { - margin: 0 0 12px; -} - -/* ---------- Sections ---------- */ -.learn-section { - padding: 56px 0 48px; - border-bottom: 1px solid var(--mk-line); -} -.learn-section:last-of-type { - border-bottom: 0; -} -.learn-h2 { - margin: 0; - font-family: var(--mk-font-display); - font-size: clamp(24px, 3.2vw, 30px); - line-height: 1.15; - font-weight: 700; - letter-spacing: -0.025em; -} -.learn-anchor { - text-decoration: none; -} -.learn-anchor:hover { - text-decoration: underline; - text-decoration-color: var(--mk-line-strong); - text-underline-offset: 4px; -} -.learn-what { - margin: 12px 0 0; - font-size: 18px; - line-height: 1.5; - color: var(--mk-text); - text-wrap: pretty; -} -.learn-block { - margin-top: 28px; -} -.learn-block > p { - margin: 0; - font-size: 16px; - line-height: 1.6; - color: var(--mk-text-muted); -} -.learn-h3 { - margin: 0 0 10px; - font-size: 13px; - font-weight: 600; - letter-spacing: 0.01em; - color: var(--mk-text-muted); -} - -.learn-grid { - margin-top: 28px; - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 16px; -} -.learn-card { - padding: 20px 20px 18px; - border-radius: var(--mk-radius-lg); - background: var(--mk-surface); - border: 1px solid var(--mk-line); - box-shadow: var(--mk-shadow-1); -} -.learn-card--warn { - background: color-mix(in srgb, var(--mk-warn) 5%, var(--mk-surface)); - border-color: color-mix(in srgb, var(--mk-warn) 22%, var(--mk-line)); -} -.learn-list { - list-style: none; - margin: 0; - padding: 0; - display: grid; - gap: 10px; -} -.learn-list li { - position: relative; - padding-left: 26px; - font-size: 15px; - line-height: 1.5; -} -.learn-list li::before { - content: ""; - position: absolute; - left: 0; - top: 3px; - width: 16px; - height: 16px; - border-radius: 50%; - background-position: center; - background-repeat: no-repeat; - background-size: 10px; -} -.learn-list--check li::before { - background-color: var(--mk-accent-soft); - -webkit-mask: none; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M2 5.2 4.1 7.2 8 3' fill='none' stroke='%23007aff' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); -} -.learn-list--warn li::before { - background-color: var(--mk-warn-soft); - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M5 2.2v3.4' stroke='%23e07b00' stroke-width='1.6' stroke-linecap='round'/%3E%3Ccircle cx='5' cy='7.7' r='0.9' fill='%23e07b00'/%3E%3C/svg%3E"); -} - -.learn-chips { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-wrap: wrap; - gap: 8px; -} -.learn-chip { - display: inline-flex; - align-items: center; - min-height: 30px; - padding: 4px 12px; - border-radius: var(--mk-radius-full); - background: var(--ws-fill); - font-size: 14px; - font-weight: 500; - text-decoration: none; - transition: background var(--mk-dur-fast) var(--mk-ease); -} -.learn-chip:hover { - background: var(--ws-fill-hover); -} - -/* Further reading: cards with the publisher on top, like a docs site's "related" links. */ -.learn-links { - list-style: none; - margin: 0; - padding: 0; - display: grid; - grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); - gap: 12px; -} -.learn-link { - position: relative; - display: flex; - flex-direction: column; - gap: 4px; - height: 100%; - padding: 14px 40px 14px 16px; - border-radius: var(--mk-radius-lg); - border: 1px solid var(--mk-line); - background: var(--mk-surface); - text-decoration: none; - transition: - border-color var(--mk-dur-fast) var(--mk-ease), - box-shadow var(--mk-dur-fast) var(--mk-ease), - transform var(--mk-dur-fast) var(--mk-ease); -} -.learn-link:hover { - border-color: color-mix(in srgb, var(--accent) 45%, var(--mk-line)); - box-shadow: var(--mk-shadow-1); -} -.learn-link:focus-visible, -.learn-chip:focus-visible, -.learn-toc__link:focus-visible { - outline: none; - box-shadow: var(--mk-focus-ring); -} -.learn-link__source { - font-size: 12px; - font-weight: 600; - color: var(--mk-text-muted); -} -.learn-link__title { - font-size: 15px; - font-weight: 500; - line-height: 1.35; - color: var(--mk-text); -} -.learn-link__arrow { - position: absolute; - right: 14px; - top: 16px; - color: var(--mk-text-faint); - transition: color var(--mk-dur-fast) var(--mk-ease); -} -.learn-link:hover .learn-link__arrow { - color: var(--accent); -} - -/* ---------- Start here ---------- */ -.learn-layers { - list-style: none; - margin: 28px 0 0; - padding: 0; - display: grid; - gap: 12px; -} -.learn-layer { - display: grid; - grid-template-columns: 32px minmax(0, 1fr); - gap: 16px; - padding: 18px 20px; - border-radius: var(--mk-radius-lg); - background: var(--mk-surface); - border: 1px solid var(--mk-line); - box-shadow: var(--mk-shadow-1); -} -.learn-layer__num { - display: grid; - place-items: center; - width: 32px; - height: 32px; - border-radius: 50%; - background: var(--mk-accent-soft); - color: var(--accent); - font-weight: 700; - font-size: 14px; -} -.learn-layer__name { - margin: 4px 0 4px; - font-size: 17px; - font-weight: 600; - letter-spacing: -0.01em; -} -.learn-layer p { - margin: 0; - font-size: 15px; - line-height: 1.5; - color: var(--mk-text-muted); -} -.learn-layer .learn-layer__rule { - margin-top: 8px; - color: var(--mk-text); - font-weight: 500; -} - -/* ---------- Glossary ---------- */ -.learn-terms { - margin: 28px 0 0; - display: grid; - gap: 0; - border-top: 1px solid var(--mk-line); -} -.learn-term { - display: grid; - grid-template-columns: 200px minmax(0, 1fr); - gap: 24px; - padding: 20px 0; - border-bottom: 1px solid var(--mk-line); -} -.learn-term:target { - margin: 0 -16px; - padding: 20px 16px; - border-radius: var(--mk-radius-lg); - background: var(--mk-accent-soft); - border-bottom-color: transparent; -} -.learn-term dt { - font-size: 16px; - font-weight: 600; - letter-spacing: -0.01em; -} -.learn-term dd { - margin: 0; -} -.learn-term dd p { - margin: 0; - font-size: 15px; - line-height: 1.55; -} -.learn-term .learn-term__matters { - margin-top: 8px; - color: var(--mk-text-muted); -} -.learn-term__label { - font-weight: 600; - color: var(--mk-text); -} -.learn-term__foot { - margin-top: 10px; - display: flex; - flex-wrap: wrap; - gap: 6px 16px; - font-size: 13px; - color: var(--mk-text-muted); -} -.learn-term__used a { - color: var(--accent); - text-decoration: none; -} -.learn-term__used a:hover, -.learn-term__read:hover { - text-decoration: underline; -} -.learn-term__read { - display: inline-flex; - align-items: center; - gap: 4px; - color: var(--accent) !important; - text-decoration: none; -} - -.learn-foot { - margin-top: 48px; - padding-top: 24px; - border-top: 1px solid var(--mk-line); - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 16px; - font-size: 13px; - color: var(--mk-text-muted); -} -.learn-foot p { - margin: 0; - max-width: 56ch; -} -.learn-foot .mk-btn { - text-decoration: none; -} - -/* ---------- Smaller screens ---------- */ -@media (max-width: 899px) { - html:has(.learn) { - scroll-padding-top: 124px; - } - .learn-shell { - display: block; - } - .learn-toc { - display: none; - } - .learn-main { - max-width: none; - padding-top: 32px; - } - .learn-toc-mobile { - display: block; - position: sticky; - top: 8px; - z-index: 5; - margin-top: 24px; - border-radius: var(--mk-radius-lg); - background: var(--ws-glass-strong); - -webkit-backdrop-filter: var(--ws-blur); - backdrop-filter: var(--ws-blur); - border: 1px solid var(--ws-glass-line); - box-shadow: var(--mk-shadow-1); - } - .learn-toc-mobile > summary { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px 16px; - font-size: 14px; - font-weight: 600; - cursor: pointer; - list-style: none; - } - .learn-toc-mobile > summary::-webkit-details-marker { - display: none; - } - .learn-toc-mobile > summary::after { - content: ""; - width: 8px; - height: 8px; - border-right: 1.8px solid var(--mk-text-muted); - border-bottom: 1.8px solid var(--mk-text-muted); - transform: rotate(45deg) translateY(-2px); - transition: transform var(--mk-dur-fast) var(--mk-ease); - } - .learn-toc-mobile[open] > summary::after { - transform: rotate(-135deg) translateY(-2px); - } - .learn-toc-mobile nav { - max-height: 60vh; - overflow-y: auto; - padding: 0 8px 12px; - } - .learn-toc-mobile .learn-toc__heading:first-child { - margin-top: 4px; - } - .learn-term { - grid-template-columns: 160px minmax(0, 1fr); - } -} - -@media (max-width: 640px) { - .learn-lead, - .learn-what { - font-size: 17px; - } - .learn-grid { - grid-template-columns: minmax(0, 1fr); - } - .learn-links { - grid-template-columns: minmax(0, 1fr); - } - .learn-section { - padding-top: 40px; - padding-bottom: 36px; - } - .learn-card, - .learn-layer { - padding: 16px; - } - .learn-term { - grid-template-columns: minmax(0, 1fr); - gap: 6px; - } - .learn-term:target { - margin: 0 -8px; - padding: 16px 8px; - } -} - diff --git a/src/app/learn/page.tsx b/src/app/learn/page.tsx deleted file mode 100644 index f08234a..0000000 --- a/src/app/learn/page.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import type { Metadata } from "next"; -import { loadCatalog } from "@/engine/load"; -import { readMe } from "@/local/home"; -import { LearnView, type LearnPart, type LearnTerm } from "./LearnView"; -import "../shell.css"; -import "./learn.css"; - -// Read /data on every request, like the planner, so edits to learn.json show up on refresh. -export const dynamic = "force-dynamic"; - -export const metadata: Metadata = { - title: "Learn | StackWise", - description: "Every part of a web app in plain words: what it does, how to choose one, the mistakes beginners make, and where to read more.", -}; - -/** - * The Learn page: the teaching content from data/learn.json as a docs-style page. Deep links are - * `/learn#part-`, `/learn#term-` and `/learn#start-here`. - */ -export default function LearnPage() { - const catalog = loadCatalog(); - const { learn } = catalog; - - const parts: LearnPart[] = catalog.slots.flatMap((slot) => { - const entry = learn.slots[slot.id]; - return entry ? [{ id: slot.id, label: slot.label, ...entry }] : []; - }); - - // Each term lists the parts that use it, so the glossary links back to them. - const terms: LearnTerm[] = Object.entries(learn.terms) - .map(([id, t]) => ({ id, ...t, usedIn: parts.filter((p) => p.terms.includes(id)).map((p) => ({ id: p.id, label: p.label })) })) - .sort((a, b) => a.term.localeCompare(b.term, "en", { sensitivity: "base" })); - - const sources = new Set( - [...(learn.start_here?.read_more ?? []), ...parts.flatMap((p) => p.read_more), ...terms.flatMap((t) => t.read_more)].map((link) => link.source), - ); - - return ; -} diff --git a/src/app/settings/SettingsView.tsx b/src/app/settings/SettingsView.tsx index dd73394..20fcaea 100644 --- a/src/app/settings/SettingsView.tsx +++ b/src/app/settings/SettingsView.tsx @@ -6,7 +6,7 @@ import { providersOf, recipientsFor, saveDefaultAnswerer, saveProviderSetting, S import { KeyForm } from "@/components/ConnectPanel"; import { Icon, type IconName } from "@/components/icons"; import type { AiStatus, ProviderInfo } from "@/components/Planner"; -import { Shell, shortPath, useMe, type Me } from "@/components/Shell"; +import { Shell, shortPath, useMe, type Me, type ShellSections } from "@/components/Shell"; import { useTheme, type Theme } from "@/components/ThemeSwitch"; import { copyText, cx } from "@/components/ui"; import { FEATURED_AGENTS, pairInstructions } from "@/mcp/pairing"; @@ -351,30 +351,19 @@ export default function SettingsView({ builders, priorities, sizes }: { builders ); + const sidebar: ShellSections = { title: "Settings", items: SECTIONS.map((s) => ({ id: s.id, label: s.label, href: `/settings#${s.id}`, icon: s.icon, active: section === s.id, onSelect: () => show(s.id) })) }; + return ( - +
    -

    Settings

    -

    Saved in {me ? shortPath(me.dir, me.home) : "~/.stackwise"} on this computer.

    +

    {current.label}

    +

    {current.blurb}

    -
    - - +
    -
    -

    {current.label}

    -

    {current.blurb}

    -
    {section === "account" && ( <> diff --git a/src/app/shell.css b/src/app/shell.css index 28f7102..19979d1 100644 --- a/src/app/shell.css +++ b/src/app/shell.css @@ -9,13 +9,16 @@ body:has(.shell) { } .shell { - --shell-side: 248px; - --shell-gutter: 40px; + --shell-side: 224px; + --shell-gutter: 32px; display: grid; grid-template-columns: var(--shell-side) minmax(0, 1fr); min-height: 100vh; background: var(--mk-bg); color: var(--mk-text); + /* The same size as the canvas's own text; the body's 15px is for the planner's prose. */ + font-size: 14px; + line-height: 1.5; overflow-wrap: break-word; } @@ -26,7 +29,7 @@ body:has(.shell) { flex-direction: column; gap: 18px; height: 100vh; - padding: 18px 14px 16px; + padding: 14px 12px 14px; border-right: 1px solid var(--ws-glass-line); background: var(--ws-glass); -webkit-backdrop-filter: var(--ws-blur); @@ -38,7 +41,7 @@ body:has(.shell) { gap: 9px; padding: 4px 8px; color: inherit; - font-size: 15px; + font-size: 13px; font-weight: 650; letter-spacing: -0.015em; text-decoration: none; @@ -56,12 +59,12 @@ body:has(.shell) { display: grid; flex: none; place-items: center; - width: 36px; - height: 36px; + width: 32px; + height: 32px; border-radius: 50%; background: linear-gradient(135deg, var(--mk-accent), color-mix(in srgb, var(--mk-accent) 55%, #af52de)); color: #fff; - font-size: 15px; + font-size: 13px; font-weight: 700; } .shell-me__text { @@ -72,7 +75,7 @@ body:has(.shell) { } .shell-me__text strong { overflow: hidden; - font-size: 14px; + font-size: 13px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; @@ -100,7 +103,7 @@ body:has(.shell) { background: none; color: var(--mk-text); font: inherit; - font-size: 14px; + font-size: 13px; font-weight: 500; text-align: left; text-decoration: none; @@ -146,19 +149,19 @@ body:has(.shell) { .shell-main { display: flex; flex-direction: column; - gap: 36px; + gap: 28px; width: 100%; - max-width: 1080px; + max-width: 960px; min-width: 0; - padding: 44px var(--shell-gutter) 96px; + padding: 32px var(--shell-gutter) 80px; } .shell-title { - font-size: 30px; + font-size: 24px; font-weight: 700; letter-spacing: -0.025em; } .shell-h2 { - font-size: 19px; + font-size: 17px; font-weight: 650; letter-spacing: -0.015em; } @@ -196,7 +199,7 @@ body:has(.shell) { display: flex; flex-direction: column; gap: 14px; - padding: 18px 20px; + padding: 16px 18px; border: 0.5px solid var(--ws-glass-line); border-radius: 16px; background: var(--mk-surface); @@ -343,6 +346,28 @@ body:has(.shell) { margin-top: 12px; } +/* A page's own sections in the sidebar, under the pages. */ +.shell-subnav { + display: flex; + flex-direction: column; + gap: 2px; + padding-top: 6px; + border-top: 0.5px solid var(--ws-glass-line); +} +.shell-subnav__title { + margin: 8px 0 4px; + padding: 0 10px; + color: var(--mk-text-faint); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} +.shell-subnav__item { + width: 100%; + font-size: 13px; +} + /* Found under your folders: a quieter card than a plan. */ .apps-card--found .apps-icon { background: var(--mk-surface-sunk); @@ -383,7 +408,7 @@ body:has(.shell) { padding-top: 24px; } .shell-title { - font-size: 26px; + font-size: 22px; } .shell-search { width: 100%; @@ -400,6 +425,15 @@ html[data-desktop] .shell-side button, html[data-desktop] .shell-side .shell-me { -webkit-app-region: no-drag; } +/* Full screen hides the traffic lights (preload.cjs sets data-fullscreen; the media query is the fallback). */ +html[data-desktop][data-fullscreen] .shell-side { + padding-top: 14px; +} +@media (display-mode: fullscreen) { + html[data-desktop] .shell-side { + padding-top: 14px; + } +} @media (max-width: 720px) { html[data-desktop] .shell-side { padding-top: 10px; @@ -414,6 +448,9 @@ html[data-desktop] .shell-side .shell-me { gap: 40px; align-items: start; } +.set-layout--one { + grid-template-columns: minmax(0, 1fr); +} .set-nav { position: sticky; top: 44px; @@ -431,7 +468,7 @@ html[data-desktop] .shell-side .shell-me { background: none; color: var(--mk-text); font: inherit; - font-size: 14px; + font-size: 13px; font-weight: 500; text-align: left; cursor: pointer; @@ -487,9 +524,9 @@ html[data-desktop] .shell-side .shell-me { gap: 14px; } .set-me .shell-avatar { - width: 48px; - height: 48px; - font-size: 20px; + width: 40px; + height: 40px; + font-size: 17px; } .set-seg { display: inline-flex; diff --git a/src/components/AskPanel.tsx b/src/components/AskPanel.tsx index e71c82d..41ca19f 100644 --- a/src/components/AskPanel.tsx +++ b/src/components/AskPanel.tsx @@ -1,16 +1,17 @@ "use client"; import { useRouter } from "next/navigation"; -import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { Fragment, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { answerFromFacts, evaluatePlan, inSentence, planInput, questionFocus, talkBrief, worstLevel, type SlotId } from "@/engine"; import { agentName, mcpAddress, pairInstructions } from "@/mcp/pairing"; import { AnswererMark } from "./AnswererMark"; -import { answererLogo, providerLabel, providersOf, recipientsFor, pickDefault, saveProviderSetting, STATE_TEXT, type Recipient, type RecipientId } from "./answerers"; +import { describeAgentModel, wantsLongContext, answererLogo, providerLabel, providersOf, recipientsFor, pickDefault, saveProviderSetting, STATE_TEXT, type Recipient, type RecipientId } from "./answerers"; +import { foldLookups, isChangeActivity, isLong, parseChatText, type Inline } from "./chatText"; import { ContextMenu, type MenuItem, type MenuRequest } from "./ContextMenu"; import { Icon, type IconName } from "./icons"; import { PanelEdge } from "./PanelEdge"; import type { AiStatus, ProviderInfo } from "./Planner"; -import { toSharedPlan, type ChatTurn } from "./store"; +import { toSharedPlan, type ChatAgentItem, type ChatTurn } from "./store"; import type { AgentMessage, ClaudeActivity, Pairing } from "./usePairing"; import { newId, type PlanModel } from "./usePlans"; import { Logo, VerdictBadge, copyText, cx, undoHint, type Verdict } from "./ui"; @@ -80,6 +81,8 @@ const PROVIDERS: Provider[] = [ ]; /** A model's short name as the provider's page gives it, else its id. */ const modelNameOf = (api: ProviderInfo, id: string) => api.modelInfo?.find((x) => x.id === id)?.name ?? id; +/** "Oct 22, 3:41 PM": when a past chat ended. */ +const when = (iso: string) => new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); /** The provider a recipient belongs to; an agent or API outside the list gets a provider of its own. */ function providerFor(id: RecipientId, ai: AiStatus | null): Provider { @@ -107,30 +110,64 @@ interface TalkResponse { const now = () => new Date().toISOString(); -/** Plain text with "- " and "1. " lines shown as lists. Nothing else is interpreted. */ -function Formatted({ text }: { text: string }) { - const blocks: ReactNode[] = []; - const lines = text.split("\n").map((line) => line.trim()); - let i = 0; - while (i < lines.length) { - const ordered = /^\d+\.\s/.test(lines[i]); - if (ordered || /^[-*]\s/.test(lines[i])) { - const items: string[] = []; - while (i < lines.length && (ordered ? /^\d+\.\s/ : /^[-*]\s/).test(lines[i])) items.push(lines[i++].replace(/^(\d+\.|[-*])\s+/, "")); - const Tag = ordered ? "ol" : "ul"; - blocks.push( - - {items.map((item, n) => ( -
  • {item}
  • - ))} -
    , - ); - } else { - if (lines[i]) blocks.push(

    {lines[i]}

    ); - i++; - } - } - return <>{blocks}; +function Inlines({ parts }: { parts: Inline[] }) { + return ( + <> + {parts.map((part, n) => (part.kind === "strong" ? {part.text} : part.kind === "code" ? {part.text} : {part.text}))} + + ); +} + +/** + * A message as the pane shows it: headings, lists, bold and code read from the text (chatText.ts), + * built as elements so nothing in it can inject markup. With `fold`, a long reply shows its first + * screen and a "Show more" link. + */ +function Formatted({ text, fold = false }: { text: string; fold?: boolean }) { + const [open, setOpen] = useState(false); + const folds = fold && isLong(text); + return ( + <> +
    + {parseChatText(text).map((block, n) => + block.kind === "heading" ? ( +

    + +

    + ) : block.kind === "list" ? ( + block.ordered ? ( +
      + {block.items.map((item, k) => ( +
    1. + +
    2. + ))} +
    + ) : ( +
      + {block.items.map((item, k) => ( +
    • + +
    • + ))} +
    + ) + ) : block.kind === "code" ? ( +
    {block.text}
    + ) : ( +

    + +

    + ), + )} +
    + {folds && ( + + )} + + ); } /** How much of the model's context window the next message would use, as a ring that fills. */ @@ -176,9 +213,9 @@ function Turn({ model, turn, ai, onToast }: { model: PlanModel; turn: ChatTurn; return (
    - {turn.role === "claude" ? providerLabel(ai, turn.by) : "StackWise facts"} + {turn.by === "summary" ? "Earlier chat, compacted" : turn.role === "claude" ? providerLabel(ai, turn.by) : "StackWise facts"}
    - +
    {turn.proposal && turn.proposal.status === "open" && ( @@ -254,11 +291,8 @@ function AgentTurn({ message }: { message: AgentMessage }) { const name = agentName(message.agent); if (message.from === "you") { return ( -
    +
    - - To {name}, {message.deliveredAt ? "picked up" : "waiting"} -
    ); } @@ -270,7 +304,7 @@ function AgentTurn({ message }: { message: AgentMessage }) { {message.status === "needs_you" && " needs you"}
    - +
    {message.files && message.files.length > 0 && (
    @@ -285,14 +319,15 @@ function AgentTurn({ message }: { message: AgentMessage }) { const TOOL_LABELS: Record = { update_plan: "Changed the plan", - check_stack: "Checked a stack", - recommend_stack: "Recommended a stack", - compare_options: "Compared options", - estimate_costs: "Estimated costs", - export_project: "Exported the project", + export_project: "Wrote the project", sync_plan_file: "Merged the plan file", }; +/** The agent asking StackWise instead of guessing, as one quiet line: "Checked StackWise: compared ...". */ +function LookupLine({ phrases }: { phrases: string[] }) { + return

    Checked StackWise: {phrases.join("; ")}.

    ; +} + function ActivityRow({ activity }: { activity: ClaudeActivity }) { return (
    @@ -457,18 +492,36 @@ export function AskPanel({ }; const subject = slot === "framework" ? plan.appName.trim() || "your app" : option ? option.name : inSentence(index.slotsById.get(slot)?.label ?? slot); + // What agents said and did in this chat: what a reopened past chat carried, then everything since the chat began. + // New chat starts the clock again, so the pane clears without touching the shared plan's messages. + const agentItems = useMemo((): ChatAgentItem[] => { + const since = plan.chatSince ?? ""; + return [ + ...(plan.chatAgent ?? []), + ...pairing.messages.filter((message) => message.at >= since).map((message): ChatAgentItem => ({ kind: "message", message })), + ...pairing.activity.filter((activity) => activity.at >= since).map((activity): ChatAgentItem => ({ kind: "activity", activity })), + ]; + }, [plan.chatSince, plan.chatAgent, pairing.messages, pairing.activity]); + // One timeline: the built-in AI's turns (in this browser) and the agents' messages and changes (on the server). const items = useMemo(() => { const list: Item[] = plan.chat.map((turn) => ({ at: turn.at, key: `t-${turn.id}`, about: turn.about, node: })); // An agent's reply is about whatever the person last asked that agent. const lastAbout: Record = {}; - for (const message of pairing.messages) { + const messages = agentItems.flatMap((item) => (item.kind === "message" ? [item.message] : [])).sort((a, b) => a.at.localeCompare(b.at)); + for (const message of messages) { if (message.from === "you") lastAbout[message.agent] = message.about; list.push({ at: message.at, key: `m-${message.id}`, about: message.from === "you" ? message.about : lastAbout[message.agent], node: }); } - for (const activity of pairing.activity) list.push({ at: activity.at, key: `a-${activity.id}`, node: }); - return list.sort((a, b) => a.at.localeCompare(b.at)); - }, [plan.chat, pairing.messages, pairing.activity, model, ai, onToast]); + // A change to the plan or the project gets a card; the agent's lookups fold into one quiet line. + const lookups: { at: string; key: string; lookup: string }[] = []; + for (const item of agentItems) { + if (item.kind !== "activity") continue; + if (isChangeActivity(item.activity)) list.push({ at: item.activity.at, key: `a-${item.activity.id}`, node: }); + else lookups.push({ at: item.activity.at, key: `a-${item.activity.id}`, lookup: item.activity.summary }); + } + return foldLookups([...list, ...lookups].sort((a, b) => a.at.localeCompare(b.at))).map((entry): Item => ("lookups" in entry ? { at: entry.at, key: entry.key, node: } : entry)); + }, [plan.chat, agentItems, model, ai, onToast]); const shown = onlyThis ? items.filter((item) => item.about === slot) : items; const mixed = new Set(items.map((i) => i.about).filter(Boolean)).size > 1; @@ -597,7 +650,8 @@ export function AskPanel({ const body = (await r.json()) as { agents?: { id: string; model?: string | null }[]; error?: string }; if (!r.ok || !body.agents) throw new Error(body.error ?? "Couldn't set Claude Code's model."); setAgentModels(Object.fromEntries(body.agents.map((a) => [a.id, a.model ?? null]))); - onToast(value ? `New Claude Code sessions start with ${modelNameOf(api ?? ({ models: [] } as unknown as ProviderInfo), value)}. A session already open switches with /model.` : "Claude Code is back on its own default model."); + const d = describeAgentModel(value, api?.modelInfo ?? []); + onToast(d ? `New Claude Code sessions start with ${d.name}${d.note ? ` (${d.note})` : ""}. A session already open switches with /model.` : "Claude Code is back on its own default model."); } catch (e) { onToast(e instanceof Error ? e.message : "Couldn't set Claude Code's model."); } finally { @@ -650,6 +704,8 @@ export function AskPanel({ * model Claude Code's own settings start new sessions with, which StackWise can set too. */ const agentModel = provider.agent ? (agentModels[provider.agent] ?? null) : null; + const agentPick = api ? describeAgentModel(agentModel, api.modelInfo ?? []) : null; + const longContext = wantsLongContext(agentModel); const openModelMenu = (e: React.MouseEvent) => { const box = e.currentTarget.getBoundingClientRect(); const items: MenuItem[] = []; @@ -663,19 +719,23 @@ export function AskPanel({ const current = api.model || api.defaultModel; const info = (id: string) => api.modelInfo?.find((x) => x.id === id); items.push({ kind: "separator" }, { kind: "header", label: viaAgent ? "Model for new Claude Code sessions" : "Model" }); + // Through Claude Code the setting is its own (an alias or an id, "[1m]" for the 1M window); the + // menu reads it and writes it back the same way, so a pick keeps the window and the window keeps the pick. + const picked = viaAgent ? (agentPick?.id ?? null) : null; if (viaAgent) { - const other = agentModel && !models.includes(agentModel) ? agentModel : null; - items.push({ label: other ? `As Claude Code has it: ${other}` : "Claude Code's own default", checked: !agentModel || Boolean(other), onSelect: () => void setAgentModel("") }); + items.push({ label: "Claude Code's own default", checked: !picked, onSelect: () => void setAgentModel("") }); + if (picked && !models.includes(picked)) items.push({ label: `As Claude Code has it: ${agentPick!.raw}`, checked: true, onSelect: () => {} }); } for (const m of models) { const known = info(m); items.push({ label: `${known?.name ?? m}${!viaAgent && m === api.defaultModel ? " (default)" : ""}`, hint: known?.price, - checked: viaAgent ? agentModel === m : recipient.id === `api:${api.id}` && current === m, + checked: viaAgent ? picked === m : recipient.id === `api:${api.id}` && current === m, onSelect: () => { if (viaAgent) { - if (m !== agentModel) void setAgentModel(m); + const next = `${m}${longContext ? "[1m]" : ""}`; + if (next !== agentModel) void setAgentModel(next); return; } setChosen(`api:${api.id}`); @@ -683,11 +743,36 @@ export function AskPanel({ }, }); } + if (viaAgent && picked) { + items.push( + { kind: "separator" }, + { kind: "header", label: "Context window" }, + { label: "Standard", checked: !longContext, onSelect: () => void (longContext && setAgentModel(picked)) }, + { label: "1M tokens", hint: "[1m]", checked: longContext, onSelect: () => void (!longContext && setAgentModel(`${picked}[1m]`)) }, + ); + } items.push({ kind: "separator" }, { label: "Another model, or a key", icon: "tool", onSelect: () => router.push("/settings#models") }); } if (provider.id === "facts") items.push({ label: "Facts only, no AI", checked: true, onSelect: () => setChosen("facts") }); setMenu({ x: box.left, y: box.top - 6, items }); }; + // Past chats: the conversations New chat put away, newest first; opening one puts the current away the same way. + const openHistoryMenu = (e: React.MouseEvent) => { + const box = e.currentTarget.getBoundingClientRect(); + const items: MenuItem[] = [{ kind: "header", label: "Past chats" }]; + for (const past of plan.pastChats) { + items.push({ + label: past.title || "Untitled chat", + hint: past.summary !== undefined ? `${when(past.endedAt)}, compacted` : when(past.endedAt), + onSelect: () => { + dispatch({ type: "openChat", id: past.id, at: now(), agent: agentItems }); + onToast(items.length ? "Opened a past chat. The one you were in is in Past chats now." : "Opened a past chat."); + }, + }); + } + items.push({ kind: "separator" }, { label: "Forget past chats", icon: "trash", danger: true, onSelect: () => dispatch({ type: "forgetChats" }) }); + setMenu({ x: box.left, y: box.bottom + 6, items }); + }; // The ring: what the next message would send (this part's brief, the recent turns, the draft) against the model's window. const apiModelInfo = api && !agent ? api.modelInfo?.find((x) => x.id === (api.model || api.defaultModel)) : undefined; const contextUsed = Math.round( @@ -700,18 +785,19 @@ export function AskPanel({ CHARS_PER_TOKEN, ); - // The bubble names the model alone; the provider bubble already says whose it is. - const modelLabel = agent - ? agentModel && api - ? modelNameOf(api, agentModel) - : "Default model" + // The bubble names the model alone, with a note for its window or mode; the provider bubble + // already says whose it is. A placeholder (no key, facts only) reads quieter than a name. + const modelShown: { name: string; note: string | null; placeholder: boolean } = agent + ? agentPick?.id + ? { name: agentPick.name, note: agentPick.note, placeholder: false } + : { name: "Default model", note: null, placeholder: true } : provider.id === "facts" - ? "Facts only" + ? { name: "Facts only", note: null, placeholder: true } : api ? api.on - ? modelNameOf(api, api.model || api.defaultModel || "") || "Default model" - : "Needs a key" - : recipient.label; + ? { name: modelNameOf(api, api.model || api.defaultModel || "") || "Default model", note: null, placeholder: !(api.model || api.defaultModel) } + : { name: "Needs a key", note: null, placeholder: true } + : { name: recipient.label, note: null, placeholder: true }; const listening = recipient.group === "agent" && (recipient.state === "listening" || recipient.state === "working"); const starters = [...(slot === "framework" ? APP_STARTERS : PART_STARTERS), ...(listening ? [AGENT_STARTER] : [])]; @@ -732,31 +818,37 @@ export function AskPanel({ }} >
    - - {plan.appName.trim() || "Untitled app"} - {slot !== "framework" && ` · ${index.slotsById.get(slot)?.label ?? slot}`} - + + + + + {mixed && ( + + )} + - {mixed && ( - - )} -
    @@ -825,8 +917,9 @@ export function AskPanel({ - {apiModelInfo && } diff --git a/src/components/PlanCanvas.tsx b/src/components/PlanCanvas.tsx index a184db2..a8b96c9 100644 --- a/src/components/PlanCanvas.tsx +++ b/src/components/PlanCanvas.tsx @@ -442,7 +442,7 @@ interface ZoneData extends Record { function ZoneNode({ data }: NodeProps>) { return ( diff --git a/src/components/Shell.tsx b/src/components/Shell.tsx index ea52f89..4d78817 100644 --- a/src/components/Shell.tsx +++ b/src/components/Shell.tsx @@ -46,11 +46,21 @@ export const shortPath = (p: string, home: string | undefined) => (home && p.sta const NAV: { href: string; label: string; icon: IconName }[] = [ { href: "/projects", label: "Projects", icon: "grid" }, - { href: "/learn", label: "Learn", icon: "learn" }, + { href: "/docs", label: "Documentation", icon: "info" }, { href: "/review", label: "Review facts", icon: "checklist" }, ]; -export function Shell({ me, children }: { me: Me | null; children: React.ReactNode }) { +/** + * A page's own sections, shown in the sidebar under the pages: Settings' Account, General and so + * on. A page can have more than one group (the documentation: Learn, then the project's docs). + */ +export interface ShellSections { + title: string; + items: { id: string; label: string; href: string; active?: boolean; icon?: IconName; onSelect?: () => void }[]; +} + +export function Shell({ me, sections, children }: { me: Me | null; sections?: ShellSections | ShellSections[]; children: React.ReactNode }) { + const groups = sections ? [sections].flat() : []; const pathname = usePathname() ?? ""; const name = me?.profile.name.trim() || me?.account || ""; const initial = (name || "S").slice(0, 1).toUpperCase(); @@ -78,10 +88,28 @@ export function Shell({ me, children }: { me: Me | null; children: React.ReactNo ))} + {groups.map((group) => ( + + ))}
    - - - Documentation + + + GitHub diff --git a/src/components/Workspace.tsx b/src/components/Workspace.tsx index eede1b9..6357f09 100644 --- a/src/components/Workspace.tsx +++ b/src/components/Workspace.tsx @@ -91,8 +91,8 @@ const isMac = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(n export default function Workspace({ catalog, problems }: { catalog: Catalog; problems: string[] }) { const model = usePlans(catalog); const router = useRouter(); - /** Learn is its own page; a part opens at its section there. The plan waits in this browser. */ - const openLearn = useCallback((slot?: SlotId | null) => router.push(`/learn${slot ? `#part-${slot}` : ""}`), [router]); + /** Learn is the first part of the Documentation page; a part opens at its entry there. The plan waits in this browser. */ + const openLearn = useCallback((slot?: SlotId | null) => router.push(`/docs#${slot ? `part-${slot}` : "start-here"}`), [router]); const { plan, dispatch, history, rec, index } = model; const [selectedSlot, setSelectedSlot] = useState(null); /** The part at the far end of the connection being looked at, when one is. */ @@ -713,8 +713,13 @@ export default function Workspace({ catalog, problems }: { catalog: Catalog; pro + + + + {building && openPanel("overview")} />}
    - {building && openPanel("overview")} />}