From fb31abf74cec9249c14bf69aa1c9e92f6762689a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berke=20Ba=C5=9Fbay?= <132104179+berkebasbay@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:08:00 +0300 Subject: [PATCH] Add a guided first simulation experiment --- docs/QUALITY.md | 2 + docs/QUICKSTART.md | 10 ++ docs/UX_GUIDE.md | 10 +- package-lock.json | 4 +- package.json | 3 +- scripts/facility-edge-smoke.mjs | 4 +- scripts/facility-navigation-smoke.mjs | 3 +- scripts/facility-smoke.mjs | 4 +- scripts/facility-workspace-smoke.mjs | 4 +- scripts/interface-polish-smoke.mjs | 4 +- scripts/learning-smoke.mjs | 159 ++++++++++++++++++ scripts/starter-collection-smoke.mjs | 4 +- scripts/templates-smoke.mjs | 6 +- scripts/templates-storage-smoke.mjs | 5 +- scripts/ui-actions.mjs | 13 ++ scripts/ux-smoke.mjs | 8 +- src/App.tsx | 232 ++++++++++++++++++++++++-- src/features/LearningGuide.tsx | 59 +++++++ src/features/ProcessList.tsx | 2 +- src/features/QuickProperties.tsx | 9 +- src/features/TemplatesPanel.tsx | 4 +- src/features/learning.css | 10 ++ src/features/learning.ts | 86 ++++++++++ src/ui/messages/App.ts | 6 +- src/ui/messages/learning.ts | 42 +++++ src/ui/messages/shellEase.ts | 3 +- tests/learning.test.ts | 80 +++++++++ 27 files changed, 727 insertions(+), 49 deletions(-) create mode 100644 scripts/learning-smoke.mjs create mode 100644 src/features/LearningGuide.tsx create mode 100644 src/features/learning.css create mode 100644 src/features/learning.ts create mode 100644 src/ui/messages/learning.ts create mode 100644 tests/learning.test.ts diff --git a/docs/QUALITY.md b/docs/QUALITY.md index 1d95a71..dffc30e 100644 --- a/docs/QUALITY.md +++ b/docs/QUALITY.md @@ -25,6 +25,8 @@ QUEUELAB_URL=http://127.0.0.1:4173 QUEUELAB_UX_PHASE=core node scripts/ux-smoke. The script uses isolated browser contexts and synthetic models. It requires Playwright browser binaries; it does not install them. Generated screenshots and files stay outside version control. +Run `QUEUELAB_URL=http://127.0.0.1:4173 npm run test:learning` for the first experiment: real selection/edit/run/compare/template save at desktop and 320/390 px, keyboard focus, reduced motion, refresh, original-project/history restoration, storage errors and cancelled loading. Other smoke checks use the welcome's public **Explore on my own** path before testing the workspace. + The facility flow has a separate isolated smoke command: ```sh diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 98b76cd..d2dc236 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -1,5 +1,15 @@ # Quickstart +## Learn by doing + +On your first visit, choose **Start my first experiment**. You can also open **Learn by doing** from the playground at any time. + +The five-step exercise opens a separate Service Studio project. Select **Specialists**, change its shared team from **2** to **3**, run the changed plan, compare completed work, waiting and resource cost, then optionally save your own template. The guide highlights the actual controls and follows your applied edits and completed calculations. + +You can minimize or leave the guide at any time. Existing work is saved before practice starts; **Back to my previous project** reopens it. Refreshing an active practice restores its saved draft and asks you to run again before comparing. Templates and projects stay in this browser; download project JSON for a portable backup. + +Choose **Explore on my own** to start without the exercise, or **Just show me the controls** for a short reference tour. + ## Open a world Open **[the live demo](https://berkebasbay.github.io/loopset/)**. No installation or account is required. diff --git a/docs/UX_GUIDE.md b/docs/UX_GUIDE.md index 35fef69..5896b24 100644 --- a/docs/UX_GUIDE.md +++ b/docs/UX_GUIDE.md @@ -6,10 +6,18 @@ Start with a process question: which arrival rate, processing time, team or wait **Tools → A little guidance → Watch the video demos** opens the English quick tour and full walkthrough in a new tab, leaving the current project open. -**How it works** in the world opens the optional three-step guide: change one thing, run the changed plan, compare and keep it. On a phone, select a world object and use **Edit selected step** below the scene. Scenario settings links directly to arrivals and related team controls. +**Learn by doing → Just show me the controls** opens the optional three-step guide: change one thing, run the changed plan, compare and keep it. On a phone, select a world object and use **Edit selected step** below the scene. Scenario settings links directly to arrivals and related team controls. The team’s base availability is visible in Properties. Installed capacity, cost and shifts have their own disclosures. A capacity note explains when the base team cannot staff every parallel station; shared use and calendar overrides remain separate limits. Short duration readouts retain the exact editable value when focused. +## Guided first experiment + +**Learn by doing** opens a five-step Service Studio practice: select Specialists, apply a shared-team change, calculate, read the comparison and optionally save a reusable template. Progress follows real edits and completed runs. Highlighted controls remain ordinary editor controls with the same validation and Undo behavior. + +The guide can be minimized or dismissed. It preserves an existing project before switching, offers a return action and resumes a saved practice after refresh. If you change other numerical inputs, it lets you keep exploring or start a fresh practice. Failed calculations and template saves remain incomplete and can be retried. The optional finish path explicitly says that no template was saved. + +A first-visit welcome is shown only when no saved project is restored. Returning users can start the exercise from the playground. **Just show me the controls** retains the short reference tour. + ## Start from a template **Templates** contains twelve facilities, including Workshop, Factory, Festival and Service, alongside **Blank**, a site with no objects or process steps. Search or filter by category, inspect a preview and its assumptions, then choose **Open this template**. The Asset library also offers **Empty site**. Place objects first; choose **Start a process** when ready to add a runnable flow. diff --git a/package-lock.json b/package-lock.json index 7b6e901..95cdb48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "queuelab", - "version": "1.0.0-rc.14", + "version": "1.0.0-rc.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "queuelab", - "version": "1.0.0-rc.14", + "version": "1.0.0-rc.15", "license": "MIT", "dependencies": { "lucide-react": "1.60.0", diff --git a/package.json b/package.json index 52a48f0..998f97a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "queuelab", - "version": "1.0.0-rc.14", + "version": "1.0.0-rc.15", "private": true, "type": "module", "description": "A playable process and capacity simulation laboratory", @@ -15,6 +15,7 @@ "simulate": "node scripts/simulate.mjs", "examples:export": "npm run build:engine && node scripts/export-examples.mjs", "test:headless": "npm run build:engine && node examples/verify.mjs", + "test:learning": "node scripts/learning-smoke.mjs", "test:ux": "node scripts/ux-smoke.mjs", "setup:hooks": "node scripts/setup-hooks.mjs", "check:publication": "node scripts/check-publication.mjs", diff --git a/scripts/facility-edge-smoke.mjs b/scripts/facility-edge-smoke.mjs index c323b85..e7eee70 100644 --- a/scripts/facility-edge-smoke.mjs +++ b/scripts/facility-edge-smoke.mjs @@ -3,7 +3,7 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; import * as THREE from 'three'; -import { headerProjectInput, runPlan } from './ui-actions.mjs'; +import { dismissLearningWelcome, headerProjectInput, runPlan } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['localhost', '127.0.0.1'].includes(origin.hostname)); @@ -18,7 +18,7 @@ const ready = page => page.waitForFunction(() => { const state = JSON.parse(wind async function fresh(width = 1440) { const context = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: 'reduce', acceptDownloads: true }); const page = await context.newPage(); page.on('pageerror', error => errors.push(String(error))); - await page.goto(origin.href); await ready(page); + await page.goto(origin.href); await dismissLearningWelcome(page); await ready(page); // Use the original numerical fixture for these compatibility checks. if (width > 740) { await page.locator('.studio-world-picker select').selectOption('factory'); await ready(page); } const pause = page.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); diff --git a/scripts/facility-navigation-smoke.mjs b/scripts/facility-navigation-smoke.mjs index a556856..1a3c85c 100644 --- a/scripts/facility-navigation-smoke.mjs +++ b/scripts/facility-navigation-smoke.mjs @@ -1,3 +1,4 @@ +import { dismissLearningWelcome } from './ui-actions.mjs'; import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; @@ -9,7 +10,7 @@ await fs.mkdir(out, { recursive: true }); await fs.mkdir('.cache/tmp', { recursi let installed = true; try { await fs.access(chromium.executablePath()); } catch { installed = false; } const browser = await chromium.launch({ headless: true, ...(installed ? { executablePath: chromium.executablePath() } : { channel: 'chrome' }) }); const errors = [], checks = []; let page; -async function fresh(width) { const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce', acceptDownloads: true }); const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await p.waitForFunction(() => { const s = JSON.parse(window.render_game_to_text?.() || '{}'); return !s.running && s.result?.status === 'completed' && !s.result.stale; }); const pause = p.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); return { context, page: p }; } +async function fresh(width) { const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce', acceptDownloads: true }); const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await dismissLearningWelcome(p); await p.waitForFunction(() => { const s = JSON.parse(window.render_game_to_text?.() || '{}'); return !s.running && s.result?.status === 'completed' && !s.result.stale; }); const pause = p.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); return { context, page: p }; } async function download(p, name) { const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, name); await file.saveAs(target); return JSON.parse(await fs.readFile(target, 'utf8')); } try { const mobile = await fresh(390); page = mobile.page; diff --git a/scripts/facility-smoke.mjs b/scripts/facility-smoke.mjs index f010b59..a833ff2 100644 --- a/scripts/facility-smoke.mjs +++ b/scripts/facility-smoke.mjs @@ -3,7 +3,7 @@ import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; -import { headerProjectInput, openPanel, runPlan, canvasDropPoint } from './ui-actions.mjs'; +import { dismissLearningWelcome, headerProjectInput, openPanel, runPlan, canvasDropPoint } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['127.0.0.1', 'localhost'].includes(origin.hostname), 'Use a separate loopback QA origin.'); @@ -18,7 +18,7 @@ const ready = page => page.waitForFunction(() => { const s = JSON.parse(window.r async function fresh(width = 1440) { const context = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: 'reduce', acceptDownloads: true }); const page = await context.newPage(); page.on('pageerror', error => errors.push(String(error))); - await page.goto(origin.href); await ready(page); + await page.goto(origin.href); await dismissLearningWelcome(page); await ready(page); // Use the original numerical fixture for these compatibility checks. await page.locator('.studio-world-picker select').selectOption('factory'); await ready(page); const pause = page.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); diff --git a/scripts/facility-workspace-smoke.mjs b/scripts/facility-workspace-smoke.mjs index 243c214..5a8fbc1 100644 --- a/scripts/facility-workspace-smoke.mjs +++ b/scripts/facility-workspace-smoke.mjs @@ -2,7 +2,7 @@ import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; -import { headerProjectInput, runPlan, canvasDropPoint } from './ui-actions.mjs'; +import { dismissLearningWelcome, headerProjectInput, runPlan, canvasDropPoint } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['localhost', '127.0.0.1'].includes(origin.hostname), 'Use an isolated QA origin.'); const out = path.resolve(process.env.QUEUELAB_EVIDENCE_DIR || '.private/evidence/facility-redesign/workspace'); @@ -13,7 +13,7 @@ const checks = [], errors = []; const state = p => p.evaluate(() => JSON.parse(window.render_game_to_text())); const ready = p => p.waitForFunction(() => { const s = JSON.parse(window.render_game_to_text?.() || '{}'); return !document.querySelector('.studio-world-picker select')?.disabled && !s.running && s.result?.status === 'completed' && !s.result.stale; }); async function artwork(p) { await p.waitForFunction(() => { const e = document.querySelector('.world-scene'), s = JSON.parse(e?.getAttribute('data-facility') || '{}'); return e?.getAttribute('data-status') === 'ready' && s.pending === 0 && s.failed === 0; }); } -async function fresh(width) { const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce', acceptDownloads: true }); const page = await context.newPage(); page.on('pageerror', e => errors.push(String(e))); await page.goto(origin.href); await ready(page); await artwork(page); const pause = page.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); return { context, page }; } +async function fresh(width) { const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce', acceptDownloads: true }); const page = await context.newPage(); page.on('pageerror', e => errors.push(String(e))); await page.goto(origin.href); await dismissLearningWelcome(page); await ready(page); await artwork(page); const pause = page.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); return { context, page }; } async function download(p, name) { const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, name); await file.saveAs(target); return JSON.parse(await fs.readFile(target, 'utf8')); } async function findModel(p) { const tray = p.locator('.facility-library'); if (!await tray.isVisible()) await p.locator('[data-build-opener]').click(); await tray.locator('.library-tabs').getByRole('button', { name: '3D models', exact: true }).click(); await tray.getByRole('searchbox', { name: 'Search equipment and objects', exact: true }).fill('Dispensing system'); const tile = tray.getByRole('button', { name: 'Dispensing system · C01', exact: true }); await tile.click(); return { tray, tile }; } let page; diff --git a/scripts/interface-polish-smoke.mjs b/scripts/interface-polish-smoke.mjs index 3b1e886..242c337 100644 --- a/scripts/interface-polish-smoke.mjs +++ b/scripts/interface-polish-smoke.mjs @@ -2,7 +2,7 @@ import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; -import { openPanel, runPlan } from './ui-actions.mjs'; +import { dismissLearningWelcome, openPanel, runPlan } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['127.0.0.1','localhost'].includes(origin.hostname), 'Use an isolated QA origin.'); const out = path.resolve(process.env.QUEUELAB_EVIDENCE_DIR || '.private/evidence/interface-polish/checks'); @@ -12,7 +12,7 @@ const browser=await chromium.launch({headless:true,...(installed?{executablePath const errors=[],checks=[];let page,stage='start'; const state=p=>p.evaluate(()=>JSON.parse(window.render_game_to_text())); async function ready(p){await p.waitForFunction(()=>{const s=JSON.parse(window.render_game_to_text?.()||'{}');return !document.querySelector('.studio-world-picker select')?.disabled && !s.running&&s.result?.status==='completed'&&!s.result.stale})} -async function fresh(width=1440,height=960){const context=await browser.newContext({viewport:{width,height},reducedMotion:'reduce',acceptDownloads:true});const p=await context.newPage();p.on('pageerror',e=>errors.push(String(e)));await p.goto(origin.href);await ready(p);const pause=p.getByRole('button',{name:'Pause replay',exact:true});if(await pause.count())await pause.click();return{context,page:p}} +async function fresh(width=1440,height=960){const context=await browser.newContext({viewport:{width,height},reducedMotion:'reduce',acceptDownloads:true});const p=await context.newPage();p.on('pageerror',e=>errors.push(String(e)));await p.goto(origin.href); await dismissLearningWelcome(p);await ready(p);const pause=p.getByRole('button',{name:'Pause replay',exact:true});if(await pause.count())await pause.click();return{context,page:p}} async function download(p,name){const next=p.waitForEvent('download');await p.locator('.studio-save').click();const file=await next,target=path.join(out,name);await file.saveAs(target);return JSON.parse(await fs.readFile(target,'utf8'))} async function screenshot(name){await page.screenshot({path:path.join(out,name+'.png')})} async function overflow(p){assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));const dialog=p.getByRole('dialog');if(await dialog.count())assert(await dialog.evaluate(e=>e.getBoundingClientRect().right<=innerWidth+1&&e.getBoundingClientRect().left>=-1));} diff --git a/scripts/learning-smoke.mjs b/scripts/learning-smoke.mjs new file mode 100644 index 0000000..4ae30a9 --- /dev/null +++ b/scripts/learning-smoke.mjs @@ -0,0 +1,159 @@ +// Synthetic browser checks; never use an owner's browser profile or projects. +import { chromium } from 'playwright'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import { dismissLearningWelcome, openPanel, runPlan } from './ui-actions.mjs'; +const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); +assert(['127.0.0.1', 'localhost'].includes(origin.hostname), 'Use a separate loopback QA origin.'); +const out = path.resolve(process.env.QUEUELAB_EVIDENCE_DIR || '.private/evidence/learning'); +await fs.mkdir(out, { recursive: true }); await fs.mkdir('.cache/tmp', { recursive: true }); process.env.TMPDIR = path.resolve('.cache/tmp'); +let installed = true; try { await fs.access(chromium.executablePath()); } catch { installed = false; } +const browser = await chromium.launch({ headless: true, ...(process.env.QUEUELAB_SYSTEM_CHROME || !installed ? { channel: 'chrome' } : { executablePath: chromium.executablePath() }) }); +const scope = process.env.QUEUELAB_LEARNING_SCOPE || 'all'; +assert(['all', 'flows', 'edges'].includes(scope)); +const checks = [], errors = []; let page, phase = 'first visit'; +const state = p => p.evaluate(() => JSON.parse(window.render_game_to_text())); +const ready = p => p.waitForFunction(() => { const s = JSON.parse(window.render_game_to_text?.() || '{}'); return !s.running && s.result?.status === 'completed'; }); +const coach = p => p.locator('.learning-coach'); +const stage = (p, name) => p.locator(`[data-learning-stage="${name}"]`).waitFor(); +const cap = p => p.locator('[data-learning-target="capacity-specialists"] input'); +const saved = p => p.locator('.workspace-footer').getByText(/^Saved in this browser/).first().waitFor(); +async function fresh(width = 1440, skip = false) { + const context = await browser.newContext({ viewport: { width, height: width > 740 ? 1000 : 844 }, reducedMotion: 'reduce', acceptDownloads: true }); + const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await ready(p); + if (skip) await dismissLearningWelcome(p); return { context, page: p }; +} +async function start(p) { + if (!await p.locator('[data-panel=learn]').count()) await p.getByRole('button', { name: 'Learn by doing', exact: true }).click(); + await p.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); await stage(p, 'select'); +} +async function change(p) { + await coach(p).getByRole('button', { name: 'Open the Steps list', exact: true }).click(); + await p.locator('[data-learning-target="step-station-b"]').press('Enter'); await stage(p, 'edit'); + await p.getByRole('button', { name: 'Show the team setting', exact: true }).click(); + await cap(p).fill('3'); await cap(p).press('Enter'); await stage(p, 'run'); +} +async function compare(p) { + await coach(p).getByRole('button', { name: 'Run & compare', exact: true }).press('Enter'); + await p.locator('[data-panel=compare] [data-learning-stage=review]').waitFor(); +} +async function keep(p) { await p.getByRole('button', { name: 'Keep this version', exact: true }).click(); await stage(p, 'save'); } +async function download(p, name) { + const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, `${name}.json`); await file.saveAs(target); return JSON.parse(await fs.readFile(target, 'utf8')); +} +async function overflow(p) { + assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); + const body = p.locator('.modal-body'); if (await body.count()) assert(await body.evaluate(el => el.scrollWidth <= el.clientWidth + 1)); +} +try { + for (const width of scope === 'edges' ? [] : [1440, 390, 320]) { + phase = `full exercise ${width}`; const c = await fresh(width); page = c.page; + await page.locator('[data-panel=learn]').waitFor(); await page.locator('.learning-intro img').evaluate(img => img.decode()); await overflow(page); + // Native modal keyboard containment before starting the lesson. + for (let i = 0; i < 7; i++) { await page.keyboard.press('Tab'); assert(await page.evaluate(() => Boolean(document.activeElement?.closest('[role=dialog]')))); } + await page.screenshot({ path: path.join(out, `welcome-${width}.png`) }); await start(page); + const initial = await download(page, `practice-${width}`); assert.equal(initial.world, 'service'); assert.equal(initial.name, 'My first experiment'); + assert.deepEqual(initial.model, JSON.parse(await fs.readFile('public/templates/service.json', 'utf8')).model); + await page.getByRole('button', { name: 'Minimize guide', exact: true }).click(); + assert(await page.locator('[data-learning-resume]').evaluate(el => el === document.activeElement)); + await page.locator('[data-learning-resume]').press('Enter'); await stage(page, 'select'); + await coach(page).getByRole('button', { name: 'Open the Steps list', exact: true }).click(); + await page.locator('[data-learning-target="step-station-b"]').press('Enter'); await stage(page, 'edit'); + await page.getByRole('button', { name: 'Show the team setting', exact: true }).click(); + assert.match(await cap(page).getAttribute('aria-describedby'), /-help learning-instruction$/); + assert(await page.locator('.learning-field-hint').isVisible()); await overflow(page); + await page.screenshot({ path: path.join(out, `edit-${width}.png`) }); + await cap(page).fill('invalid'); assert.equal(await coach(page).getAttribute('data-learning-stage'), 'edit'); + assert(await page.locator('[data-learning-target=run]').isDisabled()); await cap(page).press('Escape'); + await cap(page).fill('3'); await cap(page).press('Enter'); await stage(page, 'run'); + const changed = await download(page, `changed-${width}`); + const expected = structuredClone(initial.model); expected.resources.find(pool => pool.id === 'specialists').capacity = 3; + assert.deepEqual(changed.model, expected); assert.equal(changed.id, initial.id); + await compare(page); assert.equal((await state(page)).result.stale, false); await overflow(page); + await page.screenshot({ path: path.join(out, `review-${width}.png`) }); await keep(page); + await page.locator('.template-save input').fill('My trained team'); await page.locator('.template-save button[type=submit]').press('Enter'); await stage(page, 'complete'); + assert.match(await page.locator('.learning-saved').innerText(), /Template saved: My trained team/); + await page.locator('[data-template-id]').first().waitFor(); assert.equal(await page.locator('[data-template-id]').count(), 1); await overflow(page); + await coach(page).scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(out, `complete-${width}.png`) }); + assert.equal(await coach(page).evaluate(el => getComputedStyle(el).animationName), 'none'); + await page.getByRole('button', { name: 'Explore this project', exact: true }).click(); await saved(page); + await page.reload(); await ready(page); assert.equal(await page.locator('[data-panel=learn],.learning-coach').count(), 0); + assert.deepEqual((await download(page, `reopened-${width}`)).model, changed.model); + await openPanel(page, 'worlds'); await page.getByRole('button', { name: /^My templates/ }).click(); await page.locator('[data-template-id]').first().waitFor(); assert.equal(await page.locator('[data-template-id]').count(), 1); + await c.context.close(); checks.push(`${width}px: five real steps, pending-field guard, keyboard/focus, native persisted template, reload and reduced motion`); + } + if (scope !== 'flows') { + phase = 'resume and optional completion'; { + const c = await fresh(); page = c.page; await start(page); await change(page); await saved(page); const before = await download(page, 'before-refresh'); + await page.reload(); await stage(page, 'run'); assert.deepEqual((await download(page, 'after-refresh')).model, before.model); + assert.equal((await state(page)).result.stale, true); await compare(page); await keep(page); + await page.getByRole('button', { name: 'Finish without saving a template', exact: true }).click(); await stage(page, 'complete'); + assert.match(await page.locator('.learning-saved').innerText(), /No template was saved/); await c.context.close(); + checks.push('Refresh resumes the preserved changed model and requires a real rerun; optional finish makes no saved-template claim'); + } + phase = 'original project and history'; { + const c = await fresh(1440, true); page = c.page; + await page.locator('.studio-world-picker select').selectOption('service'); await ready(page); + await page.locator('.facility-canvas-tools').getByRole('button', { name: 'Steps', exact: true }).click(); + await page.getByRole('button', { name: 'Inspect Specialists', exact: true }).click(); + await cap(page).fill('4'); await cap(page).press('Enter'); await runPlan(page); await saved(page); + const before = await download(page, 'original-custom'), beforeState = await state(page); + const undoLabel = await page.getByRole('button', { name: /^Undo / }).getAttribute('aria-label'); + await page.evaluate(() => { const transaction = IDBDatabase.prototype.transaction; window.restoreProjectWrites = () => { IDBDatabase.prototype.transaction = transaction; }; IDBDatabase.prototype.transaction = function (...args) { if (this.name === 'queuelab-projects' && args[1] === 'readwrite') throw new DOMException('Synthetic storage failure', 'QuotaExceededError'); return transaction.apply(this, args); }; }); + await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); + await page.locator('.learning-intro [role=alert]').filter({ hasText: 'Your current work could not be saved' }).waitFor(); + assert.equal(await coach(page).count(), 0); assert.deepEqual((await state(page)).model, beforeState.model); + await page.evaluate(() => window.restoreProjectWrites()); + await start(page); await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await ready(page); + const returned = await download(page, 'returned-custom'); assert.equal(returned.id, before.id); assert.deepEqual(returned.model, before.model); + assert.deepEqual((await state(page)).result, beforeState.result); assert.equal(await page.getByRole('button', { name: /^Undo / }).getAttribute('aria-label'), undoLabel); + await page.getByRole('button', { name: /^Undo / }).click(); assert.equal((await download(page, 'original-undone')).model.resources.find(pool => pool.id === 'specialists').capacity, 2); + await saved(page); await start(page); + // Simulate a newer valid save from another tab while practice is open. + await page.evaluate(id => new Promise((resolve, reject) => { const r = indexedDB.open('queuelab-projects', 2); r.onerror = () => reject(r.error); r.onsuccess = () => { const db = r.result, tx = db.transaction('projects', 'readwrite'), get = tx.objectStore('projects').get(id); get.onsuccess = () => { const record = get.result, p = JSON.parse(record.payload); p.name = 'Newer synthetic project'; p.revision++; tx.objectStore('projects').put({ ...record, revision: p.revision, payload: JSON.stringify(p) }); }; tx.oncomplete = () => { db.close(); resolve(); }; tx.onabort = () => { db.close(); reject(tx.error); }; }; }), before.id); + await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await ready(page); + assert.equal((await download(page, 'newer-return')).name, 'Newer synthetic project'); + assert.equal(await page.getByRole('button', { name: /^Undo / }).count(), 0); + await c.context.close(); checks.push('A failed preservation write blocks practice; original project, result and Undo survive practice; a newer externally saved original is reopened without stale history'); + } + phase = 'save failure'; { + const c = await fresh(); page = c.page; await start(page); await change(page); await compare(page); await keep(page); + await page.locator('.template-save button[type=submit]').waitFor(); + await page.evaluate(() => { const transaction = IDBDatabase.prototype.transaction; window.restoreTemplateWrites = () => { IDBDatabase.prototype.transaction = transaction; }; IDBDatabase.prototype.transaction = function (...args) { if (this.name === 'loopset-templates' && args[1] === 'readwrite') throw new DOMException('Synthetic quota', 'QuotaExceededError'); return transaction.apply(this, args); }; }); + await page.locator('.template-save button[type=submit]').click(); await page.locator('.templates-panel [role=alert]').waitFor(); + await stage(page, 'save'); assert.equal(await page.locator('.learning-saved').count(), 0); assert.equal(await page.locator('[data-template-id]').count(), 0); + await page.evaluate(() => window.restoreTemplateWrites()); await page.locator('.template-save button[type=submit]').click(); await stage(page, 'complete'); + await c.context.close(); checks.push('A failed IndexedDB template write cannot complete the lesson or claim a save; native retry succeeds'); + } + phase = 'cancelled and failed practice loading'; { + const c = await fresh(1440, true); page = c.page; const before = await download(page, 'before-load-failure'); + await page.route('**/templates/service.json?*', route => route.fulfill({ status: 503, body: 'Unavailable' })); + await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); + await page.locator('.learning-intro [role=alert]').waitFor(); await page.unroute('**/templates/service.json?*'); + let release, seen; const gate = new Promise(resolve => { release = resolve; }), requested = new Promise(resolve => { seen = resolve; }); + await page.route('**/templates/service.json?*', async route => { seen(); await gate; await route.fulfill({ contentType: 'application/json', body: await fs.readFile('public/templates/service.json', 'utf8') }).catch(() => {}); }); + await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); await requested; + await page.keyboard.press('Escape'); await page.getByRole('dialog').waitFor({ state: 'detached' }); release(); + await page.locator('.studio-world-picker select').selectOption('blank'); await page.waitForFunction(() => JSON.parse(window.render_game_to_text()).workspaceMode === 'layout'); + const blank = await download(page, 'after-cancelled-load'); assert.deepEqual(blank.model.nodes, []); assert.notEqual(blank.id, before.id); + assert.equal(await coach(page).count(), 0); await page.unroute('**/templates/service.json?*'); await c.context.close(); + checks.push('HTTP errors stay actionable; Escape cancels practice loading and a late response cannot replace the newer blank project'); + } + phase = 'independent exploration'; { + const c = await fresh(); page = c.page; await start(page); await change(page); + await page.getByRole('button', { name: /^Undo / }).click(); await stage(page, 'edit'); + const stations = page.getByRole('spinbutton', { name: 'Parallel stations', exact: true }); await stations.fill('4'); await stations.press('Enter'); await stage(page, 'off-track'); + const different = await download(page, 'independent-idea'); + await page.getByRole('button', { name: 'Leave guide', exact: true }).click(); + assert.deepEqual((await download(page, 'after-leave')).model, different.model); + await saved(page); await page.reload(); await ready(page); assert.equal(await page.locator('[data-panel=learn],.learning-coach').count(), 0); + await c.context.close(); checks.push('Undo returns to the relevant task; unrelated model edits are preserved and leaving the guide never resets them'); + } + } + assert.deepEqual(errors, []); const receipt = { passed: true, at: new Date().toISOString(), origin: origin.href, browser: browser.version(), scope, checks, errors }; + await fs.writeFile(path.join(out, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n'); console.log(JSON.stringify(receipt)); +} catch (error) { + if (page && !page.isClosed()) { await page.screenshot({ path: path.join(out, 'failure.png'), fullPage: true }).catch(() => {}); await fs.writeFile(path.join(out, 'failure.txt'), `${phase}\n${error}\n${await page.locator('body').innerText()}`); } + console.error(phase, error); process.exitCode = 1; +} finally { await browser.close(); } diff --git a/scripts/starter-collection-smoke.mjs b/scripts/starter-collection-smoke.mjs index f752632..bcf0144 100644 --- a/scripts/starter-collection-smoke.mjs +++ b/scripts/starter-collection-smoke.mjs @@ -3,7 +3,7 @@ import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; -import { openPanel, runPlan } from './ui-actions.mjs'; +import { dismissLearningWelcome, openPanel, runPlan } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['127.0.0.1', 'localhost'].includes(origin.hostname), 'Use a separate loopback QA origin.'); const out = path.resolve(process.env.QUEUELAB_EVIDENCE_DIR || '.private/evidence/template-collection/smoke'); @@ -18,7 +18,7 @@ const ready = p => p.waitForFunction(() => { const s = JSON.parse(window.render_ const artwork = p => p.waitForFunction(() => { const h = document.querySelector('.world-scene'), f = JSON.parse(h?.getAttribute('data-facility') || '{}'); return h?.getAttribute('data-status') === 'ready' && f.pending === 0 && f.failed === 0; }); async function fresh(width = 1440) { const context = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: 'reduce', acceptDownloads: true }); - const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await ready(p); return { context, page: p }; + const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await dismissLearningWelcome(p); await ready(p); return { context, page: p }; } async function download(p, name) { const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, `${name}.json`); await file.saveAs(target); return JSON.parse(await fs.readFile(target, 'utf8')); diff --git a/scripts/templates-smoke.mjs b/scripts/templates-smoke.mjs index eb53de1..b6b4159 100644 --- a/scripts/templates-smoke.mjs +++ b/scripts/templates-smoke.mjs @@ -3,7 +3,7 @@ import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; import assert from 'node:assert/strict'; -import { openPanel, runPlan, headerProjectInput, canvasDropPoint } from './ui-actions.mjs'; +import { dismissLearningWelcome, openPanel, runPlan, headerProjectInput, canvasDropPoint } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['127.0.0.1', 'localhost'].includes(origin.hostname), 'Use a separate loopback QA origin.'); @@ -19,7 +19,7 @@ const close = p => p.getByRole('button', { name: 'Close dialog', exact: true }). async function fresh(width = 1440) { const context = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: 'reduce', acceptDownloads: true }); const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); - await p.goto(origin.href); await ready(p); return { context, page: p }; + await p.goto(origin.href); await dismissLearningWelcome(p); await ready(p); return { context, page: p }; } async function download(p, name) { const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); @@ -122,7 +122,7 @@ try { tx.oncomplete = () => { db.close(); resolve(); }; tx.onabort = () => { db.close(); reject(String(tx.error)); }; }; }), saved.templates[0]); - const other = await desktop.context.newPage(); other.on('pageerror', e => errors.push(String(e))); await other.goto(origin.href); await ready(other); + const other = await desktop.context.newPage(); other.on('pageerror', e => errors.push(String(e))); await other.goto(origin.href); await dismissLearningWelcome(other); await ready(other); await myTemplates(page); await page.locator('.templates-panel').getByRole('button', { name: 'Save as template', exact: true }).click(); await myTemplates(other); await other.locator('.templates-panel').getByRole('button', { name: 'Save as template', exact: true }).click(); for (const [p, name] of [[page, 'Concurrent A'], [other, 'Concurrent B']]) { await p.bringToFront(); await p.getByRole('textbox', { name: 'Template name', exact: true }).fill(name); } // Activate the two real form handlers together; background-tab frame throttling must not serialize this transaction race. diff --git a/scripts/templates-storage-smoke.mjs b/scripts/templates-storage-smoke.mjs index cee38c7..cacf971 100644 --- a/scripts/templates-storage-smoke.mjs +++ b/scripts/templates-storage-smoke.mjs @@ -1,3 +1,4 @@ +import { dismissLearningWelcome } from './ui-actions.mjs'; import { chromium } from 'playwright'; import fs from 'node:fs/promises'; import path from 'node:path'; @@ -17,7 +18,7 @@ try { for (const node of project.model.nodes) if (node.kind === 'service') node.duration = { kind: 'empirical', values: Array(10000).fill(30.123456789) }; project.scenarios = Array.from({ length: 4 }, (_, i) => ({ id: `scenario-${i}`, name: `Synthetic ${i}`, createdAt: '2026-01-01T00:00:00.000Z', model: structuredClone(project.model), world: project.world, layout: project.layout })); const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }), page = await context.newPage(); - page.on('pageerror', error => errors.push(String(error))); await page.goto(origin.href); + page.on('pageerror', error => errors.push(String(error))); await page.goto(origin.href); await dismissLearningWelcome(page); await page.locator('.studio-world-picker select').selectOption('save'); await page.getByLabel('Choose template project JSON', { exact: true }).setInputFiles({ name: 'synthetic-measurements.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(project)) }); await page.getByRole('button', { name: 'Save imported template', exact: true }).click(); @@ -38,7 +39,7 @@ try { for (const mode of ['unavailable', 'newer']) { const isolated = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }), p = await isolated.newPage(); p.on('pageerror', e => errors.push(String(e))); - await p.goto(origin.href); + await p.goto(origin.href); await dismissLearningWelcome(p); if (mode === 'unavailable') await p.evaluate(() => { const open = indexedDB.open.bind(indexedDB); indexedDB.open = function (name, version) { if (name === 'loopset-templates') throw new DOMException('Synthetic unavailable storage', 'SecurityError'); return open(name, version); }; }); else await p.evaluate(() => new Promise(resolve => { const request = indexedDB.open('loopset-templates', 2); request.onupgradeneeded = () => request.result.createObjectStore('future-data'); request.onsuccess = () => { request.result.close(); resolve(); }; })); await p.locator('.studio-world-picker select').selectOption('save'); diff --git a/scripts/ui-actions.mjs b/scripts/ui-actions.mjs index 836e1f4..7cdf9b3 100644 --- a/scripts/ui-actions.mjs +++ b/scripts/ui-actions.mjs @@ -9,6 +9,19 @@ const panelNames = { insights: 'Run insights', compare: 'Compare plans', data: 'Files & reports', }; +/** Use the public skip path before testing unrelated workspace interactions. */ +export async function dismissLearningWelcome(page) { + await page.waitForFunction(() => { + const state = JSON.parse(window.render_game_to_text?.() || '{}'); + return !state.running && (state.workspaceMode === 'layout' || state.result?.status === 'completed'); + }); + const welcome = page.locator('[data-panel="learn"]'); + if (await welcome.count()) { + await welcome.getByRole('button', { name: 'Explore on my own', exact: true }).click(); + await welcome.waitFor({ state: 'detached' }); + } +} + export async function panelOpener(page, panel) { if (!Object.hasOwn(panelNames, panel)) throw new Error(`Unknown studio panel: ${panel}`); if (toolPanels.has(panel)) { diff --git a/scripts/ux-smoke.mjs b/scripts/ux-smoke.mjs index 86389de..7824bac 100644 --- a/scripts/ux-smoke.mjs +++ b/scripts/ux-smoke.mjs @@ -4,7 +4,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; import { createHash } from 'node:crypto'; -import { openPanel, primaryRunButton, headerProjectInput } from './ui-actions.mjs'; +import { dismissLearningWelcome, openPanel, primaryRunButton, headerProjectInput } from './ui-actions.mjs'; const origin = new URL(process.env.QUEUELAB_URL || 'http://127.0.0.1:4173/'); assert(['localhost', '127.0.0.1'].includes(origin.hostname), 'Use a loopback QA server.'); const kind = process.env.QUEUELAB_BROWSER || 'chromium', phase = process.env.QUEUELAB_UX_PHASE || 'core'; @@ -36,7 +36,7 @@ async function inspect(page, label, intent = 'single') { async function field(page, name, value, scope = page) { const input = scope.getByRole('spinbutton', { name, exact: true }); await input.fill(String(value)); await input.press('Enter'); return input; } async function fresh(world = 'factory', width = viewportWidth, height = viewportHeight) { const context = await browser.newContext({ viewport: { width, height }, reducedMotion: 'reduce', acceptDownloads: true }); const page = await context.newPage(); - page.on('pageerror', error => receipt.errors.push(String(error))); await page.goto(origin.href); await ready(page); + page.on('pageerror', error => receipt.errors.push(String(error))); await page.goto(origin.href); await dismissLearningWelcome(page); await ready(page); if (world !== 'factory') { await page.locator('.studio-world-picker select').selectOption(world); await ready(page); } const pause = page.getByRole('button', { name: 'Pause replay', exact: true }); if (await pause.count()) await pause.click(); return { context, page }; } @@ -196,6 +196,7 @@ async function qualityPhase() { try { const original = await projectJSON(page, 'quality-original.json'), initial = await state(page); const packing = original.model.nodes.find(node => node.id === 'station-c'); + await inspect(page, packing.label); const mean = (packing.duration.min + packing.duration.mode + packing.duration.max) / 3; const meanInput = page.getByRole('spinbutton', { name: 'Mean processing time', exact: true }); assert.equal(await meanInput.inputValue(), String(mean)); @@ -240,7 +241,8 @@ async function qualityPhase() { const team = page.locator('.ease-team').filter({ hasText: 'Packing team' }); assert(await team.getByRole('spinbutton', { name: 'Base available units', exact: true }).isVisible()); assert.equal((await state(page)).revision, navigationRevision); - await page.getByRole('button', { name: 'How it works', exact: true }).click(); + await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); + await page.getByRole('button', { name: 'Just show me the controls', exact: true }).click(); assert.equal(await page.locator('.quality-guide-progress li').count(), 3); await page.getByRole('button', { name: 'Next step', exact: true }).click(); await page.getByRole('heading', { name: 'Run the changed plan', exact: true }).waitFor(); diff --git a/src/App.tsx b/src/App.tsx index d63041f..c070843 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,7 @@ import { appMessages as m } from './ui/messages/App'; +import { learningMessages as lm } from './ui/messages/learning'; +import { LearningIntro, LearningCoach } from './features/LearningGuide'; +import { createLearningSession, learningReturnMatches, learningModelMatches, learningRunMatches, learningStage, originalLearningProject, readLearningSession, rememberLearningSession, hasSeenLearningWelcome, rememberLearningWelcome, LEARNING_STEP_ID, LEARNING_POOL_ID, type LearningSession, type LearningStage } from './features/learning'; import { assetURL } from './assetUrl'; import { lazy, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { ArrowDownToLine, ArrowRight, Box, Check, ChevronRight, CircleHelp, Copy, FileUp, FlaskConical, Focus, GitCompareArrows, Globe2, History, Layers3, Link2, List, LoaderCircle, MousePointer2, Move, Pause, Play, Plus, Redo2, Search, ShieldCheck, SkipBack, Undo2, X } from 'lucide-react'; @@ -70,7 +73,7 @@ import { buildCouplingManifest } from './engine/provenance'; import { ExperimentsPanel } from './lab/ExperimentsPanel'; import { SavedScenarios } from './lab/SavedScenarios'; import { RunInsights } from './lab/RunInsights'; -import { captureSaveContext, loadLastProject, rememberOpenedProject, saveProject } from './storage/projectStore'; +import { captureSaveContext, loadLastProject, loadProject, rememberOpenedProject, saveProject } from './storage/projectStore'; import { BoundedCache } from './storage/boundedCache'; import { ProjectSaveQueue, type SaveInput } from './storage/projectSaveQueue'; import { openProjectJSON, serializeProject } from './storage/projectFile'; @@ -86,7 +89,7 @@ const clock = (s: number) => !Number.isFinite(s) ? '—' : `${Math.floor(s / 60) const wait = (s: number) => !Number.isFinite(s) ? '—' : s >= 60 ? m.minutes((s / 60).toFixed(1)) : m.seconds(Math.round(s)); const money = (n: number, currency: string) => new Intl.NumberFormat('en', { style: 'currency', currency, maximumFractionDigits: 0 }).format(n); const number = (n: number) => new Intl.NumberFormat('en', { maximumFractionDigits: 0 }).format(n); -type Panel = 'worlds' | 'model' | 'compare' | 'data' | 'experiments' | 'insights' | 'budget' | 'history' | 'help' | 'scenario' | 'view' | 'rename' | 'search' | 'guide' | 'brief' | null; +type Panel = 'worlds' | 'model' | 'compare' | 'data' | 'experiments' | 'insights' | 'budget' | 'history' | 'help' | 'scenario' | 'view' | 'rename' | 'search' | 'guide' | 'brief' | 'learn' | null; function focusChangedSince(origin: Element | null): boolean { const chosen = document.activeElement; @@ -97,6 +100,14 @@ export default function App() { const [pendingEdits, setPendingEdits] = useState(false); const [guideIndex, setGuideIndex] = useState(0); const [project, setProject] = useState(() => createWorkshopFacility()); + const initialProjectId = useRef(project.id), restoredExistingProject = useRef(false), earlyInteraction = useRef(false); + const [learning, setLearningState] = useState(null), learningRef = useRef(null); + const [learningMinimized, setLearningMinimized] = useState(false), [learningStarting, setLearningStarting] = useState(false), [learningError, setLearningError] = useState(null); + const learningRequest = useRef(0), learningAbort = useRef(null); + const focusedLearningStep = useRef(''); + const learningReturn = useRef<{ project: Project; result: RunResult | null; baseline: RunResult | null; attempt: RunResult | null; history: ReturnType; selection: EditorSelection; time: number; speed: number } | null>(null); + useEffect(() => () => { learningRequest.current++; learningAbort.current?.abort(); }, []); + const [history, setHistory] = useState(emptyHistory); const historyRef = useRef(history); historyRef.current = history; const [selection, setSelection] = useState({ ids: ['station-c'], primary: 'station-c' }); const selectionRef = useRef(selection); selectionRef.current = selection; @@ -172,6 +183,9 @@ export default function App() { live.current = { project, result, latestAttempt, time, playing, speed, selected, selectedIds: selection.ids, running: sim.running, canReplay, replayUntil }; const singleCoupling = useMemo(() => baseline && shownResult && baseline.provenance && shownResult.provenance ? buildCouplingManifest(baseline, shownResult) : null, [baseline, shownResult]); const singlePaired = Boolean(baseline && shownResult && singleCoupling?.compatibility.sameExternalDemand && singleCoupling.compatibility.sameMeasurementPolicies && baseline.demandHash === shownResult.demandHash); + const learningActive = Boolean(learning && learning.projectId === project.id); + const lessonStage: LearningStage | null = learningActive ? learningStage({ session: learning!, project, baseline, result: shownResult, pending: pendingEdits, running: sim.running, valid: !hasErrors, comparable: singlePaired }) : null; + const learningComparison = Boolean(learningActive && learningRunMatches(baseline, learning!.baseHash, learning!.seed) && learningRunMatches(shownResult, learning!.changedHash, learning!.seed) && singlePaired); const frame = useMemo(() => frameAt(visualProject, shownResult, time), [visualProject, shownResult, time]); const selectedStep = project.model.nodes.find(n => n.id === selected); const worldInfo = WORLD_INFO[project.world]; @@ -215,7 +229,18 @@ export default function App() { updateSelection(pruneSelection(selectStep(selectionRef.current, id, intent), live.current.project.model.nodes)); } + function updateLearning(next: LearningSession | null) { learningRef.current = next; setLearningState(next); rememberLearningSession(next); } + function patchLearning(patch: Partial) { if (learningRef.current) updateLearning({ ...learningRef.current, ...patch }); } + function leaveLearning() { + ++learningRequest.current; learningAbort.current?.abort(); learningAbort.current = null; + setLearningStarting(false); setLearningError(null); updateLearning(null); learningReturn.current = null; + rememberLearningWelcome(); + } function setPanel(next: Panel, opener?: HTMLElement | null, keepExperimentContext = false) { + if (currentPanel.current === 'learn' && next !== 'learn') { + rememberLearningWelcome(); ++learningRequest.current; learningAbort.current?.abort(); learningAbort.current = null; setLearningStarting(false); + } + if (next !== currentPanel.current && starterAbort.current) { starterRequest.current++; starterAbort.current.abort(); starterAbort.current = null; setStarterLoading(false); } if (next === 'experiments' && !keepExperimentContext) setExperimentContext(null); if (next === currentPanel.current) return; @@ -242,12 +267,13 @@ export default function App() { if (generation !== requestGeneration.current) return; if (r.status !== 'completed') { calculationStatus.controller.finish(announcementId, '', panelGeneration.current); setLatestAttempt(r); setToast(r.reason ?? m.incompleteRunNotice(r.status)); return; } setLatestAttempt(null); - runDisplayNames.current.set(r, p.name); + const lesson = learningRef.current; + runDisplayNames.current.set(r, lesson?.projectId === p.id ? r.modelHash === lesson.baseHash ? lm.originalPlan : lm.changedPlan : p.name); runPresentations.current.set(r, capturePresentation(p)); setResult(r); if (establishBaseline || !baseline) setBaseline(r); const coverage = replayManifest(r).coverage; setTime(establishBaseline ? Math.min(p.model.horizon * .38, coverage.at(-1)?.end ?? 0) : 0); - setPlaying(establishBaseline && coverage.length > 0); manualClock.current = false; + setPlaying(establishBaseline && coverage.length > 0 && !currentPanel.current && learningRef.current?.projectId !== p.id); manualClock.current = false; const current = live.current.project; const earlier = !sameNumericalSnapshot( { projectId: p.id, modelHash: r.modelHash, seed: r.seed, valid: true }, @@ -262,12 +288,15 @@ export default function App() { const surface = panelGeneration.current; const completed = await compute(snapshot); const current = live.current.project; - if (!completed || surface !== panelGeneration.current || current.id !== snapshot.id || + if (!completed || pendingEditsRef.current || surface !== panelGeneration.current || current.id !== snapshot.id || !sameNumericalSnapshot( { projectId: snapshot.id, modelHash: completed.modelHash, seed: completed.seed, valid: true }, { projectId: current.id, modelHash: modelHash(current.model), seed: current.model.seed, valid: !validateProject(current).some(issue => issue.severity === 'error') }, )) return; + const lesson = learningRef.current; + if (lesson?.projectId === current.id && learningModelMatches(current, lesson) && learningRunMatches(completed, lesson.changedHash, lesson.seed) && learningRunMatches(baseline, lesson.baseHash, lesson.seed)) patchLearning({ ran: true, reviewed: false }); setPanel('compare', opener); + return completed; } function cancelCalculation() { calculationStatus.controller.stopping(String(requestGeneration.current), m.stoppingCalculation, panelGeneration.current); @@ -284,8 +313,19 @@ export default function App() { const initial = untouched ? saved ?? project : live.current.project; if (saved) acknowledgedContent.current.set(saved.id, recoveryProjectKey(saved)); if (saved && untouched) { rememberOpenedProject(saved); setProject(saved); live.current = { ...live.current, project: saved }; setLocalRevision(saved.revision); setSelected(serviceNodes(saved)[0]?.id ?? null); } + restoredExistingProject.current = Boolean(saved); storageGate.current!.resolve(); setStorageReady(true); - if (!isLayoutOnly(initial) && !validateProject(initial).some(issue => issue.severity === 'error')) void compute(initial, true); + const resume = readLearningSession(); + if (resume && initial.id === resume.projectId) { + updateLearning(resume); setLibraryTab('steps'); setBuildTrayOpen(false); setSelected(resume.selected ? LEARNING_STEP_ID : null); + const original = originalLearningProject(initial, resume); + if (original) { original.name = lm.originalPlan; void compute(original, true); } + else if (!isLayoutOnly(initial) && !validateProject(initial).some(issue => issue.severity === 'error')) void compute(initial, true); + } else { + rememberLearningSession(null); + if (!isLayoutOnly(initial) && !validateProject(initial).some(issue => issue.severity === 'error')) void compute(initial, true); + if (!saved && untouched && !earlyInteraction.current && !currentPanel.current && !hasSeenLearningWelcome()) setPanel('learn'); + } }).catch(error => { if (!alive) return; setStorageError(error instanceof Error ? error.message : m.browserStorageIsUnavailableKeepADownloadedBackup); @@ -418,7 +458,43 @@ export default function App() { useEffect(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 6000); return () => clearTimeout(id); }, [toast]); // Adopt a document's inspector before it can receive input. A deferred reset // can otherwise overwrite a Tools choice made just after the new world appears. - useLayoutEffect(() => { setObjectDetailsOpen(!project.facility && !matchMedia('(max-width:740px)').matches); setInspectorTab('object'); }, [project.id]); + useLayoutEffect(() => { + const lesson = learningRef.current?.projectId === project.id ? learningRef.current : null; + setObjectDetailsOpen(Boolean(lesson) || (!project.facility && !matchMedia('(max-width:740px)').matches)); + setInspectorTab(lesson && !lesson.selected ? 'steps' : 'object'); + }, [project.id]); + useEffect(() => { + if (learningRef.current?.projectId === project.id && selected === LEARNING_STEP_ID && !learningRef.current.selected) patchLearning({ selected: true }); + }, [project.id, selected, learning?.selected]); + useEffect(() => { + if (!learningActive || !lessonStage || learningMinimized || (panel && panel !== 'compare' && panel !== 'worlds')) return; + const selector = learningSelector(lessonStage); + let target = selector ? document.querySelector(selector) : null; + if (!target?.checkVisibility({ visibilityProperty: true }) || target.closest('[inert]')) target = document.querySelector('.learning-coach [data-learning-action]'); + if (!target) return; + target.classList.add('learning-target'); + const description = new Set((target.getAttribute('aria-describedby') ?? '').split(' ').filter(Boolean)); + description.add('learning-instruction'); target.setAttribute('aria-describedby', [...description].join(' ')); + let handle = 0; + const key = `${project.id}:${lessonStage}`; + const active = document.activeElement; + const fromGuide = active === document.body || (active instanceof HTMLElement && Boolean(active.closest('.learning-coach,.learning-intro,[data-learning-target],[inert]') || active.matches('[data-panel-opener="learn"]'))); + const focus = lessonStage === 'review' ? document.querySelector('.learning-coach [data-learning-action]') : target; + if (fromGuide && focus?.matches('input,button,select') && !focus.matches(':disabled') && !['preparing', 'complete', 'off-track'].includes(lessonStage) && focusedLearningStep.current !== key) { + focusedLearningStep.current = key; + const origin = document.activeElement, surface = panelGeneration.current; + handle = requestAnimationFrame(() => { + if (learningRef.current?.projectId !== project.id || surface !== panelGeneration.current || focusChangedSince(origin) || !focus.isConnected || focus.closest('[inert],[hidden]')) return; + focus.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'auto' }); focus.focus({ preventScroll: true }); + }); + } + return () => { + cancelAnimationFrame(handle); target.classList.remove('learning-target'); + const remaining = (target.getAttribute('aria-describedby') ?? '').split(' ').filter(id => id && id !== 'learning-instruction'); + if (remaining.length) target.setAttribute('aria-describedby', remaining.join(' ')); else target.removeAttribute('aria-describedby'); + }; + }, [learningActive, lessonStage, learningMinimized, project.id, panel, inspectorTab, objectDetailsOpen, pendingEdits]); + function updateRetained(next: RetainedDraft[]) { retained.current = next; setRetainedDrafts(next); } @@ -688,14 +764,15 @@ export default function App() { setSelected(id, intent); if (id) { setInspectorTab('object'); setObjectDetailsOpen(true); } } - function acceptProject(next: Project, label: string = m.openProjectFile): Project | null { + function acceptProject(next: Project, label: string = m.openProjectFile, calculate = true, keepLearning = false): Project | null { const previous = live.current.project; setLinkFrom(null); if (next.id === previous.id) { ++requestGeneration.current; calculationStatus.controller.invalidate(panelGeneration.current); sim.cancel(); setLatestAttempt(null); if (!edit(next, label)) return null; return live.current.project; } if (!preserveOutgoing(previous)) return null; + if (!keepLearning && learningRef.current) leaveLearning(); ++requestGeneration.current; calculationStatus.controller.invalidate(panelGeneration.current); sim.cancel(); setLatestAttempt(null); setProject(next); live.current = { ...live.current, project: next }; const cleared = emptyHistory(); historyRef.current = cleared; setHistory(cleared); updateSelection(emptySelection()); setResult(null); setBaseline(null); setSelected(serviceNodes(next)[0]?.id ?? null); setBackupRequestedRevision(null); setLocalRevision(null); setStorageError(null); - if (!isLayoutOnly(next) && !validateProject(next).some(issue => issue.severity === 'error')) void compute(next, true); + if (calculate && !isLayoutOnly(next) && !validateProject(next).some(issue => issue.severity === 'error')) void compute(next, true); return next; } function openTemplates(intent: 'browse' | 'save' = 'browse', opener?: HTMLElement) { setTemplateIntent(intent); setPanel('worlds', opener); } @@ -719,6 +796,122 @@ export default function App() { } catch (error) { if (request === starterRequest.current && surface === panelGeneration.current) { if (currentPanel.current === 'worlds') throw error; setToast(error instanceof Error ? error.message : stm.failed); } } finally { clearTimeout(timeout); if (request === starterRequest.current) { starterAbort.current = null; setStarterLoading(false); } } } + async function startLearning() { + if (learningStarting) return; + if (!storageReady || pendingEditsRef.current || sim.running) { setLearningError(pendingEditsRef.current ? lm.pending : sim.running ? lm.waiting : lm.storageWaiting); return; } + const token = ++learningRequest.current, origin = live.current.project, surface = panelGeneration.current; + const previousLesson = learningRef.current; + const continuing = previousLesson?.projectId === origin.id && !previousLesson.finished; + const pristine = !restoredExistingProject.current && origin.id === initialProjectId.current && origin.revision === 0; + const returnId = continuing ? previousLesson!.returnProjectId : pristine ? null : origin.id; + const original = continuing ? learningReturn.current : { project: origin, result, baseline, attempt: latestAttempt, history: historyRef.current, selection: selectionRef.current, time, speed }; + const controller = new AbortController(); learningAbort.current?.abort(); learningAbort.current = controller; + const current = () => token === learningRequest.current && surface === panelGeneration.current && live.current.project.id === origin.id && live.current.project.revision === origin.revision && !pendingEditsRef.current; + const timeout = setTimeout(() => controller.abort(), 20_000); + setLearningStarting(true); setLearningError(null); + try { + try { await persistProject(origin, false, captureSaveContext(origin.id)); } + catch { if (!pristine) throw new Error(lm.preservationFailed); } + if (!current()) return; + const next = await loadStarter('service', fetch, controller.signal); + if (!current()) return; + next.name = lm.practiceName; + const session = createLearningSession(next, returnId); + if (!session) throw new Error(lm.starterChanged); + if (!acceptProject(next, lm.practiceName, true, true)) return; + learningReturn.current = original; updateLearning(session); rememberLearningWelcome(); + setLearningMinimized(false); setSelected(null); setLibraryTab('steps'); setBuildTrayOpen(false); setPlaying(false); + setPanel(null); + } catch (error) { + if (current()) setLearningError(error instanceof Error ? error.message : lm.startFailed); + } finally { + clearTimeout(timeout); + if (token === learningRequest.current) { learningAbort.current = null; setLearningStarting(false); } + } + } + async function returnFromLearning() { + const session = learningRef.current; + if (!session?.returnProjectId || learningStarting) return; + if (pendingEditsRef.current) { setLearningError(lm.pending); return; } + const origin = live.current.project, surface = panelGeneration.current, token = ++learningRequest.current; + const snapshot = learningReturn.current; + setLearningStarting(true); setLearningError(null); + try { + const saved = await loadProject(session.returnProjectId, { observe: false }); + if (token !== learningRequest.current || surface !== panelGeneration.current || origin.id !== live.current.project.id || origin.revision !== live.current.project.revision || pendingEditsRef.current) return; + if (!saved) throw new Error(lm.returnMissing); + const same = snapshot && learningReturnMatches(snapshot.project, saved); + const accepted = acceptProject(saved, lm.return, !same); + if (!accepted) return; + rememberOpenedProject(accepted); setLocalRevision(saved.revision); + if (same && snapshot) { + setResult(snapshot.result); setBaseline(snapshot.baseline); setLatestAttempt(snapshot.attempt); + historyRef.current = snapshot.history; setHistory(snapshot.history); updateSelection(snapshot.selection); + setTime(snapshot.time); setSpeed(snapshot.speed); setPlaying(false); + } + setPanel(null); setLibraryTab(isLayoutOnly(saved) ? 'objects' : 'steps'); setBuildTrayOpen(false); + } catch (error) { + if (token === learningRequest.current) setLearningError(error instanceof Error ? error.message : lm.returnFailed); + } finally { if (token === learningRequest.current) setLearningStarting(false); } + } + function learningSelector(stage: LearningStage): string | null { + if (stage === 'select') return `[data-learning-target="step-${LEARNING_STEP_ID}"]`; + if (stage === 'edit') return `[data-learning-target="capacity-${LEARNING_POOL_ID}"] input`; + if (stage === 'run') return currentPanel.current === 'compare' ? '.comparison-run' : '[data-learning-target="run"]'; + if (stage === 'review') return currentPanel.current === 'compare' ? '[data-learning-target="comparison-cost"]' : '[data-panel-opener="compare"]'; + if (stage === 'save') return currentPanel.current === 'worlds' ? '.template-save input' : '.studio-world-picker select'; + return null; + } + function focusLearningTarget(stage: LearningStage) { + const id = learningRef.current?.projectId, surface = panelGeneration.current; + requestAnimationFrame(() => { + if (!id || learningRef.current?.projectId !== id || live.current.project.id !== id || panelGeneration.current !== surface) return; + const selector = learningSelector(stage); const target = selector ? document.querySelector(selector) : null; + if (!target || target.closest('[hidden],[inert]')) return; + let ancestor = target.parentElement; + while (ancestor) { if (ancestor instanceof HTMLDetailsElement) ancestor.open = true; ancestor = ancestor.parentElement; } + target.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'auto' }); target.focus({ preventScroll: true }); + }); + } + async function learningAction() { + const session = learningRef.current; + if (!session || session.projectId !== live.current.project.id || !lessonStage) return; + setLearningError(null); setLearningMinimized(false); + if (lessonStage === 'complete') { leaveLearning(); setPanel(null); return; } + if (lessonStage === 'off-track') { await startLearning(); return; } + if (lessonStage === 'baseline') { + const original = originalLearningProject(live.current.project, session); + if (original) { original.name = lm.originalPlan; patchLearning({ ran: false, reviewed: false }); await compute(original, true); } + return; + } + if (lessonStage === 'select') { setPanel(null); setBuildTrayOpen(false); setLibraryTab('steps'); openStepList(); focusLearningTarget('select'); return; } + if (lessonStage === 'edit') { setPanel(null); setBuildTrayOpen(false); setLibraryTab('steps'); editSceneNode(LEARNING_STEP_ID); focusLearningTarget('edit'); return; } + if (lessonStage === 'run') { + if (!pendingEditsRef.current && !sim.running) { + const opener = document.activeElement instanceof HTMLElement ? document.activeElement : document.querySelector('[data-learning-target="run"]'); + if (opener) await runAndCompare(opener); + } + return; + } + if (lessonStage === 'review') { + if (currentPanel.current !== 'compare') { setPanel('compare'); return; } + if (!learningComparison || pendingEditsRef.current) return; + patchLearning({ reviewed: true }); openTemplates('save'); return; + } + if (lessonStage === 'save') { + if (currentPanel.current === 'worlds' && templateIntent === 'save') focusLearningTarget('save'); + else openTemplates('save'); + } + } + function onLearningTemplateSaved(snapshot: Project, template: { id: string; name: string }) { + const session = learningRef.current, current = live.current.project; + if (!session || !session.reviewed || !session.ran || snapshot.id !== session.projectId || current.id !== session.projectId || current.model.seed !== session.seed || snapshot.model.seed !== session.seed || modelHash(snapshot.model) !== session.changedHash || modelHash(current.model) !== session.changedHash || pendingEditsRef.current) return; + patchLearning({ finished: true, savedName: template.name }); rememberLearningWelcome(); setLearningMinimized(false); + } + function finishLearningWithoutSave() { + if (lessonStage !== 'save' || !learningComparison || pendingEditsRef.current) return; + patchLearning({ finished: true }); rememberLearningWelcome(); setPanel(null); setLearningMinimized(false); + } function applyBriefScenario(id: string) { facilityAction(() => { if (pendingEditsRef.current || sim.running) throw new Error(tm.pending); @@ -759,6 +952,7 @@ export default function App() { if (command === 'newModel') { createProcess(); return; } if (command === 'steps') { setPanel(null); openStepList(); return; } if (command === 'data') { openFiles('projects'); return; } + if (command === 'learn') { setLearningError(null); setPanel('learn'); return; } if (command === 'download') { downloadProject(); setPanel(null); return; } if (command === 'demand' || command === 'team') { const kind = command === 'demand' ? 'source' : 'service'; @@ -774,9 +968,10 @@ export default function App() { if (target === 'steps') { openStepList(); return; } requestAnimationFrame(() => document.querySelector(target === 'download' ? '.studio-save' : '.studio-command-actions .studio-primary')?.focus()); } - const panelTitle = (surface: Exclude) => ({ worlds: m.chooseYourLittleWorld, compare: m.aBetterPlanStartsHere, model: m.insideYourModel, data: m.keepYourWorkShareYourFindings, experiments: m.runExperiments, insights: m.yourRunInDetail, budget: m.beforeYouCalculate, history: m.yourRecentActions, help: m.helpHeading, scenario: sx.scenario, view: sx.view, rename: sx.renameProject, search: sx.search, guide: sx.guide, brief: stm.brief }[surface]); + const panelTitle = (surface: Exclude) => ({ worlds: m.chooseYourLittleWorld, compare: m.aBetterPlanStartsHere, model: m.insideYourModel, data: m.keepYourWorkShareYourFindings, experiments: m.runExperiments, insights: m.yourRunInDetail, budget: m.beforeYouCalculate, history: m.yourRecentActions, help: m.helpHeading, scenario: sx.scenario, view: sx.view, rename: sx.renameProject, search: sx.search, guide: sx.guide, brief: stm.brief, learn: lm.title }[surface]); + const learningCoach = learning && lessonStage ? void learningAction()} onMinimize={() => setLearningMinimized(value => !value)} onLeave={leaveLearning} onReturn={() => void returnFromLearning()} onFinishWithoutSave={finishLearningWithoutSave} /> : null; const draftSummary = layoutOnly ? tm.layoutMode : normalBudget ? sx.quickSummary(ease.duration(project.model.horizon), number(normalBudget.groups[0].arrivalsPerRun), normalBudget.groups[0].stochastic, project.model.resources.length) : sx.reviewInputs; - return
+ return
{ if (!storageReady) earlyInteraction.current = true; }} onKeyDownCapture={() => { if (!storageReady) earlyInteraction.current = true; }}>
{ event.preventDefault(); setPanel(null); }}>{m.queueLab}.

{sx.localProject}
@@ -786,10 +981,11 @@ export default function App() { - +
{ chooseLibraryTab(tab); showBuildTray(element); }} onResults={element => setPanel('insights', element)} onTools={openTools} onView={element => setPanel('view', element)} /> + {!panel && learningActive && learningCoach}
@@ -806,7 +1002,7 @@ export default function App() { {selection.ids.length > 1 &&
{m.selectionSummary(selection.ids.length, selectedStep?.label ?? m.step)}
} {linkFrom && selectedStep &&
node.id === linkFrom) ?? selectedStep} onChange={(next,label) => { edit(next,label); setLinkFrom(null); setConnectionPreview(null); }} onPreview={to => setConnectionPreview(previous => to ? { owner: 'tool', from: linkFrom, to } : previous?.owner === 'tool' ? null : previous)} />
}
-
{libraryTab === 'objects' ? fm.canvasTitle : fm.processTitle}

{project.name}

+
{libraryTab === 'objects' ? fm.canvasTitle : fm.processTitle}

{project.name}

@@ -846,14 +1042,16 @@ export default function App() { {objectDetailsOpen && }
{storageError && } {!panel && (toast || sim.error) &&
{toast ?? sim.error}
} {sim.running && } - {panel &&
setPanel(null)}>
e.stopPropagation()}>
{m.modalEyebrow(m.modalSection(panel))}
+ {panel &&
setPanel(null)}>
e.stopPropagation()}>
{m.modalEyebrow(m.modalSection(panel))}
+ {learningActive && (panel === 'compare' || panel === 'worlds') && learningCoach} + {panel === 'learn' && void startLearning()} onExplore={() => setPanel(null)} onReference={() => { setGuideIndex(0); setPanel('guide'); }} />} {sim.error &&

{sim.error}

} {panel === 'brief' && setPanel('compare')} />} {panel === 'scenario' && setPanel('budget')} onInspect={id => { setPanel(null); editSceneNode(id); }} />} @@ -863,7 +1061,7 @@ export default function App() { {panel === 'view' &&

{sx.viewScope}

{sx.shortcuts}

{sx.inputHelp}

} {panel === 'history' && } {panel === 'budget' && (layoutOnly ?

{tm.processRequired}

: normalBudget ? :

{m.repairYourModelToSeeTheWorkloadEstimateThe}

)} - {panel === 'worlds' && } + {panel === 'worlds' && } {panel === 'compare' && <>

{m.keepYourOriginalPlanChangeAStationRunIt}

{singlePaired && baseline && shownResult &&
{m.whatChanged} @@ -871,7 +1069,7 @@ export default function App() {

{shownResult.summary.waitSampleSize && baseline.summary.waitSampleSize ? m.waitingOutcome(shownResult.summary.meanWait - baseline.summary.meanWait, wait(Math.abs(shownResult.summary.meanWait - baseline.summary.meanWait))) : m.noComparableWaitSamples} {shownResult.model.currency === baseline.model.currency ? m.costOutcome(shownResult.summary.cost - baseline.summary.cost, money(Math.abs(shownResult.summary.cost - baseline.summary.cost), shownResult.model.currency)) : m.differentCostCurrencies}

{m.compareScope}
} - {stale && }
{m.fullRunHeading}{m.baseline}{baseline ? runDisplayNames.current.get(baseline) ?? baseline.model.name : '—'}{baseline && {ease.duration(baseline.model.horizon)} · {baseline.id.slice(0,8)}}{m.currentPlan}{shownResult ? runDisplayNames.current.get(shownResult) ?? shownResult.model.name : project.name}{ease.duration(shownResult?.model.horizon ?? project.model.horizon)}{shownResult ? ` · ${shownResult.id.slice(0,8)}` : ''}
{[[m.completed, baseline?.summary.completed, shownResult?.summary.completed, ''], [m.averageWait, baseline?.summary.waitSampleSize ? baseline.summary.meanWait : null, shownResult?.summary.waitSampleSize ? shownResult.summary.meanWait : null, 'wait'], [m.label95thPercentileWait, baseline?.summary.waitSampleSize ? baseline.summary.p95Wait : null, shownResult?.summary.waitSampleSize ? shownResult.summary.p95Wait : null, 'wait'], [m.resourceCost, baseline?.summary.cost, shownResult?.summary.cost, 'cost']].map(([label, a, b, kind]) =>
{label}{typeof a === 'number' ? kind === 'wait' ? wait(a) : kind === 'cost' ? money(a, baseline?.model.currency ?? project.model.currency) : number(a) : '—'}{typeof b === 'number' ? kind === 'wait' ? wait(b) : kind === 'cost' ? money(b, shownResult?.model.currency ?? project.model.currency) : number(b) : shownResult ? '—' : m.runYourPlan}
)}
{singlePaired ? m.sameExternalDemandSeed(shownResult?.seed) : !shownResult ? m.runTheCurrentDraftToCompareItWithThe : !singleCoupling ? m.matchingScopeWasNotRecordedInThisOlderRun : m.demandSeedOrMeasurementPoliciesDifferTheseAreSeparate}{m.samplingUncertaintyNote}
{baseline && shownResult && singleCoupling &&
{m.comparisonDetails}
} { setPanel(null); editSceneNode(id); }} /> { if (isLayoutOnly(snapshot)) throw new Error(tm.processRequired); const generation = ++requestGeneration.current; calculationStatus.controller.invalidate(panelGeneration.current); setLatestAttempt(null); const computed = await sim.run(snapshot.model); if (generation !== requestGeneration.current) throw new Error(m.supersededByANewerRun); if (computed.status !== 'completed') { setLatestAttempt(computed); throw new Error(computed.reason ?? m.baselineRunDidNotComplete); } setLatestAttempt(null); runDisplayNames.current.set(computed, snapshot.name); runPresentations.current.set(computed, capturePresentation(snapshot)); setBaseline(computed); }} />} + {stale && }
{m.fullRunHeading}{m.baseline}{baseline ? runDisplayNames.current.get(baseline) ?? baseline.model.name : '—'}{baseline && {ease.duration(baseline.model.horizon)} · {baseline.id.slice(0,8)}}{m.currentPlan}{shownResult ? runDisplayNames.current.get(shownResult) ?? shownResult.model.name : project.name}{ease.duration(shownResult?.model.horizon ?? project.model.horizon)}{shownResult ? ` · ${shownResult.id.slice(0,8)}` : ''}
{[[m.completed, baseline?.summary.completed, shownResult?.summary.completed, ''], [m.averageWait, baseline?.summary.waitSampleSize ? baseline.summary.meanWait : null, shownResult?.summary.waitSampleSize ? shownResult.summary.meanWait : null, 'wait'], [m.label95thPercentileWait, baseline?.summary.waitSampleSize ? baseline.summary.p95Wait : null, shownResult?.summary.waitSampleSize ? shownResult.summary.p95Wait : null, 'wait'], [m.resourceCost, baseline?.summary.cost, shownResult?.summary.cost, 'cost']].map(([label, a, b, kind]) =>
{label}{typeof a === 'number' ? kind === 'wait' ? wait(a) : kind === 'cost' ? money(a, baseline?.model.currency ?? project.model.currency) : number(a) : '—'}{typeof b === 'number' ? kind === 'wait' ? wait(b) : kind === 'cost' ? money(b, shownResult?.model.currency ?? project.model.currency) : number(b) : shownResult ? '—' : m.runYourPlan}
)}
{singlePaired ? m.sameExternalDemandSeed(shownResult?.seed) : !shownResult ? m.runTheCurrentDraftToCompareItWithThe : !singleCoupling ? m.matchingScopeWasNotRecordedInThisOlderRun : m.demandSeedOrMeasurementPoliciesDifferTheseAreSeparate}{m.samplingUncertaintyNote}
{baseline && shownResult && singleCoupling &&
{m.comparisonDetails}
} { setPanel(null); editSceneNode(id); }} /> { if (isLayoutOnly(snapshot)) throw new Error(tm.processRequired); const generation = ++requestGeneration.current; calculationStatus.controller.invalidate(panelGeneration.current); setLatestAttempt(null); const computed = await sim.run(snapshot.model); if (generation !== requestGeneration.current) throw new Error(m.supersededByANewerRun); if (computed.status !== 'completed') { setLatestAttempt(computed); throw new Error(computed.reason ?? m.baselineRunDidNotComplete); } setLatestAttempt(null); runDisplayNames.current.set(computed, snapshot.name); runPresentations.current.set(computed, capturePresentation(snapshot)); setBaseline(computed); }} />} {panel === 'model' && } {panel === 'insights' && openFiles('reports')} onExperiments={() => setPanel('experiments')} onSelectNode={id => { if (!project.model.nodes.some(node => node.id === id)) return; setPanel(null); editSceneNode(id); }} />} {panel === 'experiments' && layoutOnly &&

{tm.processRequired}

} diff --git a/src/features/LearningGuide.tsx b/src/features/LearningGuide.tsx new file mode 100644 index 0000000..f74ec57 --- /dev/null +++ b/src/features/LearningGuide.tsx @@ -0,0 +1,59 @@ +import { useEffect, useRef } from 'react'; +import { ArrowRight, Check, Compass, ChevronDown, LoaderCircle, X } from 'lucide-react'; +import { assetURL } from '../assetUrl'; +import { learningMessages as m } from '../ui/messages/learning'; +import { learningStages, type LearningSession, type LearningStage } from './learning'; +import type { RunResult } from '../model/types'; +import './learning.css'; + +export function LearningIntro({ busy, blocked, error, onStart, onExplore, onReference }: { + busy: boolean; blocked?: string; error?: string | null; + onStart: () => void; onExplore: () => void; onReference: () => void; +}) { + return
+
+

{m.welcome}

{m.introduction}

+
    {m.welcomeSteps.map((step, i) =>
  1. {i + 1}{step}
  2. )}
+

{m.practiceScope}

+ {blocked &&

{blocked}

} + {error &&

{error}

} +
+ +
+
; +} + +interface CoachProps { + session: LearningSession; stage: LearningStage; minimized: boolean; busy: boolean; busyLabel?: string; pending: boolean; + comparisonOpen: boolean; saveOpen: boolean; baseline: RunResult | null; result: RunResult | null; error?: string | null; + onAction: () => void; onMinimize: () => void; onLeave: () => void; onReturn: () => void; onFinishWithoutSave: () => void; +} +export function LearningCoach(props: CoachProps) { + const { session, stage, minimized, busy, pending, comparisonOpen, saveOpen, baseline, result, error } = props; + const resume = useRef(null), toggle = useRef(null), toggled = useRef(false); + useEffect(() => { if (toggled.current) { toggled.current = false; (minimized ? resume.current : toggle.current)?.focus(); } }, [minimized]); + const index = stage === 'complete' ? 4 : Math.max(0, learningStages.findIndex(item => item === stage)); + const caption = m.step(index + 1); + const minimize = () => { toggled.current = true; props.onMinimize(); }; + if (minimized) return ; + const content = stage === 'off-track' ? m.offTrack : stage === 'complete' ? null : m[stage]; + const action = stage === 'complete' ? m.continue : stage === 'review' && !comparisonOpen ? m.openComparison : stage === 'save' && saveOpen ? m.save.action : content!.action; + const formatCost = (run: RunResult) => new Intl.NumberFormat('en', { style: 'currency', currency: run.model.currency, maximumFractionDigits: 0 }).format(run.summary.cost); + return ; +} diff --git a/src/features/ProcessList.tsx b/src/features/ProcessList.tsx index 1ee9c1e..79c28da 100644 --- a/src/features/ProcessList.tsx +++ b/src/features/ProcessList.tsx @@ -17,7 +17,7 @@ export function ProcessList({ project, selectedId, selectedIds, onSelect }: Prop

{m.stepsCount(nodes.length, project.model.nodes.length)}{m.selectionCount(selectedIds.length)}

    {nodes.map(node =>
  • onSelect(node.id, 'toggle')} /> - +
  • )}
{!nodes.length &&

{m.noMatchingSteps}

} {search && } diff --git a/src/features/QuickProperties.tsx b/src/features/QuickProperties.tsx index 9618b48..d796531 100644 --- a/src/features/QuickProperties.tsx +++ b/src/features/QuickProperties.tsx @@ -13,7 +13,7 @@ import { NumberField, TimeField, usePendingEdit } from './EditFields'; import { ScheduleEditor, Timeline } from './ScheduleEditor'; import { easeMessages as m } from '../ui/messages/ease'; -interface Props { project: Project; node: ModelNode; onChange: (project: Project, label?: string) => void; onAdvanced: () => void; result?: RunResult | null; onPreviewConnection?: (targetId: string | null) => void } +interface Props { teamHint?: { poolId: string; text: string }; project: Project; node: ModelNode; onChange: (project: Project, label?: string) => void; onAdvanced: () => void; result?: RunResult | null; onPreviewConnection?: (targetId: string | null) => void } interface ControlProps extends Props { commit: (next: Project, label: string) => void; attempt: (action: () => void) => void } const count = (v: number) => v.toLocaleString('en', { maximumFractionDigits: 3 }); const money = (v: number, currency: string) => { try { return new Intl.NumberFormat('en', { style: 'currency', currency, maximumFractionDigits: 2 }).format(v); } catch { return `${count(v)} ${currency}`; } }; @@ -56,13 +56,16 @@ function DistributionControl({ project, node, distribution, commit, patience = f {error &&

{error}

}
; } -function TeamControl({ project, pool, service, commit }: { project: Project; pool: ResourcePool; service: ServiceNode; commit: ControlProps['commit'] }) { +function TeamControl({ project, pool, service, commit, hint }: { hint?: string; project: Project; pool: ResourcePool; service: ServiceNode; commit: ControlProps['commit'] }) { const consumers = project.model.nodes.filter((node): node is ServiceNode => node.kind === 'service' && node.resources.some(req => req.poolId === pool.id)); const requirement = service.resources.find(req => req.poolId === pool.id)!; const change = (patch: Partial) => commit(mutateProject(project, copy => { Object.assign(copy.model.resources.find(item => item.id === pool.id)!, patch); }), m.teamChanged(pool.label)); const context = `${project.id}:${pool.id}`; return
{pool.label}{m.availableUnits(pool.capacity, pool.installedCapacity)} +
+ {hint &&

{hint}

} change({ capacity })} help={m.unitsPerStart(requirement.units)} /> +
{consumers.length > 1 &&

{m.usedBy(consumers.map(node => node.label).join(', '))}

}
{m.teamPlanDetails} change({ installedCapacity })} /> @@ -135,7 +138,7 @@ export function QuickProperties(props: Props) { const controls: ControlProps = { ...props, commit, attempt }; return
- {node.kind === 'service' && <>
commit(mutateProject(project, copy => { const target = copy.model.nodes.find(item => item.id === node.id); if (target?.kind === 'service') target.servers = servers; }), m.stationChanged(node.label))} />
{node.resources.length > 0 &&

{m.teamHeading}

{node.resources.map(requirement => { const pool = project.model.resources.find(item => item.id === requirement.poolId); return pool ? : null; })}
{m.capacityExplanation}

{m.capacityScope}

}} + {node.kind === 'service' && <>
commit(mutateProject(project, copy => { const target = copy.model.nodes.find(item => item.id === node.id); if (target?.kind === 'service') target.servers = servers; }), m.stationChanged(node.label))} />
{node.resources.length > 0 &&

{m.teamHeading}

{node.resources.map(requirement => { const pool = project.model.resources.find(item => item.id === requirement.poolId); return pool ? : null; })}
{m.capacityExplanation}

{m.capacityScope}

}} {node.kind === 'delay' && } {node.kind === 'source' && } {node.kind === 'queue' && } diff --git a/src/features/TemplatesPanel.tsx b/src/features/TemplatesPanel.tsx index 1486efe..b13c9f8 100644 --- a/src/features/TemplatesPanel.tsx +++ b/src/features/TemplatesPanel.tsx @@ -14,9 +14,10 @@ import './templates.css'; export type StarterTemplate = StarterId | 'blank'; interface Props { project: Project; intent: 'browse' | 'save'; blockedReason?: string; saveBlockedReason?: string; + onSaved?: (project: Project, template: TemplateMetadata) => void; onStarter: (template: StarterTemplate) => void | Promise; onUse: (project: Project) => boolean; } -export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReason, onStarter, onUse }: Props) { +export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReason, onStarter, onUse, onSaved }: Props) { const [tab, setTab] = useState<'starters' | 'mine'>(intent === 'save' ? 'mine' : 'starters'); const [showSave, setShowSave] = useState(intent === 'save'); const [failedStarter, setFailedStarter] = useState(null); @@ -43,6 +44,7 @@ export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReas const snapshot = structuredClone(imported ?? project), templateName = name; void perform(async current => { const saved = await saveTemplate(snapshot, templateName); + onSaved?.(snapshot, saved); if (!current()) return; setStatus(m.saved(saved.name)); setImported(null); setShowSave(false); setQuery(''); await refresh(); requestAnimationFrame(() => { if (current()) panel.current?.querySelector(`[data-template-id="${saved.id}"] .ql-primary`)?.focus(); }); diff --git a/src/features/learning.css b/src/features/learning.css new file mode 100644 index 0000000..5885366 --- /dev/null +++ b/src/features/learning.css @@ -0,0 +1,10 @@ +.learning-intro{display:grid;grid-template-columns:minmax(240px,.85fr) minmax(340px,1fr);gap:30px;align-items:center}.learning-intro-visual{overflow:hidden;border-radius:16px;background:#e6ebdf;align-self:stretch;display:grid;place-items:center;min-height:320px}.learning-intro-visual img{width:145%;max-width:none;display:block}.learning-intro-copy h3{font-size:30px;line-height:1.14;letter-spacing:-1px;color:#173a2c;margin:0 0 16px}.learning-intro-copy>p{font-size:15px;line-height:1.6;color:#4b6556}.learning-overview{list-style:none;padding:0;margin:20px 0;display:grid;grid-template-columns:1fr 1fr;gap:10px}.learning-overview li{display:flex;align-items:center;gap:8px;font-size:12px;color:#294a32}.learning-overview li>span{display:grid;place-items:center;flex:none;width:22px;height:22px;background:#e4efd7;border-radius:50%;font-size:11px;font-weight:700}.learning-scope{font-size:12px!important;line-height:1.6;color:#52664e}.learning-intro-actions{display:flex;flex-direction:column;gap:9px;margin-top:22px}.learning-primary,.learning-secondary{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:44px;padding:12px 17px;border-radius:8px;border:1px solid #173a2c;font:inherit;font-size:13px;font-weight:650;cursor:pointer}.learning-primary{background:#173a2c;color:#fff}.learning-primary:hover:not(:disabled){background:#28573c}.learning-secondary{background:transparent;color:#173a2c;border-color:#cad8c1}.learning-primary:disabled,.learning-secondary:disabled{opacity:.55;cursor:default}.learning-text-button{background:none;border:0;padding:8px 0;color:#426339;text-decoration:underline;text-underline-offset:3px;font:inherit;font-size:12px;cursor:pointer;text-align:left}.learning-text-button:disabled{opacity:.55;cursor:default}.learning-intro-copy>.learning-text-button{display:block;margin:7px auto 0}.learning-feedback{font-size:12px!important;color:#785315!important}.learning-error{font-size:13px!important;color:#a0372b!important;line-height:1.5}.learning-coach{flex:none;padding:16px 26px 18px;background:#f2f7e9;color:#173a2c;border-bottom:1px solid #cad8bc;animation:learning-enter .2s ease-out}.learning-coach-top{display:flex;justify-content:space-between;align-items:center;font-size:11px;font-weight:700;letter-spacing:.3px}.learning-coach-top>span{display:flex;gap:7px;align-items:center}.learning-coach-top>div{display:flex;gap:5px}.learning-coach-top button{display:grid;place-items:center;min-width:32px;min-height:32px;background:transparent;border:0;border-radius:6px;color:#3d5b39;cursor:pointer}.learning-coach-top button:hover{background:#e0ecd3}.learning-progress{padding:0;margin:3px 0 14px;display:flex;gap:22px;list-style:none;max-width:690px}.learning-progress li{display:flex;align-items:center;gap:6px;color:#586d4f;font-size:11px;white-space:nowrap}.learning-progress li>span:first-child{display:grid;place-items:center;width:21px;height:21px;border-radius:50%;border:1px solid #bccbb1;font-size:10px;transition:background .18s,color .18s}.learning-progress .is-current{font-weight:750;color:#173a2c}.learning-progress .is-current>span:first-child{background:#173a2c;color:#fff;border-color:#173a2c}.learning-progress .is-done>span:first-child{background:#d4e9bb;border-color:#c2dca5;color:#25482c}.learning-coach-main{display:flex;align-items:center;gap:32px;justify-content:space-between}.learning-coach-main>div:first-child{max-width:780px}.learning-coach h3{margin:0 0 5px;font-size:23px;line-height:1.2;letter-spacing:-.6px}.learning-coach-main p{font-size:13px;line-height:1.6;margin:0;color:#415b39}.learning-step-caption{display:none}.learning-coach-actions{display:flex;align-items:flex-end;flex-direction:column;gap:2px;flex-shrink:0}.learning-coach-actions .learning-primary{min-width:180px}.learning-coach-actions .learning-text-button{text-align:right}.learning-mini{flex:none;background:#f2f7e9;border-bottom:1px solid #cad8bc;padding:9px 26px}.learning-mini button{display:flex;align-items:center;gap:10px;background:none;border:0;color:#173a2c;min-height:32px;font:inherit;font-size:12px;cursor:pointer}.learning-mini button>span{font-size:11px;color:#52664e;margin-left:8px}.learning-coach :is(button,a):focus-visible,.learning-mini button:focus-visible,.learning-intro :is(button,a):focus-visible{outline:3px solid #537b3c;outline-offset:3px}.learning-saved{display:flex;align-items:center;gap:7px;margin-top:10px!important;font-weight:650}.learning-outcomes{display:flex;gap:32px;margin:18px 0 10px;padding-top:16px;border-top:1px solid #cad8bc;flex-wrap:wrap}.learning-outcomes dt{font-size:11px;color:#52664e;margin-bottom:5px}.learning-outcomes dd{margin:0;display:flex;align-items:center;gap:10px;font-size:22px}.learning-outcomes dd>span{color:#586c4d}.learning-outcomes dd strong{font-weight:750}.learning-target{outline:3px solid #608b43!important;outline-offset:4px!important;scroll-margin:170px 20px 90px;box-shadow:0 0 0 7px #c5e99555!important;border-radius:6px}.modal-body>.learning-coach{margin:-20px -20px 22px;padding:12px 20px 18px;border-radius:0}.modal-body>.learning-mini{margin:-20px -20px 20px}.facility-studio .modal[data-panel=learn]{width:min(940px,calc(100vw - 40px))}.guided-comparison .comparison-disclosure,.guided-comparison .saved-scenarios,.guided-comparison .decision-guide,.guided-comparison .comparison-note,.guided-comparison .comparison-table .table-header small,.guided-comparison .comparison-advanced-action{display:none!important} +@keyframes learning-enter{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}} +@media(max-width:900px){.learning-intro{grid-template-columns:1fr}.learning-intro-visual{min-height:0;height:170px}.learning-intro-visual img{width:100%;max-width:600px}.learning-intro-copy h3{font-size:25px}.learning-coach-main{gap:18px}.learning-coach-actions .learning-primary{min-width:0}.learning-progress{gap:12px}.learning-coach{padding:12px 18px 16px}} +@media(max-width:740px){.learning-coach{padding:10px 16px 14px;position:sticky;top:0;z-index:35}.learning-coach-top{min-height:26px}.learning-progress{margin:3px 0 10px;gap:9px}.learning-progress li>span:last-child{display:none}.learning-progress li>span:first-child{width:22px;height:22px}.learning-step-caption{display:block;font-size:10px;font-weight:700;margin-bottom:4px;color:#52664e}.learning-coach h3{font-size:19px}.learning-coach-main{display:block}.learning-coach-main p{font-size:12px;line-height:1.5}.learning-coach-actions{margin-top:12px;align-items:stretch;gap:4px}.learning-coach-actions .learning-primary{width:100%;min-height:42px}.learning-coach-actions .learning-text-button{text-align:left;padding:5px 0}.learning-mini{padding:8px 12px}.learning-mini button{gap:7px;font-size:11px}.learning-mini button>span{font-size:10px;margin-left:0}.learning-outcomes{gap:16px}.learning-outcomes dd{font-size:18px;gap:6px}.learning-intro{gap:18px}.learning-intro-visual{height:135px}.learning-intro-copy>p{font-size:14px}.learning-overview{margin:16px 0;gap:8px}.learning-overview li{font-size:11px}.learning-intro-actions{margin-top:16px}.modal-body>.learning-coach{position:relative;top:auto;margin:-20px -20px 18px;padding:10px 16px 14px}.modal-body>.learning-mini{margin:-20px -20px 18px}.learning-target{scroll-margin-top:285px}.facility-studio .modal[data-panel=learn]{width:calc(100vw - 24px)}} +@media(prefers-reduced-motion:reduce){.learning-coach{animation:none}.learning-progress li>span:first-child{transition:none}} +.learning-reduced-motion .learning-coach{animation:none}.learning-reduced-motion .learning-progress li>span:first-child{transition:none} + +.facility-studio .studio-inspector .learning-field-hint{margin:8px 0 12px;padding:10px 12px;background:#edf5e2;border-left:3px solid #608b43;color:#25482c;font-size:12px;font-weight:600;line-height:1.5} + +@media(max-width:359px){.modal-body>.learning-coach,.modal-body>.learning-mini{margin-top:-17px;margin-left:-17px;margin-right:-17px}} diff --git a/src/features/learning.ts b/src/features/learning.ts new file mode 100644 index 0000000..c4c2788 --- /dev/null +++ b/src/features/learning.ts @@ -0,0 +1,86 @@ +import type { Project, RunResult } from '../model/types'; +import { canonical, modelHash } from '../model/identity'; + +export const LEARNING_STEP_ID = 'station-b'; +export const LEARNING_POOL_ID = 'specialists'; +export const LEARNING_PREFERENCES_KEY = 'loopset-learning-v1'; +export const LEARNING_SESSION_KEY = 'loopset-practice-v1'; +export interface LearningSession { + version: 1; projectId: string; returnProjectId: string | null; + baseHash: string; changedHash: string; seed: number; + selected: boolean; ran: boolean; reviewed: boolean; + finished?: boolean; savedName?: string; +} +export type LearningStage = 'preparing' | 'select' | 'edit' | 'run' | 'review' | 'save' | 'complete' | 'off-track' | 'baseline'; +export const learningStages = ['select', 'edit', 'run', 'review', 'save'] as const; + +export function createLearningSession(project: Project, returnProjectId: string | null): LearningSession | null { + const step = project.model.nodes.find(node => node.id === LEARNING_STEP_ID); + const pool = project.model.resources.find(item => item.id === LEARNING_POOL_ID); + if (project.world !== 'service' || step?.kind !== 'service' || !step.resources.some(item => item.poolId === LEARNING_POOL_ID) || pool?.capacity !== 2 || pool.installedCapacity < 3) return null; + const changed = structuredClone(project.model); + changed.resources.find(item => item.id === LEARNING_POOL_ID)!.capacity = 3; + return { version: 1, projectId: project.id, returnProjectId, baseHash: modelHash(project.model), changedHash: modelHash(changed), seed: project.model.seed, selected: false, ran: false, reviewed: false }; +} + +export function learningModelMatches(project: Project, session: LearningSession): boolean { + return project.id === session.projectId && project.model.seed === session.seed && [session.baseHash, session.changedHash].includes(modelHash(project.model)); +} +export function originalLearningProject(project: Project, session: LearningSession): Project | null { + if (!learningModelMatches(project, session)) return null; + const original = structuredClone(project); + const pool = original.model.resources.find(item => item.id === LEARNING_POOL_ID); + if (!pool) return null; + pool.capacity = 2; + return modelHash(original.model) === session.baseHash ? original : null; +} +export function learningRunMatches(run: RunResult | null, hash: string, seed: number): boolean { + return Boolean(run?.status === 'completed' && run.modelHash === hash && run.seed === seed && modelHash(run.model) === hash); +} +export function learningStage(input: { + session: LearningSession; project: Project; baseline: RunResult | null; result: RunResult | null; + pending: boolean; running: boolean; valid: boolean; comparable: boolean; +}): LearningStage { + const { session, project, baseline, result, pending, running, valid, comparable } = input; + if (session.finished) return 'complete'; + if (!valid || !learningModelMatches(project, session)) return 'off-track'; + if (!learningRunMatches(baseline, session.baseHash, session.seed)) return running ? 'preparing' : 'baseline'; + if (!session.selected) return 'select'; + if (modelHash(project.model) !== session.changedHash || pending) return 'edit'; + if (!session.ran || !learningRunMatches(result, session.changedHash, session.seed) || !comparable) return 'run'; + return session.reviewed ? 'save' : 'review'; +} + +export function parseLearningSession(text: string | null): LearningSession | null { + if (!text || text.length > 2048) return null; + try { + const v: unknown = JSON.parse(text); + if (!v || typeof v !== 'object' || Array.isArray(v)) return null; + const r = v as Record; + const id = (x: unknown): x is string => typeof x === 'string' && x.length > 0 && x.length <= 160 && !x.includes('\0'); + const hash = (x: unknown): x is string => typeof x === 'string' && /^[a-f0-9]{8,64}$/.test(x); + if (r.version !== 1 || !id(r.projectId) || !(r.returnProjectId === null || id(r.returnProjectId)) || !hash(r.baseHash) || !hash(r.changedHash) || r.baseHash === r.changedHash || typeof r.seed !== 'number' || !Number.isSafeInteger(r.seed) || typeof r.selected !== 'boolean' || typeof r.ran !== 'boolean' || typeof r.reviewed !== 'boolean') return null; + return { version: 1, projectId: r.projectId, returnProjectId: r.returnProjectId, baseHash: r.baseHash, changedHash: r.changedHash, seed: r.seed, selected: r.selected, ran: r.ran, reviewed: r.reviewed }; + } catch { return null; } +} +export function readLearningSession(): LearningSession | null { + try { return parseLearningSession(sessionStorage.getItem(LEARNING_SESSION_KEY)); } catch { return null; } +} +export function rememberLearningSession(session: LearningSession | null): void { + try { + if (!session || session.finished) { sessionStorage.removeItem(LEARNING_SESSION_KEY); return; } + const { version, projectId, returnProjectId, baseHash, changedHash, seed, selected, ran, reviewed } = session; + sessionStorage.setItem(LEARNING_SESSION_KEY, JSON.stringify({ version, projectId, returnProjectId, baseHash, changedHash, seed, selected, ran, reviewed })); + } catch { /* The lesson still works in memory; project saves report their own failures. */ } +} +export function hasSeenLearningWelcome(): boolean { + try { return localStorage.getItem(LEARNING_PREFERENCES_KEY) === 'seen'; } catch { return false; } +} +export function rememberLearningWelcome(): void { + try { localStorage.setItem(LEARNING_PREFERENCES_KEY, 'seen'); } catch { /* Optional preference, not a project save. */ } +} + +/** Storage canonicalizes object keys and supplies a new save timestamp. */ +export function learningReturnMatches(previous: Project, saved: Project): boolean { + return canonical({ ...previous, savedAt: undefined }) === canonical({ ...saved, savedAt: undefined }); +} diff --git a/src/ui/messages/App.ts b/src/ui/messages/App.ts index e198385..c611e4b 100644 --- a/src/ui/messages/App.ts +++ b/src/ui/messages/App.ts @@ -140,11 +140,11 @@ export const appMessages = { watchDemos: "Watch the video demos", watchDemosNewTab: "Watch the video demos (opens in a new tab)", freeOpenSource: "FREE & OPEN SOURCE ", - earlyBuild: "RC14", + earlyBuild: "RC15", syntheticExample: "SYNTHETIC EXAMPLE", openProject: "Open project", saveProject: "Download project JSON", - buildBadge: "V1 / RC14", + buildBadge: "V1 / RC15", aPlaygroundForBetterDecisions: "A PLAYGROUND FOR BETTER DECISIONS", calculationWorkLimits: "Calculation work & limits", calculationProgress: (percent: number) => `${percent}% calculating`, @@ -301,7 +301,7 @@ export const appMessages = { backupDownloadRequested: (repair: boolean) => `${repair ? 'Unvalidated repair backup' : 'Project file'} download requested. Verify the saved file; a request does not confirm a backup.`, retainedDraftRecovery: (count: number) => `${count} retained draft${count === 1 ? '' : 's'} · review recovery`, selectionSummary: (count: number, name: string) => `${count} selected · Inspecting ${name}`, - modalSection: (panel: 'worlds' | 'model' | 'compare' | 'data' | 'experiments' | 'insights' | 'budget' | 'history' | 'help' | 'scenario' | 'view' | 'rename' | 'search' | 'guide' | 'brief') => ({ worlds: 'TEMPLATES', brief: 'PROJECT BRIEF', model: 'MODEL', compare: 'COMPARE', data: 'DATA', experiments: 'EXPERIMENTS', insights: 'INSIGHTS', budget: 'BUDGET', history: 'HISTORY', help: 'HELP', scenario: 'SCENARIO', view: 'VIEW', rename: 'PROJECT', search: 'FIND', guide: 'GUIDE' })[panel], + modalSection: (panel: 'worlds' | 'model' | 'compare' | 'data' | 'experiments' | 'insights' | 'budget' | 'history' | 'help' | 'scenario' | 'view' | 'rename' | 'search' | 'guide' | 'brief' | 'learn') => ({ learn: 'LEARN BY DOING', worlds: 'TEMPLATES', brief: 'PROJECT BRIEF', model: 'MODEL', compare: 'COMPARE', data: 'DATA', experiments: 'EXPERIMENTS', insights: 'INSIGHTS', budget: 'BUDGET', history: 'HISTORY', help: 'HELP', scenario: 'SCENARIO', view: 'VIEW', rename: 'PROJECT', search: 'FIND', guide: 'GUIDE' })[panel], worldQuestion: (subtitle: string) => `${subtitle}. What would you change?`, runCurrency: (currency: string) => `Full run · ${currency}`, processingUnit: (unit: string) => `sec / ${unit}`, diff --git a/src/ui/messages/learning.ts b/src/ui/messages/learning.ts new file mode 100644 index 0000000..218e23d --- /dev/null +++ b/src/ui/messages/learning.ts @@ -0,0 +1,42 @@ +export const learningMessages = { + title: 'Make your first experiment', section: 'LEARN BY DOING', entry: 'Learn by doing', + welcome: 'What happens if one more specialist joins the team?', + introduction: 'Find the busy step, change its shared team, and compare the real result. Five small steps will take you through your first real simulation.', + practiceScope: 'We will open a separate Service Studio practice project. Your current project is kept before switching.', + welcomeSteps: ['Choose a step', 'Change the team', 'Run the plan', 'Read the trade-off', 'Keep your version'], + start: 'Start my first experiment', starting: 'Preparing your practice…', explore: 'Explore on my own', reference: 'Just show me the controls', + waiting: 'Wait for the current calculation to finish, or close this guide and cancel it.', + pending: 'Apply or cancel the unfinished field first. Your draft stays here.', + opening: 'Opening project…', + storageWaiting: 'Opening your saved workspace…', + practiceName: 'My first experiment', originalPlan: 'Original plan', changedPlan: 'Your experiment', + startFailed: 'The practice project could not open. Your current project is still here. Try again.', + starterChanged: 'This starter no longer matches the exercise. You can still explore its template normally.', + preservationFailed: 'Your current work could not be saved. Keep it open or download a backup before starting practice.', + returnFailed: 'The previous project could not be reopened. Your current practice is still here.', + returnMissing: 'That project is no longer available in this browser. Open Files to find your saved work or keep exploring this practice.', + coach: 'Guided experiment', progress: 'Experiment progress', step: (n: number) => `Step ${n} of 5`, + labels: { select: 'Choose', edit: 'Change', run: 'Run', review: 'Compare', save: 'Keep' }, + select: { title: 'Find the Specialists step', text: 'Requests arrive, wait, and move through the team. Select Specialists in the scene or the Steps list to see what controls its capacity.', action: 'Open the Steps list' }, + edit: { title: 'Give the shared team one more unit', text: 'In Shared specialists, change Base available units from 2 to 3. Press Enter to apply it. The parallel stations can stay as they are.', action: 'Show the team setting' }, + run: { title: 'Now test your changed plan', text: 'Run & compare calculates a new result. Your original plan remains the baseline. The Play control only replays recorded work.', action: 'Run & compare' }, + review: { title: 'Read the whole trade-off', text: 'Look at completed work, waiting and resource cost together. Decide whether the change is worth its cost in this model.', action: 'Keep this version' }, + save: { title: 'Make this a reusable starting point', text: 'Give your plan a name and choose Save template. It will appear in My templates, ready to use as a new project.', action: 'Save as template' }, + preparing: { title: 'Calculating the original plan', text: 'This gives your experiment a real baseline. The next step will be ready when the calculation completes.', action: 'Wait for the result' }, + baseline: { title: 'Prepare the original comparison', text: 'This exercise needs a completed original plan. Calculate it again to continue; your changed draft stays intact.', action: 'Calculate original plan' }, + offTrack: { title: 'You are exploring a different idea', text: 'Other model inputs changed, so this is no longer the one-team exercise. Keep exploring, or start a fresh practice project. Your current version is kept.', action: 'Start a fresh practice' }, + fieldHint: 'Change 2 to 3, then press Enter to apply.', + running: 'Calculating your plan…', applyField: 'Apply or cancel the field to continue.', + calculationIncomplete: 'The calculation did not finish. Your original result is kept; try the changed plan again.', + openComparison: 'Open the comparison', + pause: 'Minimize guide', resume: 'Resume guided experiment', leave: 'Leave guide', return: 'Back to my previous project', + finishWithoutSave: 'Finish without saving a template', + completed: 'You made a real experiment.', + completedText: 'You chose a step, changed one assumption, ran the model and compared the outcome. That is the loop you can use for your own ideas.', + saved: (name: string) => `Template saved: ${name}`, + notSaved: 'No template was saved. You can save one later or download project JSON to keep an editable copy.', + continue: 'Explore this project', + waitValue: (seconds: number) => `${(seconds / 60).toFixed(1)} min`, + completedLabel: 'Completed requests', waitLabel: 'Average wait', costLabel: 'Resource cost', + lessonScope: 'Synthetic practice model. Results depend on the inputs; resource cost is not total business cost.', +} as const; diff --git a/src/ui/messages/shellEase.ts b/src/ui/messages/shellEase.ts index 65e9dc3..bf54fa9 100644 --- a/src/ui/messages/shellEase.ts +++ b/src/ui/messages/shellEase.ts @@ -23,11 +23,12 @@ export const shellEaseMessages = { { title: 'Run the changed plan', text: 'Choose Run & compare to calculate. Your original result stays available. Replay shows the recorded run; changing its speed never changes the answer.', target: 'run', action: 'Go to Run' }, { title: 'Compare and keep it', text: 'Compare shows which inputs changed and what happened to completed work, waiting and cost. Save an alternative here. Download project JSON in the header for a portable copy; Open restores it later.', target: 'compare', action: 'Open comparison' }, ], - localProject: 'ON THIS DEVICE', firstSteps: 'How it works', workspaceQuestion: 'What changes when demand or capacity changes?', + localProject: 'ON THIS DEVICE', firstSteps: 'Learn by doing', workspaceQuestion: 'What changes when demand or capacity changes?', worldQuestions: { factory: 'What is holding up the packing line?', festival: 'How can you keep the entrance moving?', service: 'Where does the shared team need more capacity?' }, startFlow: 'Arrival → waiting → processing → completion', commandScope: 'Typing searches the available actions. Calculations, downloads and new models start only when you select their action.', noCommands: 'No matching action or setting.', commands: { + learn: { label: 'Practice your first experiment', keywords: 'learn guide tutorial onboarding practice learn by doing' }, newModel: { label: 'Create a new process', keywords: 'new blank start model yeni boş başlangıç' }, scenario: { label: 'Run length and scenario', keywords: 'duration time horizon days hours minutes süre zaman' }, demand: { label: 'Arrival demand', keywords: 'arrivals people orders intensity rate geliş insan sipariş yoğunluk' }, diff --git a/tests/learning.test.ts b/tests/learning.test.ts new file mode 100644 index 0000000..0142140 --- /dev/null +++ b/tests/learning.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; +import { buildStarter } from '../src/templates/definitions'; +import { simulate } from '../src/engine'; +import { createLearningSession, learningReturnMatches, learningModelMatches, learningRunMatches, learningStage, originalLearningProject, parseLearningSession } from '../src/features/learning'; + +function exercise() { + const original = buildStarter('service'), session = createLearningSession(original, 'previous')!; + const project = structuredClone(original); + project.model.resources.find(pool => pool.id === 'specialists')!.capacity = 3; + return { original, session, project, baseline: simulate(original.model), result: simulate(project.model), pending: false, running: false, valid: true, comparable: true }; +} +describe('learn-by-doing progression', () => { + it('requires selection, an applied change, a completed matching run and review', () => { + const e = exercise(); + expect(learningStage({ ...e, project: e.original })).toBe('select'); + e.session.selected = true; + expect(learningStage({ ...e, project: e.original })).toBe('edit'); + expect(learningStage({ ...e, pending: true })).toBe('edit'); + expect(learningStage(e)).toBe('run'); + e.session.ran = true; + expect(learningStage(e)).toBe('review'); + e.session.reviewed = true; + expect(learningStage(e)).toBe('save'); + expect(e.result.summary.completed).toBeGreaterThan(e.baseline.summary.completed); + expect(e.result.summary.meanWait).toBeLessThan(e.baseline.summary.meanWait); + expect(e.result.summary.cost).toBeGreaterThan(e.baseline.summary.cost); + }); + it('cannot pass a missing, partial, stale, tampered or noncomparable run', () => { + const e = exercise(); e.session.selected = true; e.session.ran = true; + for (const result of [null, e.baseline, { ...e.result, status: 'cancelled' as const }, { ...e.result, seed: e.session.seed + 1 }, { ...e.result, model: e.original.model }]) expect(learningStage({ ...e, result })).toBe('run'); + expect(learningStage({ ...e, comparable: false })).toBe('run'); + expect(learningRunMatches(e.result, e.session.baseHash, e.session.seed)).toBe(false); + expect(learningStage({ ...e, baseline: null })).toBe('baseline'); + expect(learningStage({ ...e, baseline: null, running: true })).toBe('preparing'); + }); + it('reconstructs the exact original without changing the working model or visual edits', () => { + const e = exercise(); e.project.name = 'My own title'; e.project.layout['station-b'].x += 2; + const before = structuredClone(e.project), restored = originalLearningProject(e.project, e.session)!; + expect(restored.model).toEqual(e.original.model); expect(restored.layout).toEqual(e.project.layout); + expect(e.project).toEqual(before); + e.project.model.horizon += 1; + expect(originalLearningProject(e.project, e.session)).toBeNull(); + expect(learningStage(e)).toBe('off-track'); + }); + it('does not apply an exercise to another project, seed or incompatible starter', () => { + const e = exercise(); + expect(learningModelMatches({ ...e.project, id: 'different' }, e.session)).toBe(false); + expect(learningModelMatches({ ...e.project, model: { ...e.project.model, seed: e.session.seed + 1 } }, e.session)).toBe(false); + expect(createLearningSession(buildStarter('factory'), null)).toBeNull(); + expect(createLearningSession(e.project, null)).toBeNull(); + expect(learningStage({ ...e, valid: false })).toBe('off-track'); + }); + it('keeps completion separate from saving a template', () => { + const e = exercise(); e.session.finished = true; + expect(learningStage(e)).toBe('complete'); expect(e.session.savedName).toBeUndefined(); + }); +}); +describe('bounded lesson receipts', () => { + it('retains only navigation and earned progress, never projects, results or saved claims', () => { + const { session, project, result } = exercise(); session.selected = true; + expect(parseLearningSession(JSON.stringify({ ...session, project, result }))).toBeNull(); + expect(parseLearningSession(JSON.stringify({ ...session, finished: true, savedName: 'Unverified', extra: 1 }))).toEqual(session); + }); + it('rejects malformed, incompatible and unbounded receipts', () => { + const { session } = exercise(); + for (const value of [null, '', '{', '[]', 'null', ' '.repeat(2049)]) expect(parseLearningSession(value)).toBeNull(); + for (const patch of [{ version: 2 }, { projectId: '' }, { returnProjectId: 4 }, { seed: 1.2 }, { baseHash: 'invalid' }, { changedHash: session.baseHash }, { selected: 'yes' }, { ran: null }, { reviewed: 1 }]) expect(parseLearningSession(JSON.stringify({ ...session, ...patch }))).toBeNull(); + }); +}); + +describe('returning from practice', () => { + it('preserves history for identical saved content despite storage key order and timestamp changes', () => { + const original = buildStarter('service'); + const stored = Object.fromEntries(Object.keys(original).sort().map(key => [key, original[key as keyof typeof original]])) as unknown as typeof original; + stored.savedAt = '2026-01-01T00:00:00.000Z'; + expect(learningReturnMatches(original, stored)).toBe(true); + expect(learningReturnMatches(original, { ...stored, revision: stored.revision + 1 })).toBe(false); + expect(learningReturnMatches(original, { ...stored, name: 'Newer saved work' })).toBe(false); + }); +});