diff --git a/PROGRESS.md b/PROGRESS.md index 3fdf5fb..712fbbe 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -37,3 +37,4 @@ Full earlier progress and acceptance records are preserved in the [archive](docs - **Model tier.** `/v1/models` has no explicit tier field (`owned_by:"nearai"`). The SDK's attestation criterion (`/v1/model/{id}`: `providerType:"vllm"`, `attestationSupported:true`) is what Familiar checks. - **Brief vs repository.** The handoff said `.env.example` already had a `NEAR_AI_API_KEY` placeholder; it did not. The placeholder was added (empty). | 2026-11-14 | One tide: the tide run and the Tidekeeper's ask as one game, on local branch `feat/one-tide` (merges `feat/one-tide-ui` `e7b29fe` into familiar-bb's `f5643c5`). On device harbors the daily is the tide run: Today's tide shows the day's card, Bram's guess and three stamps (home, guess, dry); the Home sheet celebrates the result; the tide log keeps run pages beside old three-ask pages; Bram's shelf offers today's reed and glass, up to 3 each, and pearls stay with Mochi. Signed-in harbors keep the three-ask court. Not pushed or deployed | At `f67d9fe`: `bun run typecheck`; `bun run test` 485 pass/0 fail/40232 assertions; `bun --no-env-file run build:release`; `cargo test --manifest-path contracts/Cargo.toml --workspace`; `test:tide-browser` (390×844, 412×860, 844×390, 1280×800, 1440×900), `test:tide-run-browser`, `test:season-browser`, `test:expedition-harbor-browser`, `test:expedition-touch-browser`, `test:routing-browser`, `test:records-browser` all pass. `test:expedition-browser` (320 harbor brand clickable) and `test:expedition-qa-browser` (home controls obscured at 9 sizes, 667×375 court) fail with the same messages at the base `57d8565`. At `b95ae9d`, `test:expedition-lifecycle-browser` reaches the court through the Chart and then fails at the same "Familiar home" obscured assertion as the base. Chromium screenshots from a fresh harbor through chapter one, the lit harbor, today's tide, the Home sheet, the log, Bram's shelf and the harbor after at 390×844, 844×390 and 1280×800, with no page errors. Browser emulation only: no real device, no human playtest, signed-in shelf not exercised | +| 2026-11-14 | Slice B verification (uncommitted working tree on `feat/keep-wrens-light-onboarding`, base `ca01a92`): Keep Wren's Light prologue and in-run teaching. **Not committed: the Chromium tide-run suite fails** | `bun run typecheck` pass; `bun run test` 555 pass/0 fail/41739 assertions across 76 files; `bun run build` pass. **`test:tide-run-browser` fails in Chromium** (first engine, first scenario `destinationEdgeTaps`, `scripts/test-tide-run-browser.ts:230` via `:170`): `open controls before destination-edge taps: Mochi’s body is exposed` `'DIV' !== 'CANVAS'`. At 390×844 with Button controls open, `.tide-tray-reading` (objective/forecast) covers Mochi on the dock at y≈503, and a screenshot shows Mochi and the dock hidden behind the tray. It failed the same way when run on its own (3 s), so WebKit was never reached. When all 13 browser processes ran at once, `routing`, `tide`, `season`, `records` and `expedition-qa` passed. `tide-run` ×3, `expedition`, `expedition-touch`, `expedition-lifecycle`, `passage` and `expedition-harbor` failed under that load, mostly 5 s readiness timeouts. Run one at a time afterwards, `expedition-harbor`, `expedition`, `expedition-touch`, `expedition-lifecycle` and `passage` all passed. Only `tide-run` still fails. A Chromium 390×844 touch walkthrough on a fresh device with the network blocked by the fixtures: the prologue copy matches the plan; the objective line is partly hidden behind the actions at first paint but can be scrolled into view (panel overflow 47 px); the first cue and the lens-safe decision copy match the plan; Help Mochi, Sail, and Keep gathering respond to taps; no page errors. Browser emulation only | diff --git a/scripts/browser-controls.ts b/scripts/browser-controls.ts index b88ad85..d63418c 100644 --- a/scripts/browser-controls.ts +++ b/scripts/browser-controls.ts @@ -51,3 +51,15 @@ export async function sailStory(page:Page){ await page.getByRole("button",{name:/^Prepare Chapter \d+$/}).click(); await page.getByRole("button",{name:"Sail with Mochi",exact:true}).click(); } + +/** A repair stays on each earned beat until the player chooses to continue. */ +export async function continueStoryExchange(page:Page){ + const dialog=page.getByRole("dialog").filter({has:page.getByRole("button",{name:/^Continue(?: with Mochi)?$/,exact:true})}); + await dialog.waitFor(); + for(let beat=0;beat<4;beat++){ + const next=dialog.getByRole("button",{name:"Continue",exact:true}); + if(await next.count())await next.click(); + else{await dialog.getByRole("button",{name:"Continue with Mochi",exact:true}).click();return;} + } + throw Error("Story exchange did not reach its final confirmation"); +} diff --git a/scripts/browser-fixtures.test.ts b/scripts/browser-fixtures.test.ts index 231d2ee..d6a690c 100644 --- a/scripts/browser-fixtures.test.ts +++ b/scripts/browser-fixtures.test.ts @@ -1,12 +1,14 @@ import { expect, test } from "bun:test"; import type { Page, Route } from "@playwright/test"; import { runInNewContext } from "node:vm"; -import { BROWSER_DAY, prepareBrowser, seasonRpcFixture } from "./browser-fixtures"; +import { BROWSER_DAY, prepareBrowser, seasonRpcFixture, seedGameplayGuidance } from "./browser-fixtures"; +import { GUIDANCE_KEY } from "../web/src/run/guidance"; const rpc=(method:string,args:unknown={},receiver="season.familiar-game.testnet")=>JSON.stringify({jsonrpc:"2.0",id:"season",method:"query",params:{request_type:"call_function",finality:"final",account_id:receiver,method_name:method,args_base64:btoa(JSON.stringify(args))}}); test("browser RPC fixtures match endpoint, receiver, method and exact arguments",()=>{ expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc("get_shelf"),BROWSER_DAY)).toMatchObject({day:BROWSER_DAY}); expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:null}),BROWSER_DAY)).toMatchObject({day:BROWSER_DAY,content_version:"first_light_v2"}); + expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:"helper-a.familiar-game.testnet"}),BROWSER_DAY)).toMatchObject({day:BROWSER_DAY,content_version:"first_light_v2"}); for(const [method,args] of [["get_account",{account_id:"alice.familiar-game.testnet"}],["get_wish",{pet:"mochi.familiar-game.testnet"}],["get_postcard",{pet:"mochi.familiar-game.testnet"}]] as const) expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc(method,args),BROWSER_DAY)).toBeNull(); for(const [url,verb,body] of [["https://test.rpc.fastnear.com.evil/","POST",rpc("get_shelf")],["https://test.rpc.fastnear.com/other","POST",rpc("get_shelf")],["https://test.rpc.fastnear.com","GET",rpc("get_shelf")],["https://test.rpc.fastnear.com","POST",rpc("get_shelf",{},"other.testnet")],["https://test.rpc.fastnear.com","POST",rpc("unknown")],["https://test.rpc.fastnear.com","POST",rpc("get_shelf",{unexpected:true})],["https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:null,extra:true})],["https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:"unknown.testnet"})]]) @@ -19,7 +21,7 @@ test(`browser preparation shifts only the running wall clock and validates every let dateScript!:(time:number)=>void; let handle!:(route:Route)=>Promise; const page={clock:{install:async(value:unknown)=>{calls.push(["install",value]);}},addInitScript:async(callback:typeof dateScript,time:number)=>{dateScript=callback;calls.push(["date",time]);},evaluate:async(callback:typeof dateScript,time:number)=>{dateScript=callback;calls.push(["shift",time]);},route:async(pattern:string,callback:typeof handle)=>{calls.push(["route",pattern]);handle=callback;}} as unknown as Page; - const network=await prepareBrowser(page,origin,BROWSER_DAY); + const network=await prepareBrowser(page,origin,BROWSER_DAY,{guidance:false}); const noon=BROWSER_DAY*86_400_000+43_200_000; expect(calls).toEqual([["date",noon],["route","**/*"]]); let elapsed=10_000; @@ -71,15 +73,32 @@ test(`browser preparation shifts only the running wall clock and validates every test("only deliberate timer-control scenarios install Playwright's full clock",async()=>{ const calls:unknown[]=[]; const page={clock:{install:async(value:unknown)=>{calls.push(["manual",value]);}},addInitScript:async()=>{calls.push(["date"]);},route:async()=>{}} as unknown as Page; - const manual=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:"manual"}); + const manual=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:"manual",guidance:false}); expect(calls).toEqual([["manual",{time:new Date(BROWSER_DAY*86_400_000+43_200_000)}]]); calls.length=0; - const unclocked=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:false}); + const unclocked=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:false,guidance:false}); expect(calls).toEqual([]); await expect(manual.setTime(0)).rejects.toThrow("Date shifts require"); await expect(unclocked.setTime(0)).rejects.toThrow("Date shifts require"); }); +test("gameplay fixtures seed a separate guidance choice while preserving player preferences and game saves",async()=>{ + const scripts:{callback:(key:string)=>void;key:string}[]=[]; + const page={addInitScript:async(callback:(key:string)=>void,key:string)=>{scripts.push({callback,key});},route:async()=>{}} as unknown as Page; + const saves=new Map([["familiar.expedition.local.v2","ORIGINAL_GAME_SAVE"]]); + const localStorage={getItem:(key:string)=>saves.get(key)??null,setItem:(key:string,value:string)=>{saves.set(key,value);}}; + await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:false}); + expect(scripts).toHaveLength(1);expect(scripts[0]!.key).toBe(GUIDANCE_KEY); + const apply=()=>runInNewContext(`(${scripts[0]!.callback.toString()})(key)`,{localStorage,key:GUIDANCE_KEY}); + apply();expect(JSON.parse(saves.get(GUIDANCE_KEY)!)).toEqual({version:1,intro:"skip",buttons:false}); + expect(saves.get("familiar.expedition.local.v2")).toBe("ORIGINAL_GAME_SAVE"); + saves.set(GUIDANCE_KEY,JSON.stringify({version:1,intro:null,buttons:true})); + apply();expect(JSON.parse(saves.get(GUIDANCE_KEY)!)).toEqual({version:1,intro:null,buttons:true}); + scripts.length=0;await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:false,guidance:false}); + expect(scripts).toEqual([]); + await seedGameplayGuidance(page);expect(scripts).toHaveLength(1); +}); + test("browser fixtures reject every hosted origin except the existing QA deployment",async()=>{ for(const origin of ["https://unexpected.example","http://familiar-two.vercel.app","https://familiar-two.vercel.app:444","https://familiar-two.vercel.app.evil"]) await expect(prepareBrowser({} as Page,origin)).rejects.toThrow("Browser fixtures require a local server or the existing hosted QA origin"); diff --git a/scripts/browser-fixtures.ts b/scripts/browser-fixtures.ts index 56aab5b..d133a28 100644 --- a/scripts/browser-fixtures.ts +++ b/scripts/browser-fixtures.ts @@ -1,10 +1,11 @@ import assert from "node:assert/strict"; import type { Page } from "@playwright/test"; import type { ShelfView, TodayView } from "../web/src/season/model"; +import { GUIDANCE_KEY } from "../web/src/run/guidance"; export const BROWSER_DAY=20771; const RPC="https://test.rpc.fastnear.com/",ROOT="familiar-game.testnet"; -const accounts=new Set([`alice.${ROOT}`,`bob.${ROOT}`,`harness.${ROOT}`]); +const accounts=new Set([`alice.${ROOT}`,`bob.${ROOT}`,`harness.${ROOT}`,`helper-a.${ROOT}`]); const pets=new Set([`mochi.${ROOT}`,`mochi-harness.${ROOT}`]); /** Public reads only. A mismatched envelope is an unexpected request, never a live fallback. */ @@ -44,10 +45,18 @@ function shiftBrowserDate(time:number) { }); } +/** Gameplay fixtures choose guidance explicitly; pristine introduction tests omit this setup. */ +export async function seedGameplayGuidance(page:Page) { + await page.addInitScript(key=>{ + if(localStorage.getItem(key)===null)localStorage.setItem(key,JSON.stringify({version:1,intro:"skip",buttons:false})); + },GUIDANCE_KEY); +} + /** Date drives the UTC day; native frame/timer clocks must keep driving Phaser. */ -export async function prepareBrowser(page:Page,origin:string|URL,day=BROWSER_DAY,{clock=true}: {clock?:boolean|"manual"}={}) { +export async function prepareBrowser(page:Page,origin:string|URL,day=BROWSER_DAY,{clock=true,guidance=true}: {clock?:boolean|"manual";guidance?:boolean}={}) { const resourceUrl=new URL(origin),local=resourceUrl.origin,unexpected:string[]=[],rpc:string[]=[]; assert(["localhost","127.0.0.1","[::1]"].includes(resourceUrl.hostname)||local==="https://familiar-two.vercel.app","Browser fixtures require a local server or the existing hosted QA origin"); + if(guidance)await seedGameplayGuidance(page); if(clock==="manual")await page.clock.install({time:new Date(day*86_400_000+43_200_000)}); else if(clock)await page.addInitScript(shiftBrowserDate,day*86_400_000+43_200_000); await page.route("**/*",async route=>{ diff --git a/scripts/test-expedition-browser.ts b/scripts/test-expedition-browser.ts index 9ce9303..de659b3 100644 --- a/scripts/test-expedition-browser.ts +++ b/scripts/test-expedition-browser.ts @@ -1,4 +1,4 @@ -import { guide, departCourt } from "./browser-controls"; +import { guide, departCourt, continueStoryExchange } from "./browser-controls"; import { prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import { mkdtemp, writeFile } from "node:fs/promises"; @@ -114,7 +114,7 @@ try{ await departCourt(page); const initial=startCourt({area:"beacon",tool:"rope",banked:[]}),route=solveCourt(initial,["lens","moth"],{dry:true})!;assert(route); const returned=await playRoute(page,route.commands,initial,`${width}`);assert.equal(returned.resolve,3);assert.deepEqual(returned.cargo,["lens","moth"]); - await record(page,`${width}-returned`);await expect(page.locator('[data-action="home-next"]')).toHaveText("Fit the Beacon Lens");await page.locator('[data-action="home-next"]').click();await page.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click(); + await record(page,`${width}-returned`);await expect(page.locator('[data-action="home-next"]')).toHaveText("Fit the Beacon Lens");await page.locator('[data-action="home-next"]').click();await page.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();await continueStoryExchange(page); await page.getByRole("button",{name:"Workbench",exact:true}).click();await page.getByRole("radio",{name:"Moth",exact:true}).check();await expect(page.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","moth");await page.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","moth");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(page,`${width}-lantern-home`); await page.getByRole("button",{name:"Workbench",exact:true}).click();await page.getByText("Light’s origin",{exact:true}).click();await expect(page.getByText("Mochi returned with the wind-moth. 17 choices with the Rope.",{exact:true})).toBeVisible();await expect(page.getByText(/Static illustration of this device’s validated return/)).toBeVisible();await record(page,`${width}-local-origin`);await page.getByRole("button",{name:"Place at the dock",exact:true}).click(); const home=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey);assert(home.home.lit);assert.equal(home.home.lantern.motif,"moth");assert.equal(home.home.lantern.socket,"dock");assert.deepEqual(home.home.banked,["lens","moth"]); @@ -125,6 +125,7 @@ try{ await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); await expect(page.getByRole("heading",{name:"One missing piece."})).toBeVisible(); await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); + await continueStoryExchange(page); await expect(page.locator(".exp-departure h1")).toHaveText("Today’s Tide Run."); await record(page,`${width}-wind-repaired`); assert((await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.signaled,"Wind goal changes the returned harbor"); @@ -160,7 +161,7 @@ try{ const second=await shared.newPage();await fixture(second);await second.goto(`${origin}/outing/?play`);await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","blocked");const owned=await second.evaluate(key=>localStorage.getItem(key),saveKey);await second.getByTestId("expedition-game").focus();await second.keyboard.press("ArrowRight");assert.equal(await second.evaluate(key=>localStorage.getItem(key),saveKey),owned,"second tab cannot overwrite the active branch");await first.close();await second.getByRole("button",{name:"Check this tab again",exact:true}).click();await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await expect(second.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await guide(second,"step:east");await settled(second);assert.deepEqual((await second.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.commands,["step:west","step:east"],"reacquired lease loads the original tab’s latest move");await shared.close(); const storage=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),saving=await storage.newPage();await fixture(saving);await saving.addInitScript(key=>{const original=Storage.prototype.setItem;(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";Storage.prototype.setItem=function(name,value){const mode=(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition;if(mode==="active"&&name===key||mode==="returns"&&name.startsWith("familiar.expedition.returns.v2:"))throw new DOMException("The browser rejected this write.","QuotaExceededError");original.call(this,name,value);};},saveKey); await saving.goto(`${origin}/outing/?play`);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await departCourt(saving);assert.equal(await saving.evaluate(key=>localStorage.getItem(key),saveKey),null,"rejected first save cannot create a phantom expedition");await expect(saving.getByRole("button",{name:"Check device saving again",exact:true})).toBeVisible();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await departCourt(saving);await act(saving,"step:north");await act(saving,"step:south");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="returns";});await act(saving,"return");await expect(saving.getByRole("button",{name:"Retry recording this return",exact:true})).toBeVisible();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.outcome,"returned","failed return write preserves the terminal transcript");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Retry recording this return",exact:true}).click();await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");assert.equal((await saving.evaluate(()=>JSON.parse(localStorage.getItem("familiar.expedition.returns.v2:preview")!))).length,1,"retry records one original return"); - await departCourt(saving);for(const input of solveCourt({area:"beacon",tool:"rope",banked:[]},["lens"],{dry:true})!.commands)await act(saving,input);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");await saving.locator('[data-action="home-next"]').click();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";});await saving.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,false,"failed repair keeps the previously saved dark beacon");await expect(saving.getByRole("dialog")).toBeVisible();await expect(saving.getByTestId("expedition-feedback")).not.toContainText("Mochi lifts the lens into place");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await saving.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,true,"repair success appears only after the retry is durable");await saving.getByRole("button",{name:"Workbench",exact:true}).click();await expect(saving.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","crest");await expect(saving.getByRole("radio",{name:"Moth",exact:true})).toBeDisabled();await saving.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","crest");await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(saving,"validated-crest-preview");await storage.close(); + await departCourt(saving);for(const input of solveCourt({area:"beacon",tool:"rope",banked:[]},["lens"],{dry:true})!.commands)await act(saving,input);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");await saving.locator('[data-action="home-next"]').click();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";});await saving.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,false,"failed repair keeps the previously saved dark beacon");await expect(saving.getByRole("dialog")).toBeVisible();await expect(saving.getByTestId("expedition-feedback")).not.toContainText("Mochi lifts the lens into place");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await saving.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,true,"repair success appears only after the retry is durable");await continueStoryExchange(saving);await saving.getByRole("button",{name:"Workbench",exact:true}).click();await expect(saving.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","crest");await expect(saving.getByRole("radio",{name:"Moth",exact:true})).toBeDisabled();await saving.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","crest");await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(saving,"validated-crest-preview");await storage.close(); // Asset failure is visible and must not silently replace or erase the stored expedition. const failed=await browser.newContext({viewport:{width:390,height:844}}),failure=await failed.newPage();await fixture(failure);await failure.route("**/assets/expedition/runtime/stone-island.webp",route=>route.abort());await failure.goto(`${origin}/outing/?play`);await expect(failure.getByRole("button",{name:"Reload the scene",exact:true})).toBeVisible();await expect(failure.getByRole("alert")).toContainText("artwork did not load");assert.equal(await failure.evaluate(key=>localStorage.getItem(key),saveKey),null,"failed artwork cannot fabricate a new save");await failed.close(); } diff --git a/scripts/test-expedition-harbor-browser.ts b/scripts/test-expedition-harbor-browser.ts index 25b1864..5ee3831 100644 --- a/scripts/test-expedition-harbor-browser.ts +++ b/scripts/test-expedition-harbor-browser.ts @@ -16,7 +16,7 @@ import {dayResult} from "../web/src/run/save"; import {BROWSER_DAY,prepareBrowser} from "./browser-fixtures"; // Actual React controller/provider/panel; all account/RPC ports below are isolated synthetic fixtures. -const id="\0expedition-harbor-fixture.tsx",dir=await mkdtemp(join(tmpdir(),"familiar-expedition-harbor-")); +const id="\0expedition-harbor-fixture.tsx",guidanceId="\0expedition-guidance-fixture.tsx",dir=await mkdtemp(join(tmpdir(),"familiar-expedition-harbor-")); const fixturePublicKey=KeyPair.fromRandom("ed25519").getPublicKey().toString(); let publicViews=0; const captureRoutes=courtFixtures.cases.filter(row=>["beacon-rope-objective","beacon-rope-rescue"].includes(row.id)).map(row=>({id:row.id,start:row.start,commands:row.commands})); @@ -127,12 +127,107 @@ function Probe(){const session=useHarborSession();fixture.port=session;return <> {session.state.review&&

{session.state.review.title}

{session.state.review.description}

{session.state.review.costs.join(' ')}

}} const Game=React.lazy(()=>import('/src/expedition/Game.tsx')); -function GameProbe(){const session=useHarborSession();fixture.port=session;return Opening fixture world

}>}/>
} -function App(){const[open,setOpen]=useState(true);fixture.close=()=>setOpen(false);fixture.reopen=()=>setOpen(true);const game=location.pathname.endsWith('-game');return

Synthetic controller fixture · no real identity or chain

{open?{game?:}:

Controller closed

}
} +function GameProbe({initialRestorationComplete}){const session=useHarborSession();fixture.port=session;return Opening fixture world

}>}/>
} +function App(){const[open,setOpen]=useState(true);fixture.close=()=>setOpen(false);fixture.reopen=()=>setOpen(true);const game=location.pathname.endsWith('-game');return

Synthetic controller fixture · no real identity or chain

{open?{(_,complete)=>game?:}:

Controller closed

}
} createRoot(document.getElementById('root')).render(); `; +const guidanceEntry=` +import '/src/browser-globals.ts'; +import React,{useState} from 'react';import{createRoot}from'react-dom/client'; +import{HarborSessionProvider}from'/src/expedition/harbor-session.tsx'; +const Game=React.lazy(()=>import('/src/expedition/Game.tsx')); +const root='familiar-game.testnet',pub=${JSON.stringify(fixturePublicKey)}; +const fixture=window.__guidanceLifecycle={requests:[],reads:[],sends:[],port:null}; +fixture.binding=name=>({playerId:'fixture-'+name,network:'testnet',nearAccountId:'helper-'+name.toLowerCase()+'.'+root,signerPublicKey:pub,signerBindingId:'synthetic-'+name}); +function connection(name){return {name,adapter:{accountRoot:root,restoreSession(){return new Promise(resolve=>fixture.requests.push({name,finish:resolve}))},async authenticate(){return fixture.binding(name)},async endSession(){},async provisionAccount(){throw Error('must not provision')}},accountExists:async()=>{},client:{root,itemsContract:'items.'+root, + async snapshot(binding){fixture.reads.push(name);return {readAt:'synthetic',binding,checkpointHash:'a'.repeat(64),pets:[{token_id:'mochi.'+root}],items:[],nextItemIndex:null,journey:{revision:1,banked:['lens'],lit:true,signaled:false,lens_claim:'b'.repeat(64),moth_claim:null,credit:'available',workshop_salvage:1,bram_budget:12,shells:0,burned_shells:0,commission_fulfilled:false,craft:null,polish:null,placement:null}}}, + async verifyStack(){},pending(){return null},async send(){fixture.sends.push(name);throw Error('unexpected synthetic signing')},async resumeNative(){throw Error('unexpected resume')},async reconcileNative(){throw Error('unexpected reconcile')},async resolveExpiredNative(){throw Error('unexpected expiry')},async view(){throw Error('unexpected view')}, +}}} +function App(){const[current,setCurrent]=useState(()=>connection('A')),[revealed,setRevealed]=useState(false);fixture.replace=name=>setCurrent(connection(name));fixture.reveal=()=>setRevealed(true);return {(session,complete)=>{fixture.port=session;return Opening lifecycle fixture

}>
}}
} +createRoot(document.getElementById('root')).render(); +`; +async function checkGuidanceLifecycle(browser:import("@playwright/test").Browser,origin:string){ + const guidanceKey="familiar.guidance.keep-wrens-light.v1",saveKey="familiar.expedition.local.v2",bookKey=saveKey+":tide-run.v1"; + const fixture=async(earnedLens=false)=>{ + const context=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),page=await context.newPage(),errors:string[]=[]; + const network=await prepareBrowser(page,origin,BROWSER_DAY,{guidance:false});page.on("pageerror",error=>errors.push(error.message)); + if(earnedLens)await page.addInitScript(key=>localStorage.setItem(key,JSON.stringify({version:2,home:{banked:["lens"],lit:false,signaled:false,lantern:null},active:null,last:null})),saveKey); + await page.goto(origin+"/__guidance");await page.bringToFront(); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:20000}); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held"); + await expect.poll(()=>page.evaluate(()=>(window as any).__guidanceLifecycle.requests.filter((request:any)=>request.name==="A").length)).toBe(2); + await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-complete","false"); + return {page,async close(){network.assertClean();assert.deepEqual(errors,[]);assert.deepEqual(await page.evaluate(()=>(window as any).__guidanceLifecycle.sends),[],"guidance lifecycle sends no account action");publicViews+=network.rpc.length;await context.close();}}; + }; + const settle=async(page:Page,name:string,index=-1,bound=false)=>{ + await expect.poll(()=>page.evaluate(({name,index})=>(window as any).__guidanceLifecycle.requests.filter((request:any)=>request.name===name).length>Math.max(0,index),{name,index})).toBe(true); + await page.evaluate(({name,index,bound})=>{const f=(window as any).__guidanceLifecycle,requests=f.requests.filter((request:any)=>request.name===name),request=requests.at(index);assertFixture(request);request.finish(bound?f.binding(name):null);function assertFixture(value:unknown):asserts value{if(!value)throw Error("Missing deferred restoration");}},{name,index,bound}); + }; + const frames=async(page:Page)=>{await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));}; + const pristine=await fixture(); + try{ + const {page}=pristine,restoration=page.getByTestId("guidance-restoration"),intro=page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true}); + await settle(page,"A",0,true);await frames(page); + await expect(restoration).toHaveAttribute("data-complete","false");assert.deepEqual(await page.evaluate(()=>(window as any).__guidanceLifecycle.reads),[],"StrictMode cleanup fences the first restore before canonical reads"); + await page.evaluate(()=>(window as any).__guidanceLifecycle.replace("B")); + await expect(restoration).toHaveAttribute("data-controller","B");await expect(restoration).toHaveAttribute("data-complete","false"); + await settle(page,"A",1,true);await frames(page); + await expect(restoration).toHaveAttribute("data-complete","false");assert.equal(await page.evaluate(()=>(window as any).__guidanceLifecycle.port.state.binding),null,"old controller completion cannot restore its replacement"); + await settle(page,"B");await expect(restoration).toHaveAttribute("data-complete","true");await frames(page);await expect(intro).toHaveCount(0); + await page.evaluate(()=>(window as any).__guidanceLifecycle.reveal());await expect(intro).toBeVisible();await expect(intro.getByRole("heading")).toBeFocused(); + await page.evaluate(()=>(window as any).__guidanceLifecycle.replace("C")); + await expect(restoration).toHaveAttribute("data-controller","C");await expect(restoration).toHaveAttribute("data-complete","false");await expect(intro).toHaveCount(0); + await settle(page,"C");await expect(restoration).toHaveAttribute("data-complete","true");await frames(page);await expect(intro).toHaveCount(0); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),guidanceKey),null,"cancelling a mismatched introduction changes no preference"); + }finally{await pristine.close();} + const escaped=await fixture(); + try{ + const {page}=escaped;await settle(page,"A",1);await page.evaluate(()=>(window as any).__guidanceLifecycle.reveal()); + const intro=page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true});await expect(intro.getByRole("heading")).toBeFocused(); + const untouched=await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[saveKey,bookKey]);await page.keyboard.press("Escape");await expect(intro).toHaveCount(0); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),guidanceKey),{version:1,intro:"skip",buttons:false},"Escape records the current automatic introduction choice"); + assert.deepEqual(await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[saveKey,bookKey]),untouched,"Escape changes guidance only"); + }finally{await escaped.close();} + const interacted=await fixture(); + try{ + const {page}=interacted;await page.getByRole("button",{name:"Game menu",exact:true}).click();await page.getByRole("button",{name:"Back to Mochi",exact:true}).click(); + await page.evaluate(()=>(window as any).__guidanceLifecycle.replace("B"));await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-controller","B"); + await settle(page,"A",0,true);await settle(page,"A",1,true);await settle(page,"B");await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-complete","true"); + await page.evaluate(()=>(window as any).__guidanceLifecycle.reveal());await frames(page);await expect(page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true})).toHaveCount(0); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),null,"opening and closing a menu does not create progress");assert.equal(await page.evaluate(key=>localStorage.getItem(key),guidanceKey),null,"a prior local interaction suppresses a late introduction without recording Help or Skip"); + }finally{await interacted.close();} + const local=await fixture(); + try{ + const {page}=local;await page.evaluate(()=>(window as any).__guidanceLifecycle.reveal()); + await page.getByRole("button",{name:"Prepare Chapter 1",exact:true}).click();await page.getByRole("button",{name:"Sail with Mochi",exact:true}).click(); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true");const trace=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await page.evaluate(()=>(window as any).__guidanceLifecycle.replace("B"));await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-controller","B"); + await settle(page,"A",0,true);await settle(page,"A",1,true);await settle(page,"B",-1,true); + await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-complete","true"); + await page.getByRole("button",{name:"Pause outing",exact:true}).click();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + await frames(page);await expect(page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true})).toHaveCount(0);await expect(page.getByRole("button",{name:"Resume outing",exact:true})).toBeVisible(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),trace,"restoration and replacement preserve a locally started outing");assert.equal(await page.evaluate(key=>localStorage.getItem(key),guidanceKey),null,"starting local play while restoration waits does not make an introduction choice"); + }finally{await local.close();} + for(const replacement of ["controller","branch"] as const){ + const repair=await fixture(true); + try{ + const {page}=repair;await settle(page,"A",1,true);await page.evaluate(()=>(window as any).__guidanceLifecycle.reveal());await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-complete","true"); + await page.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click();await page.getByRole("dialog").getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click(); + const exchange=page.getByRole("dialog",{name:"Wren’s light",exact:true});await expect(exchange).toContainText("Mochi lifts the lens into place. The beacon finds the bay again."); + const earned=await page.evaluate(key=>localStorage.getItem(key),saveKey); + if(replacement==="controller"){ + await page.evaluate(()=>(window as any).__guidanceLifecycle.replace("B"));await expect(exchange).toHaveCount(0);await settle(page,"B"); + }else{ + await page.evaluate(async()=>{await (window as any).__guidanceLifecycle.port.selectSaved();});await expect(page.getByTestId("guidance-restoration")).toHaveAttribute("data-complete","true");await expect(exchange).toHaveCount(0); + await page.evaluate(()=>(window as any).__guidanceLifecycle.port.selectPreview());await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + } + await frames(page);await expect(exchange).toHaveCount(0);assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),earned,`${replacement} cancellation preserves the earned repair`); + await page.getByRole("button",{name:"Open the tide log",exact:true}).and(page.locator(":visible")).click();const log=page.getByRole("dialog",{name:"Bram’s tide log",exact:true});await expect(log.locator(".tide-memories summary")).toHaveCount(2); + }finally{await repair.close();} + } +} const server=await createServer({configFile:false,root:resolve(import.meta.dir,"../web"),envDir:false,envPrefix:[],cacheDir:join(dir,"vite-cache"),logLevel:"error", - plugins:[{name:"expedition-harbor-fixture",resolveId(source){if(source!=="/__harbor-fixture.tsx")return;return id;},async load(source){if(source===id)return (await transformWithOxc(entry,"harbor-fixture.tsx")).code;},configureServer(server){server.middlewares.use((req,res,next)=>{if(!["/__harbor","/__harbor-game"].includes(req.url??"")){next();return;}res.setHeader("Content-Type","text/html");res.end('
');});}}],server:{host:"127.0.0.1",port:0}}); + plugins:[{name:"expedition-harbor-fixture",resolveId(source){return source==="/__harbor-fixture.tsx"?id:source==="/__guidance-fixture.tsx"?guidanceId:undefined;},async load(source){if(source===id||source===guidanceId)return (await transformWithOxc(source===id?entry:guidanceEntry,"harbor-fixture.tsx")).code;},configureServer(server){server.middlewares.use((req,res,next)=>{if(!["/__harbor","/__harbor-game","/__guidance"].includes(req.url??"")){next();return;}res.setHeader("Content-Type","text/html");res.end('
');});}}],server:{host:"127.0.0.1",port:0}}); await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,""),browser=await chromium.launch({headless:true}); try{ const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage(),external:string[]=[],errors:string[]=[]; @@ -192,5 +287,5 @@ try{ await game.evaluate(async()=>{const f=(window as any).__harbor;f.displayLantern('moth',true);await f.port.refresh();});await expect(game.getByTestId('expedition-world')).toHaveAttribute('data-lantern-motif','moth'); await game.evaluate(async()=>{const f=(window as any).__harbor;f.removeHeldLantern();await f.port.refresh();});await expect(game.getByTestId('expedition-world')).not.toHaveAttribute('data-lantern-motif',/.+/);await expect(game.getByTestId('expedition-world')).not.toHaveAttribute('data-lantern-finish',/.+/);assert.equal(await game.evaluate(()=>(window as any).__harbor.sends.length),1); const geometry=await game.evaluate(()=>({x:scrollX,y:scrollY,scroll:document.documentElement.scrollHeight,height:innerHeight}));assert.equal(geometry.x,0);assert.equal(geometry.y,0);assert(geometry.scroll<=geometry.height+1); - network.assertClean();gameNetwork.assertClean();publicViews+=network.rpc.length+gameNetwork.rpc.length;await gameContext.close();await checkReturnLayouts(browser,origin);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);console.log(JSON.stringify({status:"passed",actualReactController:true,actualGameAndPhaser:true,freshDeviceCanonicalMotifAndItem:true,canonicalAppearance:"Crest/original to Moth/polish; hidden after current holding disappears; no achievement inheritance",rememberedExplicitSelectionReload:true,explicitBramReview:true,busyReviewDismissalFenced:true,workingMemoryDownload:true,twoTabDistinctReturns:"both retained through actual Web Locks",lateOwnerFenced:true,harborLayouts:"fresh, before today’s tide, all three kept, one kept, rescued, longest Tomorrow; six viewports",externalRequests:0,mockedRpcViews:publicViews,chainActions:0,captures:dir,limits:"Synthetic account/RPC ports only; no physical-device, provider-recovery or human-playtest claim."},null,2)); + network.assertClean();gameNetwork.assertClean();publicViews+=network.rpc.length+gameNetwork.rpc.length;await gameContext.close();await checkReturnLayouts(browser,origin);await checkGuidanceLifecycle(browser,origin);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);console.log(JSON.stringify({status:"passed",actualReactController:true,actualGameAndPhaser:true,freshDeviceCanonicalMotifAndItem:true,canonicalAppearance:"Crest/original to Moth/polish; hidden after current holding disappears; no achievement inheritance",rememberedExplicitSelectionReload:true,explicitBramReview:true,busyReviewDismissalFenced:true,workingMemoryDownload:true,twoTabDistinctReturns:"both retained through actual Web Locks",lateOwnerFenced:true,guidanceLifecycle:"StrictMode stale restoration, replacement identities, title handoff, local play while restoration waits, no late introduction, controller/branch exchange cancellation",harborLayouts:"fresh, before today’s tide, all three kept, one kept, rescued, longest Tomorrow; six viewports",externalRequests:0,mockedRpcViews:publicViews,chainActions:0,captures:dir,limits:"Synthetic account/RPC ports only; no physical-device, provider-recovery or human-playtest claim."},null,2)); }finally{await browser.close();await server.close();} diff --git a/scripts/test-expedition-lifecycle-browser.ts b/scripts/test-expedition-lifecycle-browser.ts index 1f0590e..b6f83be 100644 --- a/scripts/test-expedition-lifecycle-browser.ts +++ b/scripts/test-expedition-lifecycle-browser.ts @@ -1,4 +1,5 @@ import { guide, departCourt } from "./browser-controls"; +import { prepareBrowser } from "./browser-fixtures"; import assert from 'node:assert/strict'; import {mkdir,mkdtemp,writeFile} from 'node:fs/promises'; import {join,resolve} from 'node:path'; @@ -18,7 +19,8 @@ const f=window.__audit={held:[],hold:false};const request=window.requestAnimatio function App(){const[open,setOpen]=useState(true);f.close=()=>setOpen(false);f.reopen=()=>setOpen(true);return open?:

Game unmounted; no new input accepted.

}createRoot(document.getElementById('root')).render();`; const server=await createServer({configFile:false,root:project+'/web',envDir:false,envPrefix:[],cacheDir:join(scratch,'vite-cache'),logLevel:'error',server:{host:'127.0.0.1',port:0,hmr:false,watch:null},plugins:[{name:'qa-fixture',resolveId(source){if(source==='/__audit.tsx')return id},async load(source){if(source===id)return(await transformWithOxc(entry,'frontend-audit.tsx')).code},configureServer(server){server.middlewares.use((req,res,next)=>{if(req.url!=='/__audit'){next();return}res.setHeader('Content-Type','text/html');res.end('
')})}}]}); await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,''),browser=await chromium.launch({headless:true}),results:any[]=[]; -async function open(path='/outing/?play',size={width:390,height:844},touch=false){const context=await browser.newContext({viewport:size,reducedMotion:'reduce',hasTouch:touch,isMobile:touch,deviceScaleFactor:touch?2:1}),page=await context.newPage();await page.route('**/*',route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith('/api/')?route.continue():route.abort());await page.goto(origin+path);await expect(page.getByTestId('expedition-world')).toHaveAttribute('data-ready','true');await expect(page.getByTestId('expedition-game')).toHaveAttribute('data-lease','held');await page.evaluate(()=>document.fonts.ready);return{context,page}} +const networks:Awaited>[]=[]; +async function open(path='/outing/?play',size={width:390,height:844},touch=false){const context=await browser.newContext({viewport:size,reducedMotion:'reduce',hasTouch:touch,isMobile:touch,deviceScaleFactor:touch?2:1}),page=await context.newPage();networks.push(await prepareBrowser(page,origin));await page.goto(origin+path);await expect(page.getByTestId('expedition-world')).toHaveAttribute('data-ready','true');await expect(page.getByTestId('expedition-game')).toHaveAttribute('data-lease','held');await page.evaluate(()=>document.fonts.ready);return{context,page}} async function raw(page:Page){return await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),key)} async function homeGeometry(page:Page){return page.locator('button:visible,a:visible').evaluateAll(nodes=>nodes.map(node=>{const r=node.getBoundingClientRect(),points=[[r.x+r.width/2,r.y+r.height/2],[r.x+8,r.y+8],[r.right-8,r.y+8],[r.x+8,r.bottom-8],[r.right-8,r.bottom-8],[r.x+r.width/2,r.y+2],[r.x+r.width/2,r.bottom-2],[r.x+2,r.y+r.height/2],[r.right-2,r.y+r.height/2]];return{label:node.getAttribute('aria-label')??node.textContent,rect:r.toJSON(),hits:points.map(([x,y])=>({x,y,hit:node.contains(document.elementFromPoint(x!,y!))}))}}))} async function homeBounds(page:Page){const controls=await homeGeometry(page),viewport=page.viewportSize()!;for(const control of controls){assert(control.rect.x>=0&&control.rect.y>=0&&control.rect.right<=viewport.width&&control.rect.bottom<=viewport.height&&control.rect.width>=44&&control.rect.height>=44,`Home control fits44px: ${control.label}`);assert(control.hits.every(p=>p.hit),`Home control not obscured at any of9points: ${control.label}`)}return controls} @@ -50,4 +52,4 @@ try{ await context.close()} const transcript=out+(keyboardOnly?'/keyboard-':landscapeOnly?'/landscape-':'/frontend-')+phase+'-probe.json';await writeFile(transcript,JSON.stringify({phase,syntheticOnly:true,externalMutations:0,results},null,2)+'\n');console.log(JSON.stringify({phase,captures:out,cases:results.map(result=>({case:result.case,index:result.index,prefix:result.prefix,variant:result.variant})),transcripts:transcript},null,2)); if(phase==='after'&&!keyboardOnly&&!landscapeOnly){assert.deepEqual(results[0].after,results[0].before,'An unmounted Game may not accept its queued decision');assert.equal(results[1].active.label,'Game menu','Closing a nested panel restores the original opener')} -}finally{await browser.close();await server.close()} +}finally{try{for(const network of networks)network.assertClean();}finally{await browser.close();await server.close()}} diff --git a/scripts/test-expedition-touch-browser.ts b/scripts/test-expedition-touch-browser.ts index 7b9a675..0b744f7 100644 --- a/scripts/test-expedition-touch-browser.ts +++ b/scripts/test-expedition-touch-browser.ts @@ -1,4 +1,5 @@ import { guide, worldAction, buttonControls, departCourt } from "./browser-controls"; +import { prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import {mkdtemp,mkdir,writeFile} from "node:fs/promises"; import {join,resolve} from "node:path"; @@ -17,13 +18,14 @@ const server=await createServer({root:resolve(import.meta.dir,"../web"),cacheDir await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,""); const browser=await chromium.launch({headless:true}),key="familiar.expedition.local.v2"; const results:Record[]=[]; +const networks:Awaited>[]=[]; const tideFixtureDay=20771,tideFixtureCard=cardForDay(tideFixtureDay),tideFixtureRoute=solve(tideFixtureCard.tool,tideFixtureCard.asks,tideFixtureCard.best); assert(tideFixtureRoute?.at(-1)==="return","the tide fixture ends with a real dock return"); const tideFixtureRun=replayRun(tideFixtureCard.tool,tideFixtureRoute.slice(0,-1)); assert(tideFixtureRun&&tideFixtureRun.state.outcome==="active"&&tideFixtureRun.state.resolve<3,"the active tide fixture has taken its one splash"); async function state(page:Page){return page.evaluate(key=>{const raw=localStorage.getItem(key);return raw?JSON.parse(raw).active?.state??null:null;},key);} async function touch(cdp:CDPSession,type:"touchStart"|"touchMove"|"touchEnd"|"touchCancel",point?:{x:number;y:number}){await cdp.send("Input.dispatchTouchEvent",{type,touchPoints:point?[{id:1,x:point.x,y:point.y,radiusX:2,radiusY:2,force:1}]:[]});} -async function open(tide=false,freshTide=false){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();await page.route("**/*",route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith("/api/")?route.continue():route.abort());if(tide)await page.addInitScript(({key,day,state})=>{ +async function open(tide=false,freshTide=false){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();networks.push(await prepareBrowser(page,origin));if(tide)await page.addInitScript(({key,day,state})=>{ localStorage.setItem(key,JSON.stringify({version:2,home:{banked:["lens"],lit:true,signaled:false,lantern:null},last:null,active:{context:{authority:"local-preview",banked:[],lit:true,signaled:false},state,season:true}})); localStorage.setItem("familiar.tide.pending.v1:preview",JSON.stringify({day,late:false})); },{key,day:tideFixtureDay,state:freshTide?replayRun(tideFixtureCard.tool,[])!.state:tideFixtureRun!.state});await page.goto(origin+"/outing/?play");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");return {context,page,cdp:await context.newCDPSession(page)};} @@ -206,4 +208,4 @@ try{ assert.equal((results[2]!.after as {turn:number}).turn,1,"A qualifying swipe is one movement decision, without a destination tap"); assert.deepEqual((results[2]!.after as {commands:string[]}).commands,["step:west"]); assert.equal((results[3]!.after as {turn:number}).turn,0,"Press and release must target the same platform even below the drag threshold"); -}finally{await browser.close();await server.close();} +}finally{try{for(const network of networks)network.assertClean();}finally{await browser.close();await server.close();}} diff --git a/scripts/test-records-browser.ts b/scripts/test-records-browser.ts index 6982d6a..3ca8a3b 100644 --- a/scripts/test-records-browser.ts +++ b/scripts/test-records-browser.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { seedGameplayGuidance } from "./browser-fixtures"; import {mkdtemp} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join,resolve} from "node:path"; @@ -22,8 +23,8 @@ const connection={adapter:{accountRoot:root,async restoreSession(){return locati async snapshot(binding){return structuredClone({readAt:'synthetic',binding,journey,checkpointHash:'a'.repeat(64),pets,items:[],nextItemIndex:null})}, async verifyStack(){},pending(){return null},async send(){throw Error('no sends')},async resumeNative(){throw Error('no')},async reconcileNative(){return 'checked'},async resolveExpiredNative(){return 'not proven'},async view(){throw Error('no view')}}}; const Game=React.lazy(()=>import('/src/expedition/Game.tsx')); -function GameProbe(){const session=useHarborSession();return Opening

}>}/>
} -createRoot(document.getElementById('root')).render(); +function GameProbe({initialRestorationComplete}){const session=useHarborSession();return Opening

}>}/>
} +createRoot(document.getElementById('root')).render({(_,complete)=>}); `; const encode=(v:unknown)=>[...new TextEncoder().encode(JSON.stringify(v))]; const full=(public_key:string,nonce:number)=>({access_key:{nonce,permission:"FullAccess"},public_key}); @@ -53,6 +54,7 @@ async function serve(records:boolean) { await server.listen();return {server,origin:server.resolvedUrls!.local[0]!.replace(/\/$/,"")}; } async function openAccount(page:Page,url:string,rpc:{count:number;fail?:boolean}) { + await seedGameplayGuidance(page); await page.route(RPC,async route=>{rpc.count++;const body=JSON.parse(route.request().postData()!);assert.equal(body.params.finality,"final"); await route.fulfill(rpc.fail?{status:502,body:"bad gateway"}:{contentType:"application/json",body:JSON.stringify({jsonrpc:"2.0",id:body.id,...answer(body.params) as object})});}); await page.goto(url);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:20000}); @@ -61,7 +63,7 @@ async function openAccount(page:Page,url:string,rpc:{count:number;fail?:boolean} const browser=await chromium.launch({headless:true}),on=await serve(true),off=await serve(false); try { // Let each dev server finish its first dependency optimisation before any checked page loads. - for(const origin of [on.origin,off.origin]){const warm=await browser.newPage();await warm.goto(origin+"/__records?signedout");await warm.getByTestId("expedition-world").waitFor({timeout:30000}).catch(()=>{});await warm.waitForTimeout(1500);await warm.close();} + for(const origin of [on.origin,off.origin]){const warm=await browser.newPage();await seedGameplayGuidance(warm);await warm.goto(origin+"/__records?signedout");await warm.getByTestId("expedition-world").waitFor({timeout:30000}).catch(()=>{});await warm.waitForTimeout(1500);await warm.close();} for(const [width,height] of [[390,844],[1440,900]] as const){ const page=await browser.newPage({viewport:{width,height}}),errors:string[]=[],external:string[]=[],rpc={count:0}; page.on("pageerror",e=>errors.push(e.message));page.on("request",r=>{const u=r.url();if(!u.startsWith(on.origin)&&!u.startsWith(RPC)&&!u.startsWith("blob:")&&!u.startsWith("data:"))external.push(u);}); diff --git a/scripts/test-tide-run-browser.ts b/scripts/test-tide-run-browser.ts index fb79355..11c4e90 100644 --- a/scripts/test-tide-run-browser.ts +++ b/scripts/test-tide-run-browser.ts @@ -7,10 +7,11 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { chromium, webkit, expect, type Locator, type Page } from "@playwright/test"; import { createServer } from "vite"; -import { VALUE, applyMove, replayTide, startTide, type Move, type TideStart } from "../web/src/run/engine"; +import { VALUE, applyMove, legalMoves, replayTide, startTide, stepDestination, type Move, type TideStart, type TideState } from "../web/src/run/engine"; import { cautiousMove } from "../web/src/run/bot"; -import { storyStart } from "../web/src/run/story"; +import { CHAPTERS, storyStart } from "../web/src/run/story"; import { dayLabel } from "../web/src/tide/cards"; +import { GUIDANCE_KEY } from "../web/src/run/guidance"; const KEY: Record = { north: "ArrowUp", south: "ArrowDown", west: "ArrowLeft", east: "ArrowRight", wait: "Space", home: "r" }; /** The cautious bot's route. In a story tide it wants the chapter's prize above everything. */ @@ -123,12 +124,318 @@ async function guidanceOverflow(page:Page) { assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),saved,"revealing all guidance preserves the exact outing trace"); await reading.evaluate(node=>{node.scrollTop=0;}); } + +async function storyComposition(page:Page) { + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + await expect.poll(()=>page.getByTestId("expedition-world").evaluate(node=>Boolean(JSON.parse(node.getAttribute("data-harbor-anchors")??"{}").story))).toBe(true); + const geometry=await page.evaluate(()=>{ + const panel=document.querySelector(".exp-story-panel")!,rect=panel.getBoundingClientRect(); + const story=JSON.parse(document.querySelector('[data-testid="expedition-world"]')!.getAttribute("data-harbor-anchors")!).story; + return{panel:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},story,width:innerWidth,height:innerHeight}; + }); + assert(geometry.story,"staged art reports actual scene bounds"); + for(const name of ["bram","mochi","lanternRoom",...(geometry.story.keeper?["keeper"]:[])]) { + const art=geometry.story[name];assert(art&&art.width>0&&art.height>0,`${name} is visible in the held composition`); + assert(art.x>=0&&art.y>=0&&art.x+art.width<=geometry.width+.5&&art.y+art.height<=geometry.height+.5,`${name} remains inside the viewport`); + assert(art.y+art.height<=geometry.panel.y+.5,`${name} stays unobscured above the parchment`); + } +} + +async function exposedTideTargets(page:Page,state:TideState) { + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + const destinations=legalMoves(state).flatMap(move=>{const position=stepDestination(state,move);return position?[position]:[];}); + const geometry=await page.getByTestId("tide-world").evaluate((node,destinations)=>{ + const tiles=JSON.parse(node.getAttribute("data-tiles")!),actions=JSON.parse(node.getAttribute("data-actions")!),actor=JSON.parse(node.getAttribute("data-actor")!); + const active=[...tiles.filter((tile:any)=>destinations.some(position=>position.x===tile.position.x&&position.y===tile.position.y)),...actions]; + return{actor,actions:actions.map((action:any)=>action.action),active:active.map((target:any)=>({...target,exposed:[[0,0],[-.45,-.45],[.45,-.45],[-.45,.45],[.45,.45]].every(([x,y])=>document.elementFromPoint(target.x+x!*target.width,target.y+y!*target.height)?.tagName==="CANVAS")})),width:innerWidth,height:innerHeight}; + },destinations); + assert(geometry.actions.includes("wait"),"labelled Wait remains exposed"); + if(legalMoves(state).includes("home")&&state.moves.length)assert(geometry.actions.includes("home"),"Finish remains exposed at the dock"); + for(const[index,target]of geometry.active.entries()) { + assert(target.width>=44&&target.height>=44,"every active world target retains a 44px hit area"); + assert(target.exposed&&target.x-target.width/2>=0&&target.x+target.width/2<=geometry.width&&target.y-target.height/2>=0&&target.y+target.height/2<=geometry.height,"active hit areas fit and remain uncovered with native controls open"); + assert(Math.abs(target.x-geometry.actor.x)>=(target.width+geometry.actor.width)/2||Math.abs(target.y-geometry.actor.y)>=(target.height+geometry.actor.height)/2,"Mochi's Phaser exclusion bounds leave every active target usable"); + for(const other of geometry.active.slice(index+1))assert(Math.abs(target.x-other.x)>=(target.width+other.width)/2||Math.abs(target.y-other.y)>=(target.height+other.height)/2,"legal destinations, Wait and Finish do not overlap"); + } +} + +async function destinationEdgeTaps(browser:import("@playwright/test").Browser,origin:URL) { + const page=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}); + const network=await prepareBrowser(page,origin,BROWSER_DAY); + try { + await page.goto(new URL("/outing/?play",origin).href); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await sailStory(page); + const run=page.getByTestId("tide-run"),world=page.getByTestId("tide-world"); + await expect(world).toHaveAttribute("data-ready","true");await buttonControls(page,true); + await expect.poll(()=>page.getByRole("region",{name:"Outing guidance",exact:true}).evaluate(node=>{ + const reading=node.getBoundingClientRect(),tray=node.closest(".passage-tray")!.getBoundingClientRect(); + const controls=node.closest(".tide-controls")!.querySelector(".exp-button-controls")!.getBoundingClientRect(); + return reading.top>=tray.top&&reading.bottom<=controls.top; + })).toBe(true); + await exposedTideTargets(page,startTide(storyStart("lens"))); + await freeActorTaps(page,"open controls before destination-edge taps"); + let state=startTide(storyStart("lens")); + const accept=async(move:Move,act:()=>Promise)=>{ + state=applyMove(state,move)!.after; + await act();await expect(run).toHaveAttribute("data-beat",String(state.beat));await expect(run).toHaveAttribute("data-busy","false"); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),state.moves,"an edge tap accepts exactly its destination move"); + }; + const directions=["north","west","east"] as const,edges=[[0,-1],[-1,0],[1,0],[0,1]] as const; + for(const move of directions)for(const [index,[dx,dy]] of edges.entries()) { + await exposedTideTargets(page,state); + const to=stepDestination(state,move)!; + const tile=await world.evaluate((node,to)=>{ + const tiles=JSON.parse(node.getAttribute("data-tiles")!); + return tiles.find((tile:any)=>tile.position.x===to.x&&tile.position.y===to.y) as {x:number;y:number;width:number;height:number}; + },to); + await accept(move,()=>page.touchscreen.tap(tile.x+dx*(tile.width/2-1),tile.y+dy*(tile.height/2-1))); + if(move!=="east"||index!==edges.length-1)await accept(move==="north"?"south":move==="west"?"east":"west",()=>guide(page,move==="north"?"south":move==="west"?"east":"west")); + } + await freeActorTaps(page,"open controls after destination-edge taps"); + }finally{network.assertClean();await page.close();} +} + +async function persistentTeaching(browser:import("@playwright/test").Browser,origin:URL) { + const page=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}); + const network=await prepareBrowser(page,origin,BROWSER_DAY); + await page.addInitScript(key=>localStorage.setItem(key,JSON.stringify({version:1,intro:"help",buttons:false})),GUIDANCE_KEY); + try { + await page.goto(new URL("/outing/?play",origin).href); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await sailStory(page); + const run=page.getByTestId("tide-run"),feedback=page.getByTestId("tide-feedback"); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + let beat=0; + const take=async(move:Move)=>{await guide(page,move);await expect(run).toHaveAttribute("data-beat",String(++beat));await expect(run).toHaveAttribute("data-busy","false");}; + for(const move of ["wait","north","south"] as const)await take(move); + const bridge="That wave moved the bridge to the left lane. Cross the channel there."; + await expect(feedback).toHaveText(bridge);await take("wait");await expect(feedback).toHaveText(bridge); + await page.getByRole("button",{name:"Dismiss cue",exact:true}).click();await take("wait"); + await expect(feedback).not.toHaveText(bridge); + // Start the actual authored trace afresh, so pickup and splash occur in the running component. + await page.evaluate(key=>localStorage.removeItem(key),bookKey);await page.reload(); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await sailStory(page); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true");beat=0; + for(const move of zeroLens.slice(0,7))await take(move); + const carried="Mochi has the Beacon Lens. Bring it to the center dock before taking more risks."; + await expect(feedback).toHaveText(carried);await take("wait");await expect(feedback).toHaveText(carried); + await take("east"); + await expect(feedback).toContainText("Splashed.");await expect(feedback).not.toContainText("Mochi has the Beacon Lens"); + await expect(page.getByTestId("tide-prize-status")).toHaveCount(0); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),[...zeroLens.slice(0,7),"wait","east"]); + }finally{network.assertClean();await page.close();} +} + +async function freeActorTaps(page:Page,label:string) { + const run=page.getByTestId("tide-run"),world=page.getByTestId("tide-world"); + await expect(run).toHaveAttribute("data-busy","false"); + await expect(world).toHaveAttribute("data-actor",/^\{/); + const actor=JSON.parse((await world.getAttribute("data-actor"))!) as {x:number;y:number;width:number;height:number}; + const before=await page.evaluate(key=>localStorage.getItem(key),bookKey),beat=await run.getAttribute("data-beat"); + for(const[name,y]of [["body",actor.y],["head",actor.y-actor.height*.35]] as const) { + const target={x:actor.x,y}; + assert.equal(await page.evaluate(({x,y})=>document.elementFromPoint(x,y)?.tagName,target),"CANVAS",`${label}: Mochi’s ${name} is exposed`); + await page.touchscreen.tap(target.x,target.y); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + await expect(run).toHaveAttribute("data-beat",beat!); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),before,`${label}: tapping Mochi’s ${name} spends zero moves`); + } +} + +async function earnedExchange(page:Page,kind:"lens"|"vane"|"moth",engine:string) { + const lines=kind==="lens"?["Mochi lifts the lens into place. The beacon finds the bay again.","The Tidekeeper goes still beneath the light.",...CHAPTERS.lens.after] + :kind==="vane"?["The vane catches the breeze.",...CHAPTERS.vane.after] + :["The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.",...CHAPTERS.moth.after]; + const dialog=page.getByRole("dialog").filter({has:page.getByRole("button",{name:/^Continue(?: with Mochi)?$/,exact:true})}); + await expect(dialog).toBeVisible(); + const persisted=await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[bookKey,"familiar.expedition.local.v2"]); + for(const[index,line]of lines.entries()) { + await expect(dialog).toContainText(line); + await expect(dialog.getByRole("heading")).toBeFocused(); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-story-beat",String(index)); + await storyComposition(page); + if(kind==="lens"&&index===1)await expect.poll(()=>page.getByTestId("expedition-world").evaluate(node=>Boolean(JSON.parse(node.getAttribute("data-harbor-anchors")!).story.keeper))).toBe(true); + await page.screenshot({path:join(cacheDir,`${engine}-${kind}-exchange-${index}-390x844.png`)}); + await dialog.getByRole("button",{name:index===lines.length-1?"Continue with Mochi":"Continue",exact:true}).click(); + } + assert.deepEqual(await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[bookKey,"familiar.expedition.local.v2"]),persisted,"reading earned exchanges spends no moves or extra saves"); +} + +async function milestoneFocus(page:Page) { + const opener=page.getByRole("button",{name:"Open the tide log",exact:true}).and(page.locator(":visible")); + await opener.focus();await page.keyboard.press("Enter"); + const log=page.getByRole("dialog",{name:"Bram’s tide log",exact:true}); + const summaries=log.locator(".tide-memories summary"),close=log.getByRole("button",{name:"Close panel",exact:true}); + await expect(summaries).toHaveCount(2); + await expect(log).not.toContainText("Chart of Mochi’s route"); + await summaries.first().focus();await page.keyboard.press("Enter"); + await expect(summaries.first().locator("..")).toHaveAttribute("open",""); + await page.keyboard.press("Space");await expect(summaries.first().locator("..")).not.toHaveAttribute("open",""); + await summaries.last().focus();await page.keyboard.press("Tab");await expect(close).toBeFocused(); + await page.keyboard.press("Shift+Tab");await expect(summaries.last()).toBeFocused(); + await page.keyboard.press("Escape");await expect(opener).toBeFocused(); + const preferences=await page.evaluate(key=>localStorage.getItem(key),GUIDANCE_KEY); + const progress=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await page.getByRole("button",{name:"Game menu",exact:true}).click(); + await page.getByRole("button",{name:"Read introduction",exact:true}).click(); + const replay=page.getByRole("dialog",{name:"How it began",exact:true}); + await expect(replay).toContainText("The storm had taken the beacon’s lens. Mochi was ready to help."); + await expect(replay.getByRole("button",{name:"Help Mochi",exact:true})).toHaveCount(0); + await expect(replay).not.toContainText("Bring the Beacon Lens home from the left shell."); + await replay.getByRole("button",{name:"Back to Mochi",exact:true}).click(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),GUIDANCE_KEY),preferences,"manual replay does not change guidance preferences"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),progress,"manual replay preserves the original trace"); +} + +async function skipIntroduction(browser:import("@playwright/test").Browser,origin:URL) { + const page=await browser.newPage({viewport:{width:390,height:844},reducedMotion:"reduce"}); + const network=await prepareBrowser(page,origin,BROWSER_DAY,{guidance:false}); + try { + await page.goto(new URL("/outing/?play",origin).href); + const introduction=page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true});await expect(introduction).toBeVisible(); + const untouched=await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[bookKey,"familiar.expedition.local.v2"]); + await introduction.getByRole("button",{name:"Skip introduction",exact:true}).click(); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),GUIDANCE_KEY),{version:1,intro:"skip",buttons:false}); + assert.deepEqual(await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[bookKey,"familiar.expedition.local.v2"]),untouched,"Skip changes guidance alone"); + await page.reload();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + await expect(introduction).toHaveCount(0); + await page.getByRole("button",{name:"Game menu",exact:true}).click(); + await page.getByRole("button",{name:"Guidance: off",exact:true}).click(); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),GUIDANCE_KEY),{version:1,intro:"help",buttons:false}); + await page.getByRole("button",{name:"Guidance: on",exact:true}).click(); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),GUIDANCE_KEY),{version:1,intro:"skip",buttons:false}); + assert.deepEqual(await page.evaluate(keys=>keys.map(key=>localStorage.getItem(key)),[bookKey,"familiar.expedition.local.v2"]),untouched,"changing guidance spends no moves"); + }finally{network.assertClean();await page.close();} +} + +async function preferenceWriteFailure(browser:import("@playwright/test").Browser,origin:URL) { + const page=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}); + const network=await prepareBrowser(page,origin,BROWSER_DAY,{guidance:false}),errors:string[]=[]; + page.on("pageerror",error=>errors.push(error.message)); + await page.addInitScript(key=>{ + const write=Storage.prototype.setItem; + Storage.prototype.setItem=function(name,value){if(name===key)throw new DOMException("Guidance storage is blocked","QuotaExceededError");return write.call(this,name,value);}; + },GUIDANCE_KEY); + try { + await page.goto(new URL("/outing/?play",origin).href); + const intro=page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true});await expect(intro).toBeVisible(); + await intro.getByRole("button",{name:"Use buttons",exact:true}).click(); + await expect(intro).toContainText("Button controls will be open when you sail."); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),GUIDANCE_KEY),null,"failed preference writes preserve the original absence"); + await intro.getByRole("button",{name:"Help Mochi",exact:true}).click(); + await expect(page.getByRole("heading",{name:"Chapter 1: First light",exact:true})).toBeVisible(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),null,"Help still opens preparation without departing"); + await expect(page.locator(".exp-save-problem")).toHaveCount(0); + await page.getByRole("button",{name:"Sail with Mochi",exact:true}).click(); + const run=page.getByTestId("tide-run");await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + await expect(run).toHaveAttribute("data-buttons-open","true"); + await expect(page.getByTestId("tide-feedback")).toHaveText("Swipe on the board, or tap a glowing neighboring stone. Mochi moves one step at a time."); + const trace=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await buttonControls(page,false);await expect(run).toHaveAttribute("data-buttons-open","false"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),trace,"a failed preference write while closing controls never changes the outing"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),GUIDANCE_KEY),null); + await guide(page,"wait");await expect(run).toHaveAttribute("data-beat","1");await expect(run).toHaveAttribute("data-busy","false"); + await expect(page.getByTestId("tide-feedback")).toHaveText("Every step or wait advances the water by one move. Reading and menus do not."); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),["wait"],"play accepts a real saved decision despite blocked preference storage"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),GUIDANCE_KEY),null);assert.deepEqual(errors,[]); + }finally{network.assertClean();await page.close();} +} + +async function guidedJourney(browser:import("@playwright/test").Browser,engine:typeof chromium,origin:URL,input:"buttons"|"touch") { + const page=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}); + const network=await prepareBrowser(page,origin,BROWSER_DAY,{guidance:false}); + try { + await page.goto(new URL("/outing/?play",origin).href); + const intro=page.getByRole("dialog",{name:"Keep Wren’s Light",exact:true}); + await expect(intro.getByRole("heading")).toBeFocused(); + await storyComposition(page); + await expect(intro).toContainText("You guide Mochi as a volunteer harbor helper."); + await readable(intro.locator(".exp-story-objective")); + if(input==="buttons") { + await intro.getByRole("button",{name:"Use buttons",exact:true}).click(); + await expect(intro).toContainText("Button controls will be open when you sail."); + await readable(intro.locator(".exp-story-objective")); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),GUIDANCE_KEY),{version:1,intro:null,buttons:true}); + await page.goto(new URL("/outing/",origin).href); + await expect(page.locator('[data-el="begin"]')).toHaveText("Begin"); + await page.locator('[data-el="begin"]').click();await page.locator('[data-plank="new"]').click(); + await expect(intro).toBeVisible(); + } + await page.screenshot({path:join(cacheDir,`${engine.name()}-${input}-prologue-390x844.png`)}); + await intro.getByRole("button",{name:"Help Mochi",exact:true}).click(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),null,"Help opens preparation without departing"); + await page.getByRole("button",{name:"Sail with Mochi",exact:true}).click(); + const run=page.getByTestId("tide-run"),world=page.getByTestId("tide-world"); + await expect(world).toHaveAttribute("data-ready","true"); + await exposedTideTargets(page,startTide(storyStart("lens"))); + await expect(page.getByTestId("tide-feedback")).toHaveText("Swipe on the board, or tap a glowing neighboring stone. Mochi moves one step at a time."); + const original=await page.evaluate(key=>localStorage.getItem(key),bookKey); + const tileAt=async(x:number,y:number)=>{ + const tiles=JSON.parse((await world.getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[]; + const tile=tiles.find(tile=>tile.position.x===x&&tile.position.y===y);assert(tile);return tile; + }; + await freeActorTaps(page,`${engine.name()} ${input} initial`); + if(input==="touch") { + const distant=await tileAt(2,4);await page.touchscreen.tap(distant.x,distant.y); + await expect(page.getByTestId("tide-feedback")).toHaveText("Choose a glowing neighboring stone. Mochi moves one step at a time."); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),original,"distant feedback spends zero moves"); + } + await page.evaluate(key=>{ + const write=Storage.prototype.setItem; + Storage.prototype.setItem=function(name,value){if(name===key){Storage.prototype.setItem=write;throw new DOMException("Blocked fixture save","QuotaExceededError");}return write.call(this,name,value);}; + },bookKey); + await guide(page,"wait"); + await expect(page.getByTestId("tide-feedback")).toHaveText("This move could not be saved. Try it again when this browser can save."); + await expect(run).toHaveAttribute("data-beat","0"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),original,"rejected saves do not observe a lesson or spend a move"); + const cdp=engine===chromium&&input==="touch"?await page.context().newCDPSession(page):null; + for(const[index,move]of zeroLens.entries()) { + await expect(run).toHaveAttribute("data-busy","false"); + if(input==="buttons")await page.locator(`[data-move="${move}"]`).click(); + else if(cdp) { + const from=index===0?JSON.parse((await world.getAttribute("data-actor"))!) as {x:number;y:number}:await tileAt(1,2),dx=move==="west"?-60:move==="east"?60:0,dy=move==="north"?-60:move==="south"?60:0; + await cdp.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{id:1,x:from.x,y:from.y}]}); + await cdp.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{id:1,x:from.x+dx,y:from.y+dy}]}); + await cdp.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[]}); + }else { + const after=applyMove(replayTide(storyStart("lens"),zeroLens.slice(0,index))!,move)!.after; + const target=await tileAt(after.position.x,after.position.y);await page.touchscreen.tap(target.x,target.y); + } + await expect(run).toHaveAttribute("data-beat",String(index+1)); + await expect(run).toHaveAttribute("data-busy","false"); + if(index===0)await expect(page.getByTestId("tide-feedback")).toHaveText("Every step or wait advances the water by one move. Reading and menus do not."); + if(index===1)await expect(page.getByTestId("tide-feedback")).toHaveText("The numbers show moves until the next wave. Mochi moves first, then the wave lands."); + assert.deepEqual(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),zeroLens.slice(0,index+1)); + const settled=replayTide(storyStart("lens"),zeroLens.slice(0,index+1))!; + if(settled.pack.includes("lens"))await exposedTideTargets(page,settled); + } + const decision=page.getByTestId("tide-lens-decision");await expect(decision).toBeVisible(); + const banked=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await run.focus();await page.keyboard.press("Space"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),banked,"lens decision pauses commands"); + await decision.getByRole("button",{name:"Keep gathering",exact:true}).click(); + await expect(run).toBeFocused();assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),banked); + await exposedTideTargets(page,zeroLensState); + await buttonControls(page,true);await exposedTideTargets(page,zeroLensState); + await freeActorTaps(page,`${engine.name()} ${input} lens banked with buttons open`); + await page.getByTestId("tide-finish-return").click(); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + assert.equal(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active,bookKey),null); + const home=await page.evaluate(()=>JSON.parse(localStorage.getItem("familiar.expedition.local.v2")!).home); + assert.deepEqual(home.banked,["lens"]);assert.equal(home.lit,false); + return zeroLens; + }finally{network.assertClean();await page.close();} +} try { await server.listen(); const origin = new URL(server.resolvedUrls!.local[0]!); for(const engine of [chromium,webkit]) { const browser = await engine.launch(); try { + await destinationEdgeTaps(browser,origin); + await persistentTeaching(browser,origin); + await preferenceWriteFailure(browser,origin); + await skipIntroduction(browser,origin); + assert.deepEqual(await guidedJourney(browser,engine,origin,"touch"),await guidedJourney(browser,engine,origin,"buttons"),"guided gestures and native buttons accept the same canonical decisions"); const probe=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,reducedMotion:"reduce"}); const probeNetwork=await prepareBrowser(probe,origin,BROWSER_DAY); await probe.goto(new URL("/outing/?play",origin).href);await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); @@ -139,6 +446,9 @@ try { await probe.mouse.up();await probe.keyboard.press("Escape");await expect(probeRun).toBeFocused();await worldAction(probe,"wait",true); await expect(probeRun).toHaveAttribute("data-beat","1"); assert.deepEqual(await probe.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),["wait"],"a release while the guide is open cannot block the next native touch"); + await buttonControls(probe);await probe.locator('[data-move="wait"]').click(); + await expect(probeRun).toHaveAttribute("data-beat","2");await buttonControls(probe,false); + assert.deepEqual(await probe.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),["wait","wait"],"labelled world Wait and native Wait each spend exactly one move"); for(const failFiling of [false,true]){ await probe.evaluate(()=>localStorage.clear());await probe.reload();await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await sailStory(probe); await expect(probe.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); @@ -158,7 +468,7 @@ try { await readable(probe.getByTestId("tide-prize-status")); await readable(probe.getByTestId("tide-finish-return")); await guidanceOverflow(probe); - await buttonControls(probe);await readable(probe.locator(".exp-button-controls-body"));await buttonControls(probe,false); + await buttonControls(probe);await readable(probe.locator(".exp-button-controls-body"));await exposedTideTargets(probe,zeroLensState);await buttonControls(probe,false); await probe.screenshot({path:join(cacheDir,`${engine.name()}-lens-safe-zero-score-${size.width}x${size.height}.png`)}); } await probe.setViewportSize({width:390,height:844}); @@ -310,6 +620,7 @@ try { await expect(page.getByTestId("tide-finish")).toBeEnabled(); } await page.getByTestId("tide-finish").click(); + if(start.story==="moth")await earnedExchange(page,"moth",engine.name()); await harbor(); return state; } @@ -340,7 +651,7 @@ try { assert.equal(geometry.count,15);assert.deepEqual(geometry.hidden,[],`${engine.name()} ${size.width}x${size.height}: all world targets remain exposed`); assert.deepEqual(geometry.scroll,[0,0,0,0],"the gesture playfield never scrolls the page"); await guidanceOverflow(page); - await buttonControls(page);await readable(page.locator(".exp-button-controls-body"));await buttonControls(page,false); + await buttonControls(page);await readable(page.locator(".exp-button-controls-body"));await exposedTideTargets(page,startTide(storyStart("lens")));await buttonControls(page,false); await page.screenshot({path:join(cacheDir,`${engine.name()}-hints-${size.width}x${size.height}.png`)}); } await page.setViewportSize({width:390,height:844}); @@ -374,6 +685,8 @@ try { assert.deepEqual((await home()).banked, ["lens"]); await page.locator('[data-action="home-next"]').click(); await page.getByRole("button", { name: "Fit the Beacon Lens" }).click(); + await earnedExchange(page,"lens",engine.name()); + await milestoneFocus(page); await expect(page.locator(".exp-departure-heading p")).toHaveText("The beacon is lit. Bram needs the Signal Vane to read the wind. Bring it home from the right shell."); await expect(page.getByRole("button",{name:"Today’s tide · optional",exact:true})).toBeVisible(); @@ -411,6 +724,7 @@ try { await sail(storyStart("vane"), 3); await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); await page.getByRole("button", { name: "Fit the Signal Vane" }).click(); + await earnedExchange(page,"vane",engine.name()); await sailStory(page); await sail(storyStart("moth")); diff --git a/web/DESIGN.md b/web/DESIGN.md index 821a146..d7bd5b3 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -30,6 +30,12 @@ The painted world already matches the Pocket Harbor concept; the interface layer **Coming home** is the peak of the loop: a centred Home sheet with the day's stamp, the three asks, a large result line and the next action (Take it to Bram, or Sail again). All three kept shows Mochi's proud portrait. Closing any panel returns focus to whatever opened it. +**Keep Wren’s Light** uses the existing harbor behind one parchment panel. At 390×844 the composition holds Bram, Mochi and the beacon’s lantern room above the parchment, unobscured throughout the introduction and repair exchanges. The lens exchange shows the existing Tidekeeper during its stillness beat. Text scrolls independently with the existing keyboard-scroll behavior; native actions stay reachable. A focusable heading receives focus after reveal, contains keyboard focus with the panel, and permits a later opening-film handoff into this composition. The film itself is separate work. Reduced motion retains the same staging, player-paced reading sequence and explicit confirmations. + +**Contextual teaching** is one persistent nonmodal cue, announced once and dismissed explicitly. Accepted and saved decisions become lessons only after their matching scene settlement. The original trace establishes already-observed lessons on resume; turning guidance back on offers future lessons. Keep the named objective separate from earlier return advice. The safely banked lens alone opens a guided decision panel with Finish and return, Keep gathering and Skip guidance; it gates play until dismissed and never substitutes for pause or filing. Menus retain complete rules. Native controls can be chosen before sailing and their complete bounds reflow the scene when opened, keeping legal destinations, labelled Wait and Finish exposed with 44px targets. + +**Harbor memories** are optional native expandable entries in the existing Log. Their prose comes only from earned banked, lit and signaled device home state, with no fabricated route charts or dates. Native summaries participate in the panel’s focus loop; descendants of closed disclosures do not. Repair and moth exchanges hold one beat until Continue, ending with Continue with Mochi. Closing an exchange preserves the earned repair and its recap. Device Menu replays the introduction without changing progress or preferences and offers Guidance on/off independently of the remembered button choice. + **The court** keeps the board clear: a Mochi status card (portrait, tide line, pips for Resolve, satchel and tool, plus one hidden sentence that reads the whole status), the surge forecast in plain words ("Next wave: left lane"), and the Tidekeeper's asks as painted-icon chips beside compact input hints. The default direction/action pad is replaced by swipe/tap guidance on touch screens and WASD/arrows on desktop. Hint mode follows actual input, not viewport width. Button controls remain in a closed-by-default native disclosure; the world retains distinct, at-least-44px targets for Wait, return and contextual objects. Menus, Sound, Inspect and confirmations remain ordinary controls. Swipes resolve only on release and produce one canonical step. A qualifying swipe travels at least 32 CSS pixels on its dominant axis with a 1.5 axis ratio; ambiguous drags do nothing. A stationary hold still inspects for free. Cancellation, multitouch, resize and modal changes discard unfinished gestures. Keyboard shortcuts act only with intentional game focus and leave native controls and text fields alone. These thresholds require physical-device comfort checks before mobile validation is claimed. diff --git a/web/PRODUCT.md b/web/PRODUCT.md index d003848..2751a70 100644 --- a/web/PRODUCT.md +++ b/web/PRODUCT.md @@ -22,6 +22,12 @@ Story preparation names the objective and outing length, with complete Tide Run Carried, banked safe, finished, filed in the harbor and installed are distinct states. Arrival at the center dock banks cargo and leaves the outing open. Pause also leaves it open. Finish ends it without advancing the water; an explicit Finish settles before filing. Failed filing retains the finished trace for deliberate retry. Filing writes the harbor prize before closing the TideBook, so a partial save must continue to offer the pending return ahead of repair. A banked story prize is safe even at zero score; installation remains deliberate after successful filing. +Keep Wren’s Light introduces the partnership in a verified fresh device harbor after the title and initial identity restoration settle. Bram names Wren’s beacon and Mochi waits for the player’s lead. Help Mochi opens Chapter 1 preparation; Skip introduction returns to the harbor; Use buttons keeps the introduction open and remembers native controls separately. Device Menu offers a read-only introduction replay and Guidance on/off. Existing progress, unreadable histories, saved-harbor mode, another interaction, or pending account work suppress the automatic introduction. Waiting for identity restoration does not block local play or insert a late introduction after play starts. + +Guidance teaches from accepted decisions after saving and scene settlement, one persistent nonmodal cue at a time. It observes the original trace on resume without replaying old lessons. Pickup and safety language follows the actual carried and banked items, including splash and ending consequences. The banked lens offers Finish and return or Keep gathering without spending a move; the finish action remains available when guidance is off. Return advice starts with nine timed moves left while carrying, and named story finds receive immediate return instructions. These cues do not promise a safe route. Reading, inspection, distant taps, tapping Mochi and changing control preferences spend no moves; labelled or native Wait spends one. + +Lens and vane installation and successful moth filing each open a short exchange at the player’s reading pace. Wren kept the light; when it failed she rowed out to guide the boats, and the boats came home. Her absence has no invented cause or promised return. The Tidekeeper was her familiar. Protection is described only when the actual shield event occurs. Harbor memories in the Log derive recaps from earned banked, lit and signaled home state, without inventing dates, routes, stamps or accepted NEAR events. Actual retained-court route pages remain separate. + Bram’s shelf joins the same daily loop: bring reed or glass home from today’s tide run (up to three of each; pearls stay with Mochi), shelve it, then trade for Shells to fill Mochi’s wish. On saved harbors Bram shelves Beacon Court hauls every other day; a find kept on this device can wait until tomorrow. Signed out, shelving and trades are a labelled device preview; wishes need a saved harbor. ## Operating Context @@ -29,6 +35,8 @@ First Light fills the desktop viewport and fits mobile portrait/landscape. Keep Outings use discrete swipe and world-tap controls on touch screens, and WASD/arrow keys on a focused desktop game. Quiet hints follow the most recent input. Wait, dock return and contextual objects have distinct world targets; a closed-by-default Button controls disclosure keeps equivalent named native controls available. Menus, Inspect, recovery and transaction confirmations remain explicit native controls. A gesture never bypasses the existing legal-command and save boundaries. +The presentation preference `familiar.guidance.keep-wrens-light.v1` stores only `{version:1,intro:null|"help"|"skip",buttons:boolean}` outside gameplay saves and the title’s expedition-save prefix. A null introduction choice permits Use buttons to survive reload while the introduction remains available. Invalid values act as unset, and storage failures leave choices active in memory without blocking play. Button disclosure changes preserve the introduction choice and reserve the complete open-control area in the scene. + ## Capabilities and Constraints First Light starts with a local preview before sign-in. Canonical actions use the recovered player's browser-authorized key, the compatible testnet registry and current ownership. Mac Privy signing and Mochi adoption are independently verified; Android same-wallet signing is user-reported. Same Mochi, earned items and progress on two physical devices remain unverified. The original operator H1 acceptance ran on testnet; it is separate from the new spatial-content acceptance. Retained signing modules include historical player-signed actions and the optional NEAR Auth recovery path; their live recovery is unverified and the earlier pet interface is retired. Receipts describe only confirmed actions. A stopped service pauses account actions without replacing the player or claiming completion. diff --git a/web/src/expedition/ControlHints.test.tsx b/web/src/expedition/ControlHints.test.tsx index f97d17b..244bb98 100644 --- a/web/src/expedition/ControlHints.test.tsx +++ b/web/src/expedition/ControlHints.test.tsx @@ -30,3 +30,10 @@ test("outing guidance shares the hint reading area while native controls remain expect(html).toContain('

Banking keeps the outing open.

'); expect(html).toContain('
'); }); + +test("a controlled button preference opens native controls while the default remains closed", () => { + const html=renderToStaticMarkup({}}>); + expect(html).toContain('
'); + expect(html).toContain('Button controls'); + expect(html).toContain(''); +}); diff --git a/web/src/expedition/ControlHints.tsx b/web/src/expedition/ControlHints.tsx index c7c3f69..bfe6ee5 100644 --- a/web/src/expedition/ControlHints.tsx +++ b/web/src/expedition/ControlHints.tsx @@ -3,8 +3,8 @@ import { scrollReadingRegion } from "./keyboard-scroll"; type InputMode = "touch" | "keyboard"; -export default function ControlHints({id,context="Tap Wait beside Mochi · tap a find to collect it.",children,reading,initialMode,keyboardContext="Space waits · E interacts · R returns at the dock · I inspects"}:{ - id:string; context?:string; children:ReactNode; reading?:ReactNode; initialMode?:InputMode; keyboardContext?:string; +export default function ControlHints({id,context="Tap Wait beside Mochi · tap a find to collect it.",children,reading,initialMode,keyboardContext="Space waits · E interacts · R returns at the dock · I inspects",buttonsOpen,onButtonsOpenChange}:{ + id:string; context?:string; children:ReactNode; reading?:ReactNode; initialMode?:InputMode; keyboardContext?:string; buttonsOpen?:boolean; onButtonsOpenChange?:(open:boolean)=>void; }) { const root=useRef(null); const readingArea=useRef(null); @@ -36,7 +36,7 @@ export default function ControlHints({id,context="Tap Wait beside Mochi · tap a ; return
{reading?
{reading}{help}
:help} -
Button controls
{children}
+
{if(event.currentTarget.open!==buttonsOpen)onButtonsOpenChange?.(event.currentTarget.open);}}>Button controls
{children}
{moreReading&&}
; } diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index a78a47e..feea641 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -2,6 +2,7 @@ import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState, type import "@fontsource-variable/fraunces"; import "@fontsource-variable/figtree"; import World from "./World"; +import StoryPanel, { exchangeBeats } from "./StoryPanel"; import PassageGame from "./PassageGame"; import {SealedNote,sealedNoteEnabled} from "../note/SealedNote"; import { passageDelivered, startPassage, type PassageState } from "./passage"; @@ -36,7 +37,9 @@ import { tideSailReason } from "../tide/sailing"; import TideRunGame, { TideRunRules } from "../run/TideRunGame"; import { startTide, tideShape, type TideStart, type TideState } from "../run/engine"; import { bramsGuess } from "../run/bot"; -import { CHAPTERS, chapterFor, storyStart } from "../run/story"; +import { CHAPTERS, chapterFor, harborMemories, storyStart } from "../run/story"; +import { guidanceEnabled, readGuidance, writeGuidance, type GuidancePreferences } from "../run/guidance"; +import { pristineDeviceHarbor } from "./onboarding"; import { closeTide, dayResults, emptyBook, readBook, shelfHaul, todayResult, writeBook, type DayResult, type TideBook } from "../run/save"; // Bram's shelf loads when his dialog first opens. @@ -55,7 +58,7 @@ const tideScopeOf=(context:RunContext)=>context.authority==="near-testnet"?conte function readLocal(key=EXPEDITION_SAVE_KEY):{save:LocalSave;problem:string}{ try{ - const raw=localStorage.getItem(key);if(!raw)return{save:fresh(),problem:""}; + const raw=localStorage.getItem(key);if(raw===null)return{save:fresh(),problem:""}; const value=JSON.parse(raw) as LocalSave,h=value.home; if(!value||typeof value!=="object"||Array.isArray(value)||value.version!==2||!h||typeof h!=="object"||Array.isArray(h)||!Array.isArray(h.banked)||new Set(h.banked).size!==h.banked.length||h.banked.some(i=>!["lens","moth","vane","chart","salvage"].includes(i))||typeof h.lit!=="boolean"||typeof h.signaled!=="boolean"||(h.lit&&!h.banked.includes("lens"))||(h.signaled&&(!h.lit||!h.banked.includes("vane")))||value.active!==null&&(!value.active||typeof value.active!=="object"||Array.isArray(value.active))||value.last!==null&&(!value.last||typeof value.last!=="object"||Array.isArray(value.last))||h.lantern!==null&&(!h.lantern||typeof h.lantern!=="object"||Array.isArray(h.lantern)))throw Error(); if(h.lantern&&(!h.banked.includes("lens")||!["crest","moth"].includes(h.lantern.motif)||!["porch","dock"].includes(h.lantern.socket)||(h.lantern.motif==="moth"&&!h.banked.includes("moth"))))throw Error(); @@ -88,14 +91,17 @@ function Icon({kind}:{kind:"menu"|"close"|"bag"|"sound"|"silent"|"north"|"south" } /** `audio`, `initialSound` and `initialMix` carry the title screen's sound choice. */ -export interface ExpeditionGameProps {session?:HarborSession;accountPanel?:ReactNode;audio?:HarborAudio;initialSound?:boolean;initialMix?:readonly [number,number]} -export default function ExpeditionGame({session,accountPanel,audio:titleAudio,initialSound=false,initialMix=[0.8,1]}:ExpeditionGameProps={}){ +export interface ExpeditionGameProps {session?:HarborSession;accountPanel?:ReactNode;audio?:HarborAudio;initialSound?:boolean;initialMix?:readonly [number,number];initialRestorationComplete?:boolean;titleHandoffComplete?:boolean} +type StoryPresentation={branch:string;owner:HarborSession|undefined;kind:"introduction"|"replay"|"lens"|"vane"|"moth";beat:number;generation:number}; +export default function ExpeditionGame({session,accountPanel,audio:titleAudio,initialSound=false,initialMix=[0.8,1],initialRestorationComplete=!session,titleHandoffComplete=true}:ExpeditionGameProps={}){ const [initial]=useState(readLocal),[save,setSave]=useState(initial.save),[surface,setSurface]=useState(null); const [problem,setProblem]=useState(initial.problem),[corrupt,setCorrupt]=useState(!!initial.problem),[notice,setNotice]=useState(""),[transition,setTransition]=useState(null),[presentationId,setPresentationId]=useState(0),[busy,setBusy]=useState(false),[finishing,setFinishing]=useState(false),[focused,setFocused]=useState(null); const [lease,setLease]=useState<"waiting"|"held"|"blocked"|"unavailable">("waiting"),[leaseAttempt,setLeaseAttempt]=useState(0); const [tool,setTool]=useState("rope"),[area,setArea]=useState(()=>initial.save.home.lit&&!initial.save.home.banked.includes("vane")?"wind":"beacon"),[reduced,setReduced]=useState(()=>matchMedia("(prefers-reduced-motion: reduce)").matches),[hidden,setHidden]=useState(document.hidden),[unfocused,setUnfocused]=useState(false),[fault,setFault]=useState(""),[sceneKey,setSceneKey]=useState(0),[sound,setSound]=useState(initialSound),[motif,setMotif]=useState<"crest"|"moth">("crest"),[recipient,setRecipient]=useState(""),[lastBeat,setLastBeat]=useState(""); const saveRef=useRef(save),keyRef=useRef(EXPEDITION_SAVE_KEY),busyRef=useRef(false),buffer=useRef(null),presentation=useRef(0),sessionRef=useRef(session),audio=useRef(titleAudio??null),panelRef=useRef(null),trigger=useRef(null),pressed=useRef(null),corruptRef=useRef(corrupt),finishBusy=useRef(false),finishEpoch=useRef(0),alive=useRef(true); const [resting,setResting]=useState(false),[greeting,setGreeting]=useState(0); + const [guidance,setGuidance]=useState(readGuidance),[storyPresentation,setStoryPresentation]=useState(null); + const storyHeadingRef=useRef(null); const gameRef=useRef(null),departureRef=useRef(null); const [musicLevel,setMusicLevel]=useState(initialMix[0]),[effectsLevel,setEffectsLevel]=useState(initialMix[1]); const [passage,setPassage]=useState(emptyPassageHome); @@ -135,6 +141,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const visibleRun=busy&&transition?transition.before:run; const canonical=savedMode?session!.state.snapshot!.journey:null; const desiredKey=savedMode?`familiar.expedition.game.v2:testnet:${session!.state.snapshot!.binding.nearAccountId}`:EXPEDITION_SAVE_KEY; + const storyPanel=storyPresentation?.branch===desiredKey&&storyPresentation.owner===session&&storyPresentation.generation===presentation.current&&!savedMode?storyPresentation:null; + const interaction=useRef({started:false}); const home:LocalHome=canonical?{banked:canonical.banked as BankedItem[],lit:canonical.lit,signaled:canonical.signaled,lantern:null}:save.home; const tideScope=savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"; const [currentTideDay,setCurrentTideDay]=useState(tideDay); @@ -181,10 +189,11 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const chapterComplete=home.signaled&&services.includes("bell")&&services.includes("reed"); const placement=session?.state.workshop.placement,placedItem=savedMode&&placement?session!.state.workshop.items.find(item=>item.mint.token_id===placement.item_id):null; const harbor:HarborView={resting,greeting,heardBell:passageScope===passageKey&&passage.heardBell,services,watchedReeds:passageScope===passageKey&&passage.watchedReeds,lit:home.lit,signaled:home.signaled,moth:home.banked.includes("moth"),lantern:!!(savedMode?placedItem:home.lantern),socket:savedMode&&placedItem?placement!.socket:home.lantern?.socket??"porch",motif:savedMode?placedItem?.mint.motif??"crest":home.lantern?.motif??"crest",polished:savedMode&&placedItem?.finish==="harbor_polish",relic:home.banked.includes("lens")&&!home.lit?"lens":home.banked.includes("vane")&&!home.signaled?"vane":null}; - const paused=showPassage||showTideRun||lease!=="held"||!worldReady||!!surface||hidden||unfocused||!!fault||!!problem||!!session?.state.review; + const paused=showPassage||showTideRun||lease!=="held"||!worldReady||!!surface||!!storyPanel||hidden||unfocused||!!fault||!!problem||!!session?.state.review; const pausedRef=useRef(paused);pausedRef.current=paused; const worldActions=useMemo(()=>{if(!run)return [];const available=legalCommands(run),actions:WorldAction[]=[];for(const action of ["wait","return","turn:vane"] as const)if(available.includes(action))actions.push(action);if(available.some(action=>action.startsWith("lure:")))actions.push("lantern");return actions;},[run]); - const snapshot=useMemo(()=>({court:run,home:harbor,reducedMotion:reduced,previewCommand:focused,worldActions}),[run,worldActions,harbor.lit,harbor.signaled,harbor.moth,harbor.lantern,harbor.socket,harbor.motif,harbor.polished,harbor.relic,resting,greeting,passage,passageScope,reduced,focused]); + const storyStage=storyPanel?{kind:storyPanel.kind,keeper:storyPanel.kind==="lens"&&storyPanel.beat===1}:undefined; + const snapshot=useMemo(()=>({court:run,home:harbor,reducedMotion:reduced,previewCommand:focused,worldActions,storyStage}),[run,worldActions,harbor.lit,harbor.signaled,harbor.moth,harbor.lantern,harbor.socket,harbor.motif,harbor.polished,harbor.relic,resting,greeting,passage,passageScope,reduced,focused,storyPanel?.kind,storyPanel?.beat]); const previousHome=useRef({branch:desiredKey,lit:home.lit,signaled:home.signaled}); useEffect(()=>{ const before=previousHome.current; @@ -196,13 +205,25 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const completed=repair.kind==="signal"?!before.signaled&&home.signaled:!before.lit&&home.lit; if(completed){repairRequest.current=null;audio.current?.playMusic(repair.kind);} },[home.lit,home.signaled,desiredKey]); - const previewReturns=useMemo(()=>{try{return new ReturnRecords(localStorage).read({authority:"local-preview",banked:save.home.banked,lit:save.home.lit,signaled:save.home.signaled});}catch{return[];}},[save.last,save.home.banked]); + const previewReturnRead=useMemo(()=>{try{return{ok:true,records:new ReturnRecords(localStorage).read({authority:"local-preview",banked:save.home.banked,lit:save.home.lit,signaled:save.home.signaled})};}catch{return{ok:false,records:[]};}},[save.last,save.home.banked,lease]); + const previewReturns=previewReturnRead.records; const logReturns=savedMode?session!.state.returns:previewReturns; const dailyResults=useMemo(()=>savedMode?[]:dayResults(tideBook),[savedMode,tideBook.days]); const todayTide=dailyResults.find(result=>result.day===today)??null; const todayGuess=useMemo(()=>savedMode?0:bramsGuess(today),[savedMode,today]); const logBook=useMemo(()=>savedMode?logPages(logReturns,tideEntries):logPages(logReturns,tideEntries,dailyResults),[savedMode,logReturns,tideEntries,dailyResults]); const logSummary=useMemo(()=>savedMode?tideSummary(tideEntries):tideSummary(tideEntries,dailyResults),[savedMode,tideEntries,dailyResults]); + const memories=savedMode?[]:harborMemories(home); + useEffect(()=>{ + if(storyPresentation&&(storyPresentation.branch!==desiredKey||storyPresentation.owner!==session||storyPresentation.generation!==presentation.current||savedMode))setStoryPresentation(null); + },[desiredKey,session,savedMode,storyPresentation]); + useEffect(()=>{ + if(savedMode||guidance.intro!==null||interaction.current.started||keyRef.current!==desiredKey||passageScope!==passageKey||corrupt||problem||passageError||!tideBookReadable.current||!passageReadable.current||lease!=="held"||!worldReady||!titleHandoffComplete||!initialRestorationComplete||hidden||unfocused||fault||surface||storyPanel||session?.state.review||session?.state.pending||session?.state.busy||session?.state.message)return; + if(!pristineDeviceHarbor(save,tideBook,passage,previewReturnRead))return; + interaction.current.started=true; + trigger.current=opener(); + setStoryPresentation({branch:desiredKey,owner:session,kind:"introduction",beat:0,generation:presentation.current}); + },[savedMode,guidance.intro,desiredKey,passageScope,corrupt,problem,passageError,lease,worldReady,titleHandoffComplete,initialRestorationComplete,hidden,unfocused,fault,surface,storyPanel,session,session?.state.review,session?.state.pending,session?.state.busy,session?.state.message,save,tideBook,passage,previewReturnRead]); const sailBlockedReason=tideSailReason({lit:home.lit,lease,problem,run:!!run,worldReady,showPassage,busy:session?.state.busy,pending:!!session?.state.pending}); const canSailTide=sailBlockedReason===null; const canRestartTide=!!save.active?.season&&run?.outcome==="active"&&!busy&&!finishing&&!problem&&!fault&&worldReady&&lease==="held"&&!session?.state.busy&&!session?.state.pending; @@ -252,8 +273,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in }); return()=>{current=false;leaseRef.current="waiting";cancelAnimationFrame(frame);release?.();}; },[desiredKey,leaseAttempt]); - useEffect(()=>{if(surface||session?.state.review){if(!panelOpen.current&&!trigger.current)trigger.current=opener();panelOpen.current=true;const frame=requestAnimationFrame(()=>panelRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected&&(opener!==gameRef.current||run))opener.focus({preventScroll:true});else if(run)gameRef.current?.focus({preventScroll:true});else (document.querySelector(".exp-departure .exp-primary:not(:disabled)")??document.querySelector(".exp-departure-buttons button:not(:disabled)")??gameRef.current)?.focus({preventScroll:true});}},[surface,session?.state.review?.id,worldReady]); - useEffect(()=>{if(!surface&&!session?.state.review)return;const trap=(event:KeyboardEvent)=>{if(event.key!=="Tab")return;const panel=panelRef.current;if(!panel)return;const targets=[...panel.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),[tabindex="0"]')].filter(n=>n.getClientRects().length);if(!targets.length){event.preventDefault();panel.focus();return;}const first=targets[0]!,last=targets.at(-1)!;if(event.shiftKey&&(document.activeElement===first||document.activeElement===panel)){event.preventDefault();last.focus();}else if(!event.shiftKey&&(document.activeElement===last||document.activeElement===panel)){event.preventDefault();first.focus();}};window.addEventListener("keydown",trap);return()=>window.removeEventListener("keydown",trap);},[surface,session?.state.review?.id]); + useEffect(()=>{if(surface||storyPanel||session?.state.review){if(!panelOpen.current&&!trigger.current)trigger.current=opener();panelOpen.current=true;const frame=requestAnimationFrame(()=>(storyPanel?storyHeadingRef.current:panelRef.current)?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected&&(opener!==gameRef.current||run))opener.focus({preventScroll:true});else if(run)gameRef.current?.focus({preventScroll:true});else (document.querySelector(".exp-departure .exp-primary:not(:disabled)")??document.querySelector(".exp-departure-buttons button:not(:disabled)")??gameRef.current)?.focus({preventScroll:true});}},[surface,storyPanel?.kind,storyPanel?.beat,session?.state.review?.id,worldReady]); + useEffect(()=>{if(!surface&&!storyPanel&&!session?.state.review)return;const trap=(event:KeyboardEvent)=>{if(event.key!=="Tab")return;const panel=panelRef.current;if(!panel)return;const targets=[...panel.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),textarea:not(:disabled),select:not(:disabled),summary,[tabindex="0"]')].filter(n=>n.getClientRects().length&&!n.closest('[hidden],[inert]')&&![...panel.querySelectorAll('details:not([open])')].some(details=>details.contains(n)&&n!==details.querySelector(":scope > summary")));if(!targets.length){event.preventDefault();panel.focus();return;}const first=targets[0]!,last=targets.at(-1)!,inside=targets.includes(document.activeElement as HTMLElement);if(event.shiftKey&&(document.activeElement===first||!inside)){event.preventDefault();last.focus();}else if(!event.shiftKey&&(document.activeElement===last||!inside)){event.preventDefault();first.focus();}};window.addEventListener("keydown",trap);return()=>window.removeEventListener("keydown",trap);},[surface,!!storyPanel,session?.state.review?.id]); function persist(next:LocalSave){if(leaseRef.current!=="held"){setNotice("This expedition is open in another tab. Finish there, or close that tab and check again.");return false;}try{writeLocal(next,keyRef.current);saveRef.current=next;setSave(next);setProblem("");return true;}catch(error){setProblem(error instanceof Error?error.message:"This browser could not save the move. No new action was taken.");return false;}} /** `tide` starts Season 2's daily outing: a fresh Beacon Court with nothing banked, kept apart from First Light progress, answering one day's Tidekeeper ask. */ @@ -326,7 +347,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(!selected&&available.some(c=>c.startsWith("lure:"))&&!busyRef.current){event.preventDefault();open("lantern");return;} } if(selected){event.preventDefault();command(selected);} - };window.addEventListener("keydown",keys);return()=>window.removeEventListener("keydown",keys);},[command,showPassage,showTideRun]); + };window.addEventListener("keydown",keys);return()=>window.removeEventListener("keydown",keys);},[command,showPassage,showTideRun,storyPanel,guidance]); function inspect(position:Position){ const state=saveRef.current.active?.state; if(!state)return; @@ -350,13 +371,16 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in function hover(position:Position|null){if(busyRef.current)return;const state=saveRef.current.active?.state;setFocused(position&&state?commandAt(state,position):null);} /** Safari never focuses a clicked button, so fall back to the last button pressed. */ function opener(){const active=document.activeElement;return active instanceof HTMLElement&&active!==document.body&&active!==gameRef.current?active:pressed.current?.isConnected?pressed.current:active instanceof HTMLElement&&active===gameRef.current?active:null;} - function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"story"|"tide"|"court-tide"|"log"|"home"){if(!panelOpen.current)trigger.current=opener();if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}if(place==="tide"&&!savedMode&&tideResume){setTideAway(false);setSurface(null);return;}if(place==="tide")setCurrentTideDay(tideDay());setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect"&&trigger.current!==gameRef.current;setSurface(place);} - function closePanel(){const controller=sessionRef.current;if(controller?.state.review){if(controller.state.busy)return;controller.cancelReview();}setSurface(null);} + function changeGuidance(change:Partial>){if(savedMode)return;setGuidance(before=>{const next={...before,...change};writeGuidance(next);return next;});} + function openStory(kind:StoryPresentation["kind"]){interaction.current.started=true;if(!panelOpen.current)trigger.current=opener();setSurface(null);buffer.current=null;setStoryPresentation({branch:desiredKey,owner:session,kind,beat:0,generation:presentation.current});} + function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"story"|"tide"|"court-tide"|"log"|"home"){interaction.current.started=true;if(!panelOpen.current)trigger.current=opener();setStoryPresentation(null);if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}if(place==="tide"&&!savedMode&&tideResume){setTideAway(false);setSurface(null);return;}if(place==="tide")setCurrentTideDay(tideDay());setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect"&&trigger.current!==gameRef.current;setSurface(place);} + function closePanel(){const controller=sessionRef.current;if(controller?.state.review){if(controller.state.busy)return;controller.cancelReview();}if(storyPanel?.kind==="introduction")changeGuidance({intro:"skip"});setStoryPresentation(null);setSurface(null);} function request(intent:WorldIntent){void sessionRef.current?.review(intent).catch(()=>{/* The controller keeps the actual failure and original operation visible. */});} function restore(restoration:"beacon"|"signal"){ if(savedMode){request({kind:"restore",restoration});return;} - if(restoration==="beacon"&&home.banked.includes("lens")){if(persist({...saveRef.current,home:{...saveRef.current.home,lit:true}})){repairRequest.current={branch:desiredKey,kind:"beacon"};setNotice(`Mochi lifts the lens into place. The beacon finds the bay again. The Tidekeeper stops mid-turn and stares at the light. Bram: “${CHAPTERS.lens.after[0]}”`);setSurface(null);}} - else if(restoration==="signal"&&home.lit&&home.banked.includes("vane")){if(persist({...saveRef.current,home:{...saveRef.current.home,signaled:true}})){repairRequest.current={branch:desiredKey,kind:"signal"};setNotice(`The vane catches the breeze. Bram: “${CHAPTERS.vane.after.join(" ")}”`);setSurface(null);}} + if(tideBook.active)return; + if(restoration==="beacon"&&!home.lit&&home.banked.includes("lens")){if(persist({...saveRef.current,home:{...saveRef.current.home,lit:true}})){repairRequest.current={branch:desiredKey,kind:"beacon"};setNotice("");openStory("lens");}} + else if(restoration==="signal"&&!home.signaled&&home.lit&&home.banked.includes("vane")){if(persist({...saveRef.current,home:{...saveRef.current.home,signaled:true}})){repairRequest.current={branch:desiredKey,kind:"signal"};setNotice("");openStory("vane");}} } function storePassage(next:PassageHome){ if(!passageReadable.current||passageScope!==passageKey||keyRef.current!==desiredKey||leaseRef.current!=="held")return false; @@ -398,7 +422,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(!storeTideBook(closed))return false; if(again){setReadySceneKey(-1);setSceneKey(k=>k+1);open(prize?"story":"tide");return true;} setReadySceneKey(-1);setSceneKey(k=>k+1); - if(prize)setNotice(won?`Mochi brought the ${names[prize]} home.${prize==="moth"?` Bram: “${CHAPTERS.moth.after.join(" ")}”`:""}`:`The ${names[prize]} is back in its shell. The tide will open it again.`); + if(prize){setNotice(won?`Mochi brought the ${names[prize]} home.`:`The ${names[prize]} is back in its shell. The tide will open it again.`);if(won&&prize==="moth"){setNotice("");openStory("moth");}} else{ const result=todayResult(closed,state.seed)!; const message=first?`Banked ${state.score}. Bram guessed ${result.guess}.`:`A practice tide: banked ${state.score}. Today’s first tide is the one that counts.`; @@ -454,6 +478,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const shownForecast=busy?currentBeat?`Resolving: ${eventDescription(currentBeat,run?.area)}`:"Mochi is acting. The tide will follow.":run?forecast(run,focused):""; if(showTideRun&&tideBook.active&&lease==="held"&&!problem)return changeGuidance({buttons})} onSkipGuidance={()=>changeGuidance({intro:"skip"})} onSave={next=>storeTideBook({...tideBook,active:next})} onFinish={finishTideRun} onToggleSound={()=>void toggleSound()} onLeave={()=>{setTideAway(true);setReadySceneKey(-1);setSceneKey(k=>k+1);}}/>; if(showPassage&&passage.active&&lease==="held"&&!problem&&!session?.state.review)return <> @@ -463,11 +488,11 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in onFinish={finishPassage} onToggleSound={()=>void toggleSound()} onLeave={()=>backFromPassage({...passage,active:null},"The line is coiled at home. You can choose another crossing.")}/> {passageError&&

{passageError}

} ; - return
{pressed.current=(event.target as Element).closest("button,summary");if(event.target instanceof HTMLCanvasElement)gameRef.current?.focus({preventScroll:true});}} data-testid="expedition-game" data-mode={run?"court":"harbor"} data-busy={busy} data-lease={lease} data-content={CONTENT_VERSION} data-beat={lastBeat}> + return
{interaction.current.started=true;}} onPointerDownCapture={event=>{interaction.current.started=true;pressed.current=(event.target as Element).closest("button,summary");if(event.target instanceof HTMLCanvasElement)gameRef.current?.focus({preventScroll:true});}} data-testid="expedition-game" data-mode={run?"court":"harbor"} data-story={storyPanel?.kind} data-story-beat={storyPanel?.beat} data-busy={busy} data-lease={lease} data-content={CONTENT_VERSION} data-beat={lastBeat}> {lease!=="waiting"&&{if(pausedRef.current||!worldActions.includes(action))return;if(action==="lantern"){if(!busyRef.current)open("lantern");}else if(action!=="ride"&&action!=="listen"&&action!=="ring")command(action);}} onCommand={command} onTarget={target} onInspect={inspect} onHover={hover} onHome={open} onSettled={settled} onBeat={beat} onFault={message=>{setFault(message);buffer.current=null;}} onReady={()=>setReadySceneKey(sceneKey)}/>} {!worldReady&&!fault&&

familiar.

Unpacking the harbor.

Opening the artwork. Mochi’s saved moves are safe.

Reload Familiar
} {worldReady&&<> -
familiar.{authority}
{run?COURTS[run.area].title:"Pocket Harbor"}
{!run&&}{!run&&!surface&&!session?.state.review&&}
+
familiar.{authority}
{run?COURTS[run.area].title:"Pocket Harbor"}
{!run&&}{!run&&!surface&&!session?.state.review&&}
{visibleRun&&
- + } {run&&!surface&&!fault&&!session?.state.review&&
{tideCard&&tideRun&&
{cardStatus(tideCard,tideRun).includes("slipped")&&}
}

{objective}

{shownForecast}

{feedback}
{(["north","west","east","south"] as const).map(direction=>)}
{pickups.map(input=>button(input))}{run.tool==="lantern"&&interactionLegal.some(c=>c.startsWith("lure:"))&&}{!pickups.length&&!interactionLegal.includes("return")&&!interactionLegal.some(c=>c.startsWith("lure:"))&&

{busy?"Mochi finishes this moment first. One next direction can wait.":run.cargo.length?`${run.cargo.map(i=>names[i]).join(" + ")} secured. Reach the center dock to return.`:"Route a surge to open a shell and move the bridge."}

}
{interactionLegal.includes("return")&&
{button("return")}
}
} {(!run||surface||fault||session?.state.review)&&feedback} {(problem||activeReturn&&!busy)&&

{problem||(finishing?"Keeping the original return safe…":"Mochi’s return is ready to save.")}

{activeReturn&&}{!corrupt&&!activeReturn&&}
} {(lease==="blocked"||lease==="unavailable")&&

{lease==="blocked"?"This expedition is open in another tab. Finish there, or close that tab before continuing here.":"This browser cannot safely coordinate saved expeditions. Web Locks support is required; no move has been taken."}

{lease==="blocked"&&}
} - {(surface||session?.state.review)&&
{(surface!=="story"||savedMode||!storyNext||!!session?.state.review)&&} - {session?.state.review?<>

{session.state.review.title}

{session.state.review.description}

{session.state.review.costs.length>0&&
    {session.state.review.costs.map(cost=>
  • {cost}
  • )}
}:surface==="account"?<>

Keep your harbor

{accountPanel??

Recoverable account controls are not connected to this local preview. This visit does not prove ownership or device recovery.

}:surface==="menu"?<>

A moment at the water’s edge.

Play at your own pace. Only accepted decisions advance the tide.

{!run&&}{logBook.length>0&&}{sound&&
Sound mix
}{save.active?.season&&}:surface==="lantern"?<>

A light on the water.

Choose a source. The wind-wheel, when present, determines its exit.

{(["left","center","right"] as const).map(lane=>)}:surface==="inspect"&&run?:surface==="guide"&&!savedMode&&!run?<>

How Tide Run works

:surface==="guide"?<>

Read the water.

Swipe on the court or tap a glowing neighboring platform. On a keyboard, use WASD or the arrow keys. Crossing the open bridge is one decision. Optional Button controls keep every action available without gestures.

Low: choose your footing. Rising: your resulting column becomes the source. Surge: act first, then the wave opens that column’s bridge and shell. Standing in the wave washes Mochi down one platform.

Rope retrieves an exposed lens or vane from two steps away. Lantern redirects a marked surge. A living moth needs two pack slots. Reach the center dock to return before 24 decisions.

{run?.area==="wind"&&

Current channels: Left → {columns[run.orientation]}, Center → {columns[(1+run.orientation)%3]}, Right → {columns[(2+run.orientation)%3]}. The cradle needs Left and Center charged and wheel alignment zero.

}

Tap Wait beside Mochi, or Home at the dock to come home. E uses a nearby object or opens the lantern; Space waits; R returns at the dock; I inspects. Right-click or hold a world target to inspect for free. Inspection and menus spend no turns.

:surface==="chart"?
{!storyPanel&&(surface!=="story"||savedMode||!storyNext||!!session?.state.review)&&} + {storyPanel?0||home.lit||home.signaled||!!save.active||!!save.last||!!tideBook.active||tideBook.days.length>0||previewReturns.length>0||!!passage.active||services.length>0||passage.watchedReeds||passage.heardBell||tideEntries.length>0||readTide(tideScope).length>0} buttons={guidance.buttons} headingRef={storyHeadingRef} onClose={closePanel} onHelp={()=>{changeGuidance({intro:"help"});setStoryPresentation(null);setSurface("story");}} onUseButtons={()=>changeGuidance({buttons:true})} onContinue={()=>{const kind=storyPanel.kind;if(kind==="introduction"||kind==="replay")return;if(storyPanel.beat===exchangeBeats[kind].length-1)closePanel();else setStoryPresentation({...storyPanel,beat:storyPanel.beat+1});}}/>:session?.state.review?<>

{session.state.review.title}

{session.state.review.description}

{session.state.review.costs.length>0&&
    {session.state.review.costs.map(cost=>
  • {cost}
  • )}
}:surface==="account"?<>

Keep your harbor

{accountPanel??

Recoverable account controls are not connected to this local preview. This visit does not prove ownership or device recovery.

}:surface==="menu"?<>

A moment at the water’s edge.

Play at your own pace. Only accepted decisions advance the tide.

{!run&&}{(logBook.length>0||memories.length>0)&&}{!savedMode&&<>}{sound&&
Sound mix
}{save.active?.season&&}:surface==="lantern"?<>

A light on the water.

Choose a source. The wind-wheel, when present, determines its exit.

{(["left","center","right"] as const).map(lane=>)}:surface==="inspect"&&run?:surface==="guide"&&!savedMode&&!run?<>

How Tide Run works

:surface==="guide"?<>

Read the water.

Swipe on the court or tap a glowing neighboring platform. On a keyboard, use WASD or the arrow keys. Crossing the open bridge is one decision. Optional Button controls keep every action available without gestures.

Low: choose your footing. Rising: your resulting column becomes the source. Surge: act first, then the wave opens that column’s bridge and shell. Standing in the wave washes Mochi down one platform.

Rope retrieves an exposed lens or vane from two steps away. Lantern redirects a marked surge. A living moth needs two pack slots. Reach the center dock to return before 24 decisions.

{run?.area==="wind"&&

Current channels: Left → {columns[run.orientation]}, Center → {columns[(1+run.orientation)%3]}, Right → {columns[(2+run.orientation)%3]}. The cradle needs Left and Center charged and wheel alignment zero.

}

Tap Wait beside Mochi, or Home at the dock to come home. E uses a nearby object or opens the lantern; Space waits; R returns at the dock; I inspects. Right-click or hold a world target to inspect for free. Inspection and menus spend no turns.

:surface==="chart"?{setArea(choice);open(!savedMode&&home.lit&&choice==="beacon"?"court-tide":"sail");}} onCrossing={departPassage} onRepair={()=>open("beacon")} onRest={()=>{setSurface(null);setGreeting(0);setResting(true);if(sound)audio.current?.playMusic("harbor");}}/>:surface==="crossings"?<>

The harbor crossing

@@ -526,7 +551,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in
How Tide Run works
- :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}

{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}

{!home.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.

{record.id}

)}{sealedNoteEnabled()&&savedMode&&session?.noteToken&&session.noteToken!()}/>}{save.last&&

{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}

}

{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}

:surface==="bram"?<>

“You’re back.”

{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}

{harbor.heardBell&&

“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}{Bram is setting out his shelf…

}>open("tide")} tideScope={savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"} {...(!savedMode?{run:todayTide}:{})}/>
}:surface==="home"&&arrival?(!savedMode&&"result" in arrival?0&&!shelved} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>open("tide")} onOpenLog={()=>openLog(arrival.day)}/>:"run" in arrival?0&&!shelved&&shelvesBeaconCourt(today)} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>sailTide(arrival.day)} onOpenLog={()=>openLog(arrival.day)}/>:null):surface==="tide"&&!savedMode?:surface==="tide"||surface==="court-tide"?:surface==="log"?:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

Choose an earned motif for one First Light lantern.

{session.state.workshop.motifs.map(m=>)}:

{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}

}{!!session?.state.workshop.items.length&&
Give a lantern

Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.

Light’s origin{previewOrigin?<>

Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.

Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} + :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}

{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}

{!home.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.

{record.id}

)}{sealedNoteEnabled()&&savedMode&&session?.noteToken&&session.noteToken!()}/>}{save.last&&

{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}

}

{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}

:surface==="bram"?<>

“You’re back.”

{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}

{harbor.heardBell&&

“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}{Bram is setting out his shelf…

}>open("tide")} tideScope={savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"} {...(!savedMode?{run:todayTide}:{})}/>
}:surface==="home"&&arrival?(!savedMode&&"result" in arrival?0&&!shelved} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>open("tide")} onOpenLog={()=>openLog(arrival.day)}/>:"run" in arrival?0&&!shelved&&shelvesBeaconCourt(today)} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>sailTide(arrival.day)} onOpenLog={()=>openLog(arrival.day)}/>:null):surface==="tide"&&!savedMode?:surface==="tide"||surface==="court-tide"?:surface==="log"?:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

Choose an earned motif for one First Light lantern.

{session.state.workshop.motifs.map(m=>)}:

{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}

}{!!session?.state.workshop.items.length&&
Give a lantern

Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.

Light’s origin{previewOrigin?<>

Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.

Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} {session?.state.message&&

{session.state.message}

} } } diff --git a/web/src/expedition/StoryPanel.test.tsx b/web/src/expedition/StoryPanel.test.tsx new file mode 100644 index 0000000..74a8aaa --- /dev/null +++ b/web/src/expedition/StoryPanel.test.tsx @@ -0,0 +1,41 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import StoryPanel, { exchangeBeats, type StoryMoment } from "./StoryPanel"; + +const render=(kind:StoryMoment,beat=0,progress=false,buttons=false)=>renderToStaticMarkup({}} onHelp={()=>{}} onUseButtons={()=>{}} onContinue={()=>{}}/>); +test("the prologue establishes the role and objective with all three native choices",()=>{ + const html=render("introduction"); + for(const copy of ["Keep Wren’s Light","You guide Mochi as a volunteer harbor helper.","I’m Bram. Wren’s beacon helps the boats find harbor.","Mochi looks from the dark beacon to the water, then waits for your lead.","Bring the Beacon Lens home from the left shell.","Help Mochi","Skip introduction","Use buttons"])expect(html).toContain(copy); + expect(html).toContain('id="exp-story-heading" data-prologue-heading="true"'); + expect(html).toContain('tabindex="-1"'); + expect(html).toContain('role="region" aria-label="Introduction"'); + expect(render("introduction",0,false,true)).toContain("Button controls will be open when you sail."); +}); +test("the prologue objective stays with Help Mochi outside the scrolling prose",()=>{ + for(const buttons of [false,true]){ + const html=render("introduction",0,false,buttons); + const actions=html.slice(html.indexOf('class="exp-story-actions"')); + expect(actions).toContain('

Bring the Beacon Lens home from the left shell.

'); + expect(actions.indexOf('class="exp-story-objective"')).toBeLessThan(actions.indexOf(">Help Mochi<")); + } +}); +test("manual replay is read-only before and after progress",()=>{ + for(const progress of [false,true]){ + const html=render("replay",0,progress); + expect(html).toContain("Back to Mochi"); + expect(html).not.toContain("Help Mochi"); + expect(html).not.toContain("Skip introduction"); + expect(html).not.toContain("Use buttons"); + expect(html).not.toContain("Bring the Beacon Lens home from the left shell."); + } + expect(render("replay",0,true)).toContain("How it began"); + expect(render("replay",0,true)).toContain("The storm had taken the beacon’s lens. Mochi was ready to help."); +}); +test("exchanges hold exactly one beat and end with the deliberate continuation",()=>{ + for(const kind of ["lens","vane","moth"] as const)for(const [beat,line] of exchangeBeats[kind].entries()){ + const html=render(kind,beat); + expect(html).toContain(line); + for(const other of exchangeBeats[kind].filter(other=>other!==line))expect(html).not.toContain(other); + expect(html).toContain(beat===exchangeBeats[kind].length-1?">Continue with Mochi<":">Continue<"); + } +}); diff --git a/web/src/expedition/StoryPanel.tsx b/web/src/expedition/StoryPanel.tsx new file mode 100644 index 0000000..f4893da --- /dev/null +++ b/web/src/expedition/StoryPanel.tsx @@ -0,0 +1,36 @@ +import type { RefObject } from "react"; +import { CHAPTERS } from "../run/story"; +import { scrollReadingRegion } from "./keyboard-scroll"; + +export type StoryMoment="introduction"|"replay"|"lens"|"vane"|"moth"; +export const exchangeBeats={ + lens:["Mochi lifts the lens into place. The beacon finds the bay again.","The Tidekeeper goes still beneath the light.",...CHAPTERS.lens.after.map(line=>`Bram: “${line}”`)], + vane:["The vane catches the breeze.",...CHAPTERS.vane.after.map(line=>`Bram: “${line}”`)], + moth:["The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.",...CHAPTERS.moth.after.map(line=>`Bram: “${line}”`)], +} as const; +const headings={introduction:"Keep Wren’s Light",replay:"Keep Wren’s Light",lens:"Wren’s light",vane:"The light’s keeper",moth:"Two familiars and one light"}; + +export default function StoryPanel({kind,beat,progress,buttons,headingRef,onClose,onHelp,onUseButtons,onContinue}:{ + kind:StoryMoment;beat:number;progress:boolean;buttons:boolean;headingRef:RefObject; + onClose:()=>void;onHelp:()=>void;onUseButtons:()=>void;onContinue:()=>void; +}){ + const introduction=kind==="introduction",replay=kind==="replay"; + const beats=!introduction&&!replay?exchangeBeats[kind]:null; + return <> +

{replay&&progress?"How it began":headings[kind]}

+
+ {replay&&progress?

The storm had taken the beacon’s lens. Mochi was ready to help.

:introduction||replay?<> +

You guide Mochi as a volunteer harbor helper.

+

Bram: “I’m Bram. Wren’s beacon helps the boats find harbor. The storm took its lens. Mochi’s ready to fetch it. Will you guide her?”

+

Mochi looks from the dark beacon to the water, then waits for your lead.

+ :

{beats?.[beat]}

} + {introduction&&buttons&&

Button controls will be open when you sail.

} +
+
{introduction?<> +

Bring the Beacon Lens home from the left shell.

+ + + + :replay?:}
+ ; +} diff --git a/web/src/expedition/World.tsx b/web/src/expedition/World.tsx index 254ba37..810f5b3 100644 --- a/web/src/expedition/World.tsx +++ b/web/src/expedition/World.tsx @@ -47,10 +47,10 @@ export default function World(props:ExpeditionWorldProps){ const refresh=()=>{cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>scene.current?.refreshLayout());}; const observer=new ResizeObserver(refresh); if(mount.current)observer.observe(mount.current); - mount.current?.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback").forEach(element=>observer.observe(element)); + mount.current?.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback,.exp-story-panel").forEach(element=>observer.observe(element)); refresh(); return()=>{cancelAnimationFrame(frame);observer.disconnect();}; - },[ready,!!props.snapshot.court,props.paused]); + },[ready,!!props.snapshot.court,props.paused,props.snapshot.storyStage?.kind,props.snapshot.storyStage?.keeper]); const {passage,court,home}=props.snapshot; let description=court?"Spatial tide court. Swipe or tap the world, or use WASD and arrows. Hints and optional Button controls follow.":"Mochi and Bram at Pocket Harbor. Choose a place using the harbor controls."; if(passage&&court){ @@ -64,5 +64,6 @@ export default function World(props:ExpeditionWorldProps){ if(home.services.includes("reed"))description+=" The Reed skiff is moored on the harbor side."; } if(!court&&home.heardBell)description+=" Bram has rigged the shore bell pull for future crossings."; + if(props.snapshot.storyStage?.keeper)description+=" The Tidekeeper stands still beneath the beacon’s light."; return
; } diff --git a/web/src/expedition/game.css b/web/src/expedition/game.css index d0fbb64..6067543 100644 --- a/web/src/expedition/game.css +++ b/web/src/expedition/game.css @@ -175,6 +175,23 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .exp-panel-body{min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--exp-panel-pad) var(--exp-panel-pad);scrollbar-color:#8b734c var(--exp-card);scrollbar-width:thin;scroll-padding:8px} .exp-panel-body:focus-visible{outline-offset:-3px} .exp-panel-body>.exp-primary{width:100%} +.exp-panel-shade[data-story-stage=true]{align-items:flex-end;justify-content:center;padding:12px max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) max(12px,env(safe-area-inset-left));background:transparent} +.exp-game .exp-story-panel{--exp-panel-pad:20px;width:min(620px,100%);max-height:52dvh;display:flex;flex-direction:column;overflow:hidden;padding:0} +.exp-story-panel .exp-panel-header{padding-bottom:12px} +.exp-story-panel .exp-panel-header>h2{font-size:clamp(24px,5.6vw,30px)} +.exp-story-reading{flex:1;min-height:48px;padding-bottom:8px;touch-action:pan-y} +.exp-story-reading p{line-height:1.5} +.exp-story-reading p:last-child{margin-bottom:8px} +.exp-story-actions{flex:none;display:flex;flex-wrap:wrap;gap:8px;padding:8px var(--exp-panel-pad) var(--exp-panel-pad)} +.exp-game .exp-story-actions>.exp-story-objective{width:100%;margin:0} +.exp-story-actions>.exp-primary{width:100%;min-height:56px} +.exp-story-actions>.exp-secondary{flex:1;min-height:44px} +.exp-story-actions>.exp-text-button{flex:1;min-height:44px} +.exp-game[data-mode=harbor][data-story]>.exp-feedback,.exp-game[data-mode=harbor][data-story]>.exp-mast .exp-place,.exp-game[data-mode=harbor][data-story]>.exp-mast .exp-header-actions,.exp-game[data-mode=harbor][data-story]>.exp-phone-dock{visibility:hidden} +@media(max-height:500px) and (orientation:landscape){ + .exp-panel-shade[data-story-stage=true]{justify-content:flex-end;align-items:center} + .exp-game .exp-story-panel{width:52%;max-height:calc(100dvh - 24px);--exp-panel-pad:16px} +} .exp-panel :focus-visible{outline-color:#2b5f4d;box-shadow:none} .exp-panel-shade:has(.tide-home){justify-content:center} .exp-panel:has(.tide-home){width:min(540px,100%)} diff --git a/web/src/expedition/harbor-controller.test.ts b/web/src/expedition/harbor-controller.test.ts index 1a30f4c..6a30456 100644 --- a/web/src/expedition/harbor-controller.test.ts +++ b/web/src/expedition/harbor-controller.test.ts @@ -45,6 +45,45 @@ test("restore selects no world and preserves existing Mochi, historical saves an expect(f.data.get("familiar.first-light.beacon.v1")).toBe("unchanged-v1-save");expect(f.provisions).toBe(0);expect(f.sent).toEqual([]); f.supported=false;await expect(f.controller.selectSaved()).rejects.toThrow("private preview");expect(f.controller.state.mode).toBe("preview");expect(f.sent).toEqual([]); }); +test("open returns initial restoration completion without blocking local play while it waits",async()=>{ + const f=fixture();let restore!:(value:PlayerBinding)=>void,finishRead!:()=>void,entered!:()=>void; + const reading=new Promise(resolve=>entered=resolve); + f.adapter.restoreSession=()=>new Promise(resolve=>restore=resolve); + f.reads=()=>{entered();return new Promise(resolve=>finishRead=resolve);}; + let complete=false;const opening=f.controller.open();expect(opening).toBeInstanceOf(Promise); + void opening.then(()=>{complete=true;}); + const context=f.controller.runContext(preview);expect(context.authority).toBe("local-preview");f.controller.setActiveRun(context); + expect(complete).toBe(false);restore(binding);await reading; + expect(complete).toBe(false);expect(f.controller.state.snapshot).toBeNull();finishRead();await opening; + expect(complete).toBe(true);expect(f.controller.state.snapshot?.binding).toEqual(binding); + expect(f.controller.state.mode).toBe("preview");expect(f.sent).toEqual([]);expect(f.provisions).toBe(0); +}); +test("StrictMode-style cleanup and reopening ignore the old restoration generation",async()=>{ + const f=fixture(),resolves:((value:PlayerBinding)=>void)[]=[]; + f.adapter.restoreSession=()=>new Promise(resolve=>resolves.push(resolve)); + const first=f.controller.open();f.controller.close();const current=f.controller.open(); + resolves[0]!(binding);await first; + expect(f.controller.state.binding).toBeNull();expect(f.controller.state.snapshot).toBeNull(); + resolves[1]!(binding);await current; + expect(f.controller.state.binding).toEqual(binding);expect(f.sent).toEqual([]); +}); +test("a replaced controller cannot settle or restore its replacement",async()=>{ + const old=fixture(),replacement=fixture();let finishOld!:(value:PlayerBinding)=>void,finishReplacement!:(value:PlayerBinding)=>void; + old.adapter.restoreSession=()=>new Promise(resolve=>finishOld=resolve); + replacement.adapter.restoreSession=()=>new Promise(resolve=>finishReplacement=resolve); + const first=old.controller.open();old.controller.close();let replacementComplete=false; + const current=replacement.controller.open();void current.then(()=>{replacementComplete=true;}); + finishOld(binding);await first; + expect(replacementComplete).toBe(false);expect(replacement.controller.state.binding).toBeNull();expect(old.controller.state.binding).toBeNull(); + finishReplacement(binding);await current;expect(replacementComplete).toBe(true);expect(replacement.controller.state.binding).toEqual(binding); +}); +test("unconfigured and failed initial restoration settle without changing authority",async()=>{ + const local=new HarborController(null,{getItem:()=>null,setItem:()=>{}}); + expect(local.open()).toBeInstanceOf(Promise);await local.open();expect(local.state.mode).toBe("preview"); + const f=fixture();f.adapter.restoreSession=async()=>{throw Error("offline");}; + await f.controller.open();expect(f.controller.state.binding).toBeNull();expect(f.controller.state.mode).toBe("preview"); + expect(f.controller.state.message).toBe("Sign in with the same identity to check the saved harbor.");expect(f.sent).toEqual([]); +}); test("waiting for sign-in does not block a local outing or merge it into a remembered saved harbor",async()=>{ const f=fixture();let release!:(binding:PlayerBinding)=>void; f.adapter.authenticate=()=>new Promise(resolve=>release=resolve); diff --git a/web/src/expedition/harbor-controller.ts b/web/src/expedition/harbor-controller.ts index 05c8735..7e23d5d 100644 --- a/web/src/expedition/harbor-controller.ts +++ b/web/src/expedition/harbor-controller.ts @@ -41,7 +41,7 @@ export class HarborController implements HarborSession { this.value=value;for(const listener of this.listeners)listener(); } private guard(epoch:number,binding?:PlayerBinding) {check(this.live&&epoch===this.epoch&&(!binding||bindingMatches(this.value.binding,binding)),"The signed-in harbor changed. Its original request and return are preserved.");} - open(){this.live=true;void this.restore();} + open(){this.live=true;return this.restore();} close(){this.live=false;this.epoch++;this.prepared=null;this.update({binding:null,snapshot:null,review:null,busy:false,mode:"preview"});} private context(snapshot:ChainSnapshot):RunContext { check(this.connection&&snapshot.pets[0],"Bring Mochi home before starting a saved expedition."); diff --git a/web/src/expedition/harbor-session.tsx b/web/src/expedition/harbor-session.tsx index 4941d00..313a3cd 100644 --- a/web/src/expedition/harbor-session.tsx +++ b/web/src/expedition/harbor-session.tsx @@ -15,12 +15,18 @@ const browserStore:Storage={ getItem:key=>globalThis.localStorage.getItem(key),setItem:(key,value)=>globalThis.localStorage.setItem(key,value),removeItem:key=>globalThis.localStorage.removeItem(key), clear:()=>{throw Error("Clearing game storage is unavailable.");},key:index=>globalThis.localStorage.key(index),get length(){return globalThis.localStorage.length;}, }; -type Children=ReactNode|((session:HarborSession)=>ReactNode); +type Children=ReactNode|((session:HarborSession,initialRestorationComplete:boolean)=>ReactNode); export function HarborSessionProvider({connection,children,storage=browserStore}:{connection:AccountConnection|HarborConnection|null;children:Children;storage?:Pick}) { const controller=useMemo(()=>new HarborController(connection&&("client"in connection?connection:{adapter:connection.adapter,client:new TideboundClient(connection.adapter.accountRoot,`items.${connection.adapter.accountRoot}`,connection.provider,connection.adapter,storage),accountExists:async accountId=>{await connection.provider.viewAccount({accountId,blockQuery:{finality:"final"}});}}),storage),[connection,storage]); + const [restored,setRestored]=useState(null); useSyncExternalStore(controller.subscribe,()=>controller.state); - useEffect(()=>{controller.open();return()=>controller.close();},[controller]); - return {typeof children==="function"?children(controller):children}; + useEffect(()=>{ + let current=true; + setRestored(null); + void controller.open().then(()=>{if(current)setRestored(controller);},()=>{if(current)setRestored(controller);}); + return()=>{current=false;controller.close();}; + },[controller]); + return {typeof children==="function"?children(controller,restored===controller):children}; } export function useHarborSession():HarborSession { const controller=useContext(Context);if(!controller)throw Error("The game needs one persistent HarborSessionProvider."); diff --git a/web/src/expedition/onboarding.test.ts b/web/src/expedition/onboarding.test.ts new file mode 100644 index 0000000..017f3da --- /dev/null +++ b/web/src/expedition/onboarding.test.ts @@ -0,0 +1,71 @@ +import {expect,test} from "bun:test"; +import {emptyBook,readBook} from "../run/save"; +import {startTide} from "../run/engine"; +import {emptyPassageHome,readPassageHome} from "./passage-save"; +import {decodeReturnRecord,ReturnRecords,returnRecordKey} from "./return-record"; +import {hasPristineDeviceHistory,isPristineHarbor,pristineDeviceHarbor} from "./onboarding"; + +const fresh=()=>({home:{banked:[],lit:false,signaled:false,lantern:null},active:null,last:null}); +const legacyKeys=["familiar.tide.log.v1:preview","familiar.season.tide.v1:preview","familiar.tide.pending.v1:preview"]; +function storage(entries:Iterable=[]){ + const bytes=new Map(entries),writes:string[]=[]; + return {bytes,writes,getItem:(key:string)=>bytes.get(key)??null,setItem:(key:string,value:string)=>{writes.push(key);bytes.set(key,value);}}; +} + +test("a pristine device requires verified empty histories, independently of the guidance preference",()=>{ + const store=storage([["familiar.guidance.keep-wrens-light.v1",'{"version":1,"intro":null,"buttons":true}']]); + expect(pristineDeviceHarbor(fresh(),emptyBook(),emptyPassageHome(),{ok:true,records:[]},store)).toBe(true); + for(const key of legacyKeys)store.bytes.set(key,key.includes("pending")?"null":"[]"); + expect(hasPristineDeviceHistory(store)).toBe(true);expect(store.writes).toEqual([]); +}); + +test("all earned, active and completed outing states suppress automatic introduction",()=>{ + const save=fresh(),book=emptyBook(),passage=emptyPassageHome(); + expect(isPristineHarbor(save,book,passage)).toBe(true); + for(const home of [{banked:["lens"]},{lit:true},{signaled:true},{lantern:{motif:"crest",socket:"porch"}}]){ + expect(isPristineHarbor({...save,home:{...save.home,...home}} as Parameters[0],book,passage)).toBe(false); + } + expect(isPristineHarbor({...save,active:{}},book,passage)).toBe(false); + expect(isPristineHarbor({...save,last:{}},book,passage)).toBe(false); + expect(isPristineHarbor(save,{...book,active:startTide({seed:5,story:"lens"})},passage)).toBe(false); + expect(isPristineHarbor(save,{...book,days:[startTide({seed:5})]},passage)).toBe(false); + for(const progress of [{services:["bell"]},{watchedReeds:true},{heardBell:true},{active:{}}]){ + expect(isPristineHarbor(save,book,{...passage,...progress} as Parameters[2])).toBe(false); + } + expect(pristineDeviceHarbor(save,book,passage,{ok:false,records:[]},storage())).toBe(false); + const record=decodeReturnRecord({schemaVersion:1,id:"onboarding-test",operationId:"return:onboarding-test",contentVersion:"first_light_v2",context:{authority:"local-preview",banked:[],lit:false,signaled:false},area:"beacon",tool:"rope",banked:[],commands:["return"],outcome:"returned",cargo:[],disposition:"private-memory"}); + expect(pristineDeviceHarbor(save,book,passage,{ok:true,records:[record]},storage())).toBe(false); +}); + +test("corrupt and nonempty legacy histories cannot masquerade as empty and retain their original bytes",()=>{ + for(const key of legacyKeys){ + const cases=key.includes("pending")?["", "{", "[]", "{}", '{"day":12,"late":false}']:["", "{", "null", "{}", "[null]", "[{}]"]; + for(const raw of cases){ + const store=storage([[key,raw]]); + expect(pristineDeviceHarbor(fresh(),emptyBook(),emptyPassageHome(),{ok:true,records:[]},store)).toBe(false); + expect(store.bytes.get(key)).toBe(raw);expect(store.writes).toEqual([]); + } + } +}); + +test("an unreadable legacy history suppresses introduction without a write",()=>{ + for(const key of legacyKeys){ + let writes=0;const store={getItem:(candidate:string)=>{if(candidate===key)throw Error("blocked");return null;},setItem:()=>{writes++;}}; + expect(hasPristineDeviceHistory(store)).toBe(false);expect(writes).toBe(0); + } +}); + +test("strict return, TideBook and passage reads reject corrupt or unreadable records without repairing bytes",()=>{ + const context={authority:"local-preview" as const,banked:[],lit:false,signaled:false}; + const readers:[string,(store:ReturnType)=>unknown][]=[ + [returnRecordKey(context),store=>new ReturnRecords(store).read(context)], + ["familiar.expedition.local.v2:tide-run.v1",store=>readBook(store,"familiar.expedition.local.v2:tide-run.v1")], + ["familiar.expedition.local.v2:shore-passages.v1",store=>readPassageHome(store,"familiar.expedition.local.v2:shore-passages.v1")], + ]; + for(const [key,read] of readers){ + for(const raw of ["", "{", "{}", "[null]"]){ + const store=storage([[key,raw]]);expect(()=>read(store)).toThrow();expect(store.bytes.get(key)).toBe(raw);expect(store.writes).toEqual([]); + } + const blocked=storage();blocked.getItem=()=>{throw Error("blocked");};expect(()=>read(blocked)).toThrow("blocked");expect(blocked.writes).toEqual([]); + } +}); diff --git a/web/src/expedition/onboarding.ts b/web/src/expedition/onboarding.ts new file mode 100644 index 0000000..9953352 --- /dev/null +++ b/web/src/expedition/onboarding.ts @@ -0,0 +1,33 @@ +import type { TideBook } from "../run/save"; +import type { HomeCheckpoint } from "./harbor-port"; +import type { PassageHome } from "./passage-save"; +import type { ReturnRecord } from "./return-record"; + +type DeviceSave = { + home: HomeCheckpoint & { lantern: unknown | null }; + active: unknown | null; + last: unknown | null; +}; + +export function isPristineHarbor(save:DeviceSave,book:TideBook,passage:PassageHome):boolean { + return save.home.banked.length===0&&!save.home.lit&&!save.home.signaled&&save.home.lantern===null&& + save.active===null&&save.last===null&&book.active===null&&book.days.length===0&& + passage.active===null&&passage.services.length===0&&!passage.watchedReeds&&!passage.heardBell; +} + +/** Legacy readers discard invalid entries; only verified absence or actual emptiness establishes freshness. */ +export function hasPristineDeviceHistory(storage?:Pick):boolean { + try { + const store=storage??globalThis.localStorage; + for(const key of ["familiar.tide.log.v1:preview","familiar.season.tide.v1:preview"]){ + const raw=store.getItem(key); + if(raw!==null){const value:unknown=JSON.parse(raw);if(!Array.isArray(value)||value.length!==0)return false;} + } + const pending=store.getItem("familiar.tide.pending.v1:preview"); + return pending===null||JSON.parse(pending)===null; + }catch{return false;} +} + +export function pristineDeviceHarbor(save:DeviceSave,book:TideBook,passage:PassageHome,returns:{ok:boolean;records:readonly ReturnRecord[]},storage?:Pick):boolean { + return returns.ok&&returns.records.length===0&&isPristineHarbor(save,book,passage)&&hasPristineDeviceHistory(storage); +} diff --git a/web/src/expedition/scene.ts b/web/src/expedition/scene.ts index 1d81072..09dba6c 100644 --- a/web/src/expedition/scene.ts +++ b/web/src/expedition/scene.ts @@ -14,7 +14,7 @@ export type WorldAction="wait"|"return"|"turn:vane"|"lantern"|"ride"|"listen"|"r export interface ActionAnchor {action:WorldAction;x:number;y:number;width:number;height:number} export type PassageView=Pick&{rode?:boolean;listened?:boolean;rang?:boolean;pullSpent?:boolean}; export interface HarborView { lit:boolean; signaled:boolean; moth:boolean; lantern:boolean; socket:"porch"|"dock";motif:"crest"|"moth";polished:boolean;relic:"lens"|"vane"|null;resting?:boolean;services?:readonly PassageJob[];watchedReeds?:boolean;heardBell?:boolean;greeting?:number } -export interface WorldSnapshot { court:CourtState|null; home:HarborView; reducedMotion:boolean;previewCommand:Command|null;previewWave?:{source:Column;exit:Column};passage?:PassageView|null;worldActions?:readonly WorldAction[] } +export interface WorldSnapshot { court:CourtState|null; home:HarborView; reducedMotion:boolean;previewCommand:Command|null;previewWave?:{source:Column;exit:Column};passage?:PassageView|null;worldActions?:readonly WorldAction[];storyStage?:{kind:"introduction"|"replay"|"lens"|"vane"|"moth";keeper:boolean} } export interface WorldHooks { command:(command:Command)=>void; target:(position:Position)=>void; @@ -190,7 +190,7 @@ export class ExpeditionScene extends Phaser.Scene { if(this.snapshot.reducedMotion)this.pose(companionIdle(0,this.attention(),true).pose); } update(_time:number,delta:number){ - if(!this.actor||this.playing||this.gated||this.stopped||this.snapshot.reducedMotion||document.hidden)return; + if(!this.actor||this.playing||this.gated||this.stopped||this.snapshot.storyStage||this.snapshot.reducedMotion||document.hidden)return; this.idleElapsed+=Math.min(delta,100); const idle=companionIdle(this.idleElapsed,this.attention(),false); if(this.idleElapsed>1200)this.pose(idle.pose); @@ -580,7 +580,10 @@ export class ExpeditionScene extends Phaser.Scene { private harbor(){ const portrait=this.w<=900&&this.h>this.w; const landscape=!portrait&&this.h<=500; - const groundY=portrait?Math.max(230,this.h-522):landscape?this.h*.60:this.h*.81; + const stage=this.snapshot.storyStage; + const panel=this.game.canvas.closest(".exp-game")?.querySelector(".exp-story-panel"); + const panelTop=panel?.getBoundingClientRect().top??this.h*.48; + const groundY=stage?landscape?this.h-36:Math.max(180,panelTop-30):portrait?Math.max(230,this.h-522):landscape?this.h*.60:this.h*.81; const source=this.textures.get("exp-island").getSourceImage() as HTMLImageElement; const landing=(x:number,y:number,width:number)=>{ const pier=this.add.image(x,y,"exp-island").setOrigin(.5,.41).setDisplaySize(width,width*source.height/source.width).setDepth(1);this.surfaces.push(pier); @@ -593,10 +596,17 @@ export class ExpeditionScene extends Phaser.Scene { landing(this.w*.40,groundY,this.w*.92); landing(this.w*.50,this.h-444,this.w*1.18); } + if(stage){ + const lanternX=this.w*(landscape?.34:.76),lanternY=landscape?this.h*.33:Math.max(110,Math.min(180,groundY*.48)); + this.backdrop.x=lanternX-this.backdrop.displayWidth*(.824-.5); + this.backdrop.y=lanternY-this.backdrop.displayHeight*(.222-.5); + } if(landscape){landing(this.w*.40,groundY,this.w*.55);landing(this.w-224,this.h-146,440);} const actorSize=Math.min(180,this.w*.28,this.h*.25); - this.actor.setPosition(this.w*(landscape?.43:.49),groundY).setDisplaySize(actorSize,actorSize);this.pose(this.snapshot.home.lit?"relieved":"curious");this.actorShadow.setPosition(this.actor.x,this.actor.y).setSize(actorSize*.5,14); - const b=Math.min(255,this.w*.36,this.h*.38);this.bram.setFlipX(false).setPosition(this.w*(landscape?.23:.28),portrait?groundY-4:landscape?this.h*.59:this.h*.82).setDisplaySize(b*.75,b); + this.actor.setPosition(this.w*(stage&&landscape?.24:landscape?.43:.49),groundY).setDisplaySize(actorSize,actorSize);this.pose(this.snapshot.home.lit?"relieved":"curious");this.actorShadow.setPosition(this.actor.x,this.actor.y).setSize(actorSize*.5,14); + const b=Math.min(255,this.w*.36,this.h*.38);this.bram.setFlipX(false).setPosition(this.w*(stage&&landscape?.10:landscape?.23:.28),stage?groundY-4:portrait?groundY-4:landscape?this.h*.59:this.h*.82).setDisplaySize(b*.75,b); + this.keeper.setVisible(!!stage?.keeper); + if(stage?.keeper){const height=Math.min(100,this.w*.23,this.h*.20);this.keeper.setPosition(this.w*(landscape?.40:.78),groundY-4).setDisplaySize(height*1.32,height).setAngle(0);} const services=this.snapshot.home.services; if(services?.includes("bell")){ const landing=this.homeProps,w=Math.min(27,actorSize*.18); @@ -681,7 +691,11 @@ export class ExpeditionScene extends Phaser.Scene { const root=this.game.canvas.closest(".exp-game"); for(const [place,point] of Object.entries(signs))for(const axis of ["x","y"] as const)root?.style.setProperty(`--exp-anchor-${place}-${axis}`,`${point[axis]}px`); for(const axis of ["x","y"] as const)root?.style.setProperty(`--exp-anchor-mochi-${axis}`,`${landmarks.mochi[axis]}px`); - if(this.game.canvas.parentElement)this.game.canvas.parentElement.dataset.harborAnchors=JSON.stringify({landmarks,signs}); + if(this.game.canvas.parentElement){ + const bounds=(object:Phaser.GameObjects.Image|Phaser.GameObjects.Sprite)=>{const b=object.getBounds();return{x:b.x,y:b.y,width:b.width,height:b.height};}; + const light=painted(.824,.222),width=this.backdrop.displayWidth,height=this.backdrop.displayHeight; + this.game.canvas.parentElement.dataset.harborAnchors=JSON.stringify({landmarks,signs,story:stage?{bram:bounds(this.bram),mochi:bounds(this.actor),lanternRoom:{x:light.x-width*.057,y:light.y-height*.055,width:width*.114,height:height*.11},...(stage.keeper?{keeper:bounds(this.keeper)}:{})}:null}); + } } private addHomeFind(item:Find,x:number,y:number,size:number){const image=this.add.image(x,y,`exp-${item}`).setDisplaySize(size,size).setDepth(item==="vane"?11:7);this.cargo.push(image);} private async tween(targets:object,config:Omit,duration:number){ diff --git a/web/src/main.tsx b/web/src/main.tsx index f6ee139..12b86a5 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -17,7 +17,7 @@ async function entry() { // `?play` skips the title screen (browser tests and direct links into play). if(new URLSearchParams(window.location.search).has("play")){ const [{default:Game},{HarborSessionBoundary,HarborAccountPanel}]=await game; - return function Expedition(){return {session=>}/>};}; + return function Expedition(){return {(session,initialRestorationComplete)=>}/>};}; } const [{default:Opening},{HarborAudio}]=await Promise.all([import("./opening/Opening"),import("./expedition/audio")]); game.catch(()=>{}); @@ -31,7 +31,7 @@ async function entry() { let screen:React.ReactNode=null; if(play){ const [{default:Game},{HarborSessionBoundary,HarborAccountPanel}]=play.mods; - screen={session=>} audio={audio} initialSound={play.start.sound} initialMix={[play.start.music,play.start.effects]}/>}; + screen={(session,initialRestorationComplete)=>} audio={audio} initialSound={play.start.sound} initialMix={[play.start.music,play.start.effects]}/>}; } return <> {screen} diff --git a/web/src/run/TideRunGame.test.tsx b/web/src/run/TideRunGame.test.tsx index 2c6c580..d1c3191 100644 --- a/web/src/run/TideRunGame.test.tsx +++ b/web/src/run/TideRunGame.test.tsx @@ -4,11 +4,11 @@ import TideRunGame, { TideRunRules } from "./TideRunGame"; import { applyMove, startTide, type TideState } from "./engine"; import { CHAPTERS, itemName, storyStart } from "./story"; -function render(initial: TideState, blocked = false) { +function render(initial: TideState, blocked = false, preferences: { guidance?: boolean; buttonsOpen?: boolean } = {}) { const document = Object.getOwnPropertyDescriptor(globalThis, "document"), onFinish = mock(() => true); Object.defineProperty(globalThis, "document", { configurable: true, value: { hidden: false } }); try { - const html = renderToStaticMarkup( true} onFinish={onFinish} onLeave={() => {}} onToggleSound={() => {}}/>); return { html, onFinish }; } finally { @@ -102,9 +102,33 @@ test("chapter briefings are narration without inventing Bram dialogue", () => { }); test("the named objective remains visible beside last-wave advice", () => { - const { html } = render({ ...startTide(storyStart("lens")), wave: 7, beat: 21 }); + const { html } = render({ ...startTide(storyStart("lens")), wave: 7, beat: 21, pack: ["reed"] }); expect(html).toContain(CHAPTERS.lens.goal); - expect(html).toContain("The last wave. Get to the dock."); + expect(html).toContain("Last wave. Bank what you can at the center dock."); +}); + +test("guidance starts with one dismissible movement cue and never replays it for a resumed trace", () => { + const initial = startTide(storyStart("lens")), line = "Swipe on the board, or tap a glowing neighboring stone. Mochi moves one step at a time."; + const guided = render(initial, false, { guidance: true }).html; + expect(guided.split(line)).toHaveLength(2); + expect(guided).toContain("Dismiss cue"); + expect(guided).toContain(CHAPTERS.lens.goal); + expect(render(initial).html).not.toContain(line); + const resumed = applyMove(initial, "wait")!.after; + expect(render(resumed, false, { guidance: true }).html).not.toContain(line); + const banked = render({ ...resumed, banked: ["lens"] }, false, { guidance: true }).html; + expect(banked).not.toContain('data-testid="tide-lens-decision"'); + expect(banked).toContain('data-testid="tide-finish-return"'); +}); + +test("remembered button controls open without changing the outing", () => { + const initial = startTide(storyStart("lens")), before = JSON.stringify(initial); + const { html } = render(initial, false, { buttonsOpen: true, guidance: true }); + expect(html).toContain('
'); + expect(html).toContain('data-buttons-open="true"'); + expect(html).toContain('aria-label="Guide Mochi" tabindex="0"'); + expect(html).toContain('aria-label="Wait one move"'); + expect(JSON.stringify(initial)).toBe(before); }); test("shared Tide Run rules explain timing, cargo and activity length", () => { diff --git a/web/src/run/TideRunGame.tsx b/web/src/run/TideRunGame.tsx index 5376d4c..2f7a510 100644 --- a/web/src/run/TideRunGame.tsx +++ b/web/src/run/TideRunGame.tsx @@ -6,6 +6,7 @@ import type { TideSnapshot } from "./scene"; import { HEARTS, PACK_SLOTS, SLOTS, applyMove, countdown, legalMoves, stepDestination, tideShape, type Move, type Position, type StoryPrize, type TideEvent, type TideState, type TideTransition } from "./engine"; import { bramsGuess } from "./bot"; import { CHAPTERS, aPrize, consequence, itemName, laneNames } from "./story"; +import { DISTANT_CUE, INITIAL_CUE, LENS_SAFE_CUE, observeTransition, observedLessons, retainedCue, returnAdvice } from "./guidance"; import { STAMPS } from "../tide/run-day"; import type { HarborAudio } from "../expedition/audio"; import type { CourtEvent } from "../expedition/types"; @@ -22,6 +23,10 @@ interface Props { /** Back to the harbor with the tide still in progress and saved. */ onLeave: () => void; onToggleSound: () => void; + guidance?: boolean; + buttonsOpen?: boolean; + onButtonsOpenChange?: (open: boolean) => void; + onSkipGuidance?: () => void; } const STEPS = ["north", "west", "east", "south"] as const; @@ -84,18 +89,25 @@ export function TideRunRules({ story }: { story?: StoryPrize }) { ; } -export default function TideRunGame({ initial, reduced, sound: soundOn, audio, blocked, onSave, onFinish, onLeave, onToggleSound }: Props) { +export default function TideRunGame({ initial, reduced, sound: soundOn, audio, blocked, onSave, onFinish, onLeave, onToggleSound, guidance = false, buttonsOpen, onButtonsOpenChange, onSkipGuidance }: Props) { const [state, setState] = useState(initial), [result, setResult] = useState(null); const current = useRef(initial), pending = useRef(null), serial = useRef(0); const [ready, setReady] = useState(false), [fault, setFault] = useState(""), [sceneKey, setSceneKey] = useState(0); const [away, setAway] = useState(document.hidden), [guide, setGuide] = useState(false); const [finishError, setFinishError] = useState(false); + const [cue, setCue] = useState(() => guidance && initial.outcome === "active" && !initial.moves.length ? INITIAL_CUE : null); + const lessons = useRef(observedLessons(initial)), acceptedLesson = useRef | null>(null); + const [lensDecision, setLensDecision] = useState(false), [localButtonsOpen, setLocalButtonsOpen] = useState(false); + const [guidanceOff, setGuidanceOff] = useState(false); + const teaching = guidance && !guidanceOff; + const openButtons = buttonsOpen ?? localButtonsOpen; + const decisionDialog = useRef(null), decisionHeading = useRef(null); const finishAttempted = useRef(false), filed = useRef(false), explicitFinish = useRef(false); const chapter = initial.story ? CHAPTERS[initial.story] : null; const [notice, setNotice] = useState(() => initial.outcome !== "active" || initial.moves.length ? "" : chapter ? chapter.before : `The Tidekeeper turns to the ${laneNames(initial.next.lanes).toLowerCase()} lane.`); const dialog = useRef(null), guideButton = useRef(null), gameRef = useRef(null), guideOpener = useRef(null); const guess = useMemo(() => initial.story ? null : bramsGuess(initial.seed), [initial.seed, initial.story]); - const busy = !!result, paused = away || blocked || guide || !!fault; + const busy = !!result, paused = away || blocked || guide || lensDecision || !!fault; // The board catches up before the numbers do: the status shows the tide as drawn. const seen = result ? result.before : state, over = state.outcome !== "active" && !busy; const { waves } = tideShape(initial), legal = legalMoves(state); @@ -103,6 +115,13 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b const worldActions = useMemo(() => legalMoves(state).filter((move): move is "wait" | "home" => move === "wait" || move === "home" && state.moves.length > 0), [state]); const snapshot = useMemo(() => ({ tide: state, reducedMotion: reduced, worldActions }), [state, reduced, worldActions]); + useEffect(() => { setGuidanceOff(false); if (!guidance) { setCue(null); setLensDecision(false); } }, [guidance]); + useEffect(() => { + if (!lensDecision) return; + decisionDialog.current?.showModal(); decisionHeading.current?.focus({ preventScroll: true }); + return () => { decisionDialog.current?.close(); gameRef.current?.focus({ preventScroll: true }); }; + }, [lensDecision]); + useEffect(() => { const hide = () => setAway(true), show = () => setAway(document.hidden); document.addEventListener("visibilitychange", show); window.addEventListener("blur", hide); window.addEventListener("focus", show); @@ -126,11 +145,13 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b setGuide(true); } - function take(move: Move) { - if (!ready || paused || pending.current || current.current.outcome !== "active" || document.hidden) return; + function take(move: Move, fromDecision = false) { + if (!ready || away || blocked || guide || !!fault || lensDecision && !fromDecision || pending.current || current.current.outcome !== "active" || document.hidden) return; const next = applyMove(current.current, move); if (!next) return; - if (!onSave(next.after)) { setNotice("This move could not be saved. Try it again when this browser can save."); return; } + if (!onSave(next.after)) { setCue(null); setNotice("This move could not be saved. Try it again when this browser can save."); return; } + acceptedLesson.current = observeTransition(next, lessons.current); + lessons.current = acceptedLesson.current.observed; current.current = next.after; pending.current = next; serial.current++; setResult(next); setState(next.after); } @@ -144,10 +165,23 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b // The last thing that happened stays up until something else does. const line = consequence(accepted); if (line) setNotice(line); + const lesson = acceptedLesson.current; + if (teaching && lesson && accepted.after.outcome === "active") { + setCue(previous => lesson.cue ?? retainedCue(previous, accepted)); + if (lesson.lensBanked) { setCue(null); setLensDecision(true); } + } else setCue(null); + acceptedLesson.current = null; if (accepted.after.moves.at(-1) === "home") explicitFinish.current = true; pending.current = null; setResult(null); } - function target(position: Position) { const move = moveToward(current.current, position); if (move) take(move); } + function target(position: Position) { + if (!ready || paused || pending.current || current.current.outcome !== "active") return; + if (same(position, current.current.position)) return; + const move = moveToward(current.current, position); + if (move) take(move); else { if (teaching) setCue(DISTANT_CUE); else setNotice(DISTANT_CUE); } + } + function skipGuidance() { setGuidanceOff(true); setCue(null); setLensDecision(false); onSkipGuidance?.(); } + function gather() { setLensDecision(false); gameRef.current?.focus({ preventScroll: true }); } function finish(again: boolean) { if (current.current.outcome === "active" || pending.current || (!ready && !current.current.story) || blocked || filed.current) return; finishAttempted.current = true; @@ -164,9 +198,10 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b }, [state.story, over, ready, blocked, onFinish]); useEffect(() => { function keys(event: KeyboardEvent) { - if (event.isComposing || event.repeat || event.metaKey || event.ctrlKey || event.altKey || guide || current.current.outcome !== "active") return; + if (event.defaultPrevented || event.isComposing || event.repeat || event.metaKey || event.ctrlKey || event.altKey || guide || current.current.outcome !== "active") return; const target = event.target instanceof Element ? event.target : null; if (!target || !gameRef.current?.contains(target) || !gameRef.current.contains(document.activeElement)) return; + if (event.key === "Escape" && cue) { event.preventDefault(); setCue(null); return; } if (target.closest("button,a,summary,input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist],.exp-input-reading")) return; const key = event.key.toLowerCase(), move = KEYS[key]; if (!move && key !== "i") return; @@ -179,15 +214,15 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b const prizeHome = !!state.story && state.banked.includes(state.story); const prizeSafety = seen.story && (seen.banked.includes(seen.story) ? "safe" : seen.pack.includes(seen.story) ? "carried" : null); const prizeLabel = seen.story === "lens" ? "Lens" : seen.story === "vane" ? "Vane" : "Moth"; - const lastWave = state.outcome === "active" && state.wave === waves - 1; + const advice = returnAdvice(seen); const title = state.outcome === "rescued" ? "Bram wades out for Mochi." : state.outcome === "turned" ? "The tide turns." : "Home for the day."; const lockControls = !ready || paused || busy; - const feedback =
{notice}
; + const feedback =
{cue ?? notice}
; return
{ if (event.target instanceof HTMLCanvasElement) gameRef.current?.focus({ preventScroll: true }); }} className="exp-game passage-game tide-run" data-mode="court" data-testid="tide-run" data-story={state.story} data-seed={state.seed} data-beat={state.beat} data-wave={state.wave} - data-outcome={state.outcome} data-busy={busy} data-score={state.score} data-hearts={state.hearts}> + data-outcome={state.outcome} data-busy={busy} data-score={state.score} data-hearts={state.hearts} data-buttons-open={openButtons}> setReady(true)} onFault={message => { setFault(message); setReady(false); pending.current = null; setResult(null); }} + onReady={() => setReady(true)} onFault={message => { setFault(message); setReady(false); pending.current = null; acceptedLesson.current = null; setResult(null); setCue(null); setNotice(""); }} onBeat={beat} onSettled={settle} onTarget={target} onMove={take} onInspect={openGuide} />
familiar.Played and saved on this device

{chapter ? chapter.title : "Today’s Tide Run"}

@@ -219,7 +254,7 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b {state.story && !prizeHome && }
} - {!over &&
+ {!over &&
{guess !== null &&
    {STAMPS.map(stamp => { const status = stamp.key === "home" ? (seen.score > 0 ? "kept" : undefined) : stamp.key === "guess" ? (seen.score >= guess ? "kept" : undefined) @@ -236,13 +271,14 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b
    {chapter &&

    {chapter.goal}

    } - {lastWave &&

    The last wave. Get to the dock.

    } + {advice &&

    {advice}

    }

    {icon(WAVE)}{state.outcome === "active" ? forecast(seen.outcome === "active" ? seen : state) : ""}

    Mochi is at {where(seen.position)}. The bridge is at the {LANES[seen.bridge]} lane. {feedback} + {cue && }

    Step onto the center dock to bank cargo. Banking keeps the outing open.

    Pause returns you to the harbor with this outing still open.

    -
    } id="tide-input-hints" context={worldActions.includes("home") ? "Tap Finish to end the outing · tap Wait." : "Tap Wait · prizes collect as you step."} keyboardContext="Space waits · R finishes at the dock · I opens the guide"> + } id="tide-input-hints" buttonsOpen={openButtons} onButtonsOpenChange={open => { setLocalButtonsOpen(open); onButtonsOpenChange?.(open); }} context={worldActions.includes("home") ? "Tap Finish to end the outing · tap Wait." : "Tap Wait · prizes collect as you step."} keyboardContext="Space waits · R finishes at the dock · I opens the guide">
    {STEPS.map(move => )} @@ -256,6 +292,16 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b {guide && { event.preventDefault(); setGuide(false); }}>

    How Tide Run works

    + {teaching && } +
    } + {lensDecision && { event.preventDefault(); gather(); }}> +

    Lens safe

    +

    {LENS_SAFE_CUE}

    +
    + + + +
    }
; } diff --git a/web/src/run/TideWorld.tsx b/web/src/run/TideWorld.tsx index ac09f3a..423f3b7 100644 --- a/web/src/run/TideWorld.tsx +++ b/web/src/run/TideWorld.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { countdown, type Move, type Position, type TideEvent, type TideTransition } from "./engine"; import { itemName, laneNames } from "./story"; -import type { TideScene, TideSnapshot, TideTile, TideActionAnchor } from "./scene"; +import type { TideScene, TideSnapshot, TideTile, TideActionAnchor, TideActorBounds } from "./scene"; export interface TideWorldProps { snapshot: TideSnapshot; @@ -20,6 +20,7 @@ export interface TideWorldProps { export default function TideWorld(props: TideWorldProps) { const mount = useRef(null), scene = useRef(null), current = useRef(props); const [ready, setReady] = useState(false),[tiles,setTiles]=useState([]),[actions,setActions]=useState([]); + const [actor,setActor]=useState(null); current.current = props; useEffect(() => { let alive = true, game: import("phaser").Game | undefined; @@ -29,7 +30,7 @@ export default function TideWorld(props: TideWorldProps) { const next = new TideScene(current.current.snapshot, { target: position => current.current.onTarget(position), move:move=>current.current.onMove(move),inspect:()=>current.current.onInspect(), - geometry:(tiles,actions)=>{if(alive){setTiles(tiles);setActions(actions);}}, + geometry:(tiles,actions,actor)=>{if(alive){setTiles(tiles);setActions(actions);setActor(actor);}}, ready: () => { if (!alive) return; setReady(true); current.current.onReady(); next.setGated(current.current.paused); }, fault: message => { if (alive) current.current.onFault(message); }, beat: event => { if (alive) current.current.onBeat(event); }, @@ -50,12 +51,14 @@ export default function TideWorld(props: TideWorldProps) { const refresh=()=>{cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>scene.current?.refreshLayout());}; const observer=new ResizeObserver(refresh); if(mount.current)observer.observe(mount.current); - mount.current?.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback").forEach(element=>observer.observe(element)); + const root=mount.current?.closest(".exp-game"); + root?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback,.exp-button-controls,.exp-button-controls-body").forEach(element=>observer.observe(element)); + root?.addEventListener("toggle",refresh,true); refresh(); - return()=>{cancelAnimationFrame(frame);observer.disconnect();}; + return()=>{cancelAnimationFrame(frame);observer.disconnect();root?.removeEventListener("toggle",refresh,true);}; },[ready,props.paused]); const { tide } = props.snapshot; const coming = tide.outcome === "active" ? ` The next wave takes ${laneNames(tide.next.lanes)} in ${countdown(tide)}${tide.next.drops.length ? ` and leaves ${tide.next.drops.map(drop => itemName(drop.kind)).join(" and ")}` : ""}.` : ""; - return
; } diff --git a/web/src/run/guidance.test.ts b/web/src/run/guidance.test.ts new file mode 100644 index 0000000..fc6b730 --- /dev/null +++ b/web/src/run/guidance.test.ts @@ -0,0 +1,170 @@ +import { expect, test } from "bun:test"; +import { VALUE, applyMove, replayTide, startTide, type Move, type TideStart, type TideTransition } from "./engine"; +import { cautiousMove } from "./bot"; +import { consequence, storyStart } from "./story"; +import { GUIDANCE_KEY, INITIAL_CUE, LENS_SAFE_CUE, guidanceEnabled, observeTransition, observedLessons, readGuidance, retainedCue, returnAdvice, writeGuidance, type GuidancePreferences } from "./guidance"; + +const defaults: GuidancePreferences = { version: 1, intro: null, buttons: false }; +function memory() { + const data = new Map(); + return { data, getItem: (key: string) => data.get(key) ?? null, setItem: (key: string, value: string) => { data.set(key, value); } }; +} +function last(start: TideStart, moves: readonly Move[]): TideTransition { + const before = replayTide(start, moves.slice(0, -1)); + expect(before).not.toBeNull(); + const transition = applyMove(before!, moves.at(-1)); + expect(transition).not.toBeNull(); + return transition!; +} + +test("nullable introduction lets button preference survive reload without choosing Help or Skip", () => { + const storage = memory(); + expect(readGuidance(storage)).toEqual(defaults); + writeGuidance({ ...readGuidance(storage), buttons: true }, storage); + expect(readGuidance(storage)).toEqual({ version: 1, intro: null, buttons: true }); + for (const intro of ["help", "skip"] as const) { + writeGuidance({ ...readGuidance(storage), intro }, storage); + expect(readGuidance(storage)).toEqual({ version: 1, intro, buttons: true }); + expect(guidanceEnabled(readGuidance(storage))).toBe(intro === "help"); + } + expect(GUIDANCE_KEY).toBe("familiar.guidance.keep-wrens-light.v1"); + expect(GUIDANCE_KEY.startsWith("familiar.expedition.")).toBe(false); +}); + +test("malformed or unsupported preferences behave as unset without rewriting bytes", () => { + for (const raw of ["{", "null", "[]", '{"version":2,"intro":"help","buttons":true}', '{"version":1,"buttons":false}', '{"version":1,"intro":"skip","buttons":0}', '{"version":1,"intro":true,"buttons":true}']) { + const storage = memory(); storage.data.set(GUIDANCE_KEY, raw); + expect(readGuidance(storage)).toEqual(defaults); + expect(storage.data.get(GUIDANCE_KEY)).toBe(raw); + } +}); + +test("blocked storage leaves the caller's in-memory choice usable", () => { + const storage = { getItem() { throw new Error("blocked"); }, setItem() { throw new Error("blocked"); } }; + expect(readGuidance(storage)).toEqual(defaults); + const choice: GuidancePreferences = { ...readGuidance(storage), intro: "help", buttons: true }; + expect(() => writeGuidance(choice, storage)).not.toThrow(); + expect(guidanceEnabled(choice)).toBe(true); + expect(choice.buttons).toBe(true); + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); + Object.defineProperty(globalThis, "localStorage", { configurable: true, get() { throw new Error("access blocked"); } }); + try { expect(readGuidance()).toEqual(defaults); expect(() => writeGuidance(choice)).not.toThrow(); } + finally { if (descriptor) Object.defineProperty(globalThis, "localStorage", descriptor); else Reflect.deleteProperty(globalThis, "localStorage"); } +}); + +test("accepted first and second decisions teach move timing before the first wave", () => { + const first = applyMove(startTide(storyStart("lens")), "wait")!; + const one = observeTransition(first, observedLessons(first.before)); + expect(one.cue).toBe("Every step or wait advances the water by one move. Reading and menus do not."); + const second = applyMove(first.after, "north")!; + expect(second.events.some(event => event.kind === "wave")).toBe(false); + expect(observeTransition(second, one.observed).cue).toBe("The numbers show moves until the next wave. Mochi moves first, then the wave lands."); + const third = applyMove(second.after, "south")!; + const lesson = observeTransition(third, observedLessons(third.before)); + expect(lesson.cue).toBe("That wave moved the bridge to the left lane. Cross the channel there."); + expect(lesson.observed.has("wave")).toBe(true); + expect(lesson.observed.has("bridge")).toBe(true); +}); + +test("observing and replaying guidance never modifies canonical traces or creates a lesson backlog", () => { + let state = startTide(storyStart("lens")); + while (state.outcome === "active") { + const transition = applyMove(state, cautiousMove(state, { ...VALUE, lens: 60 }))!; + const serialized = JSON.stringify(transition); + const lesson = observeTransition(transition, observedLessons(state)); + expect(JSON.stringify(transition)).toBe(serialized); + expect(observedLessons(transition.after)).toEqual(lesson.observed); + expect(observeTransition(transition, lesson.observed).cue).toBeNull(); + expect(observeTransition(transition, lesson.observed).lensBanked).toBe(false); + if (lesson.lensBanked) expect(lesson.cue).toBe(LENS_SAFE_CUE); + state = transition.after; + } +}); + +test("quiet accepted moves retain bridge teaching without reviving a dismissed cue", () => { + const bridge = last(storyStart("lens"), ["wait", "north", "south"]); + const cue = observeTransition(bridge, observedLessons(bridge.before)).cue; + expect(cue).toBe("That wave moved the bridge to the left lane. Cross the channel there."); + const quiet = applyMove(bridge.after, "wait")!; + expect(quiet.events).toEqual([]); + expect(observeTransition(quiet, observedLessons(quiet.before)).cue).toBeNull(); + expect(retainedCue(cue, quiet)).toBe(cue); + expect(retainedCue(null, quiet)).toBeNull(); +}); + +test("carried lens guidance survives a quiet move and clears when a real splash loses it", () => { + const pickup = last(storyStart("lens"), ["north", "north", "north", "south", "north", "west", "north"]); + const cue = observeTransition(pickup, observedLessons(pickup.before)).cue; + expect(cue).toBe("Mochi has the Beacon Lens. Bring it to the center dock before taking more risks."); + const quiet = applyMove(pickup.after, "wait")!; + expect(quiet.events).toEqual([]); + expect(retainedCue(cue, quiet)).toBe(cue); + const splash = applyMove(quiet.after, "east")!; + expect(splash.after.outcome).toBe("active"); + expect(splash.events.some(event => event.kind === "splash" && event.lost === "lens")).toBe(true); + expect(observeTransition(splash, observedLessons(splash.before)).cue).toBeNull(); + expect(retainedCue(cue, splash)).toBeNull(); + expect(consequence(splash)).toContain("Splashed."); +}); + +test("persistent cues yield to protection, endings, banking and changed bridge lanes", () => { + const cue = "Mochi has the Beacon Lens. Bring it to the center dock before taking more risks."; + const bank = last(storyStart("lens"), ["north", "north", "north", "south", "north", "west", "north", "south", "south", "south", "east"]); + expect(bank.events.some(event => event.kind === "bank" && event.items.includes("lens"))).toBe(true); + expect(retainedCue(cue, bank)).toBeNull(); + const shield = last(storyStart("moth"), ["north", "north", "north", "south", "east", "west", "north", "east", "wait"]); + expect(shield.events.some(event => event.kind === "shield")).toBe(true); + expect(retainedCue(INITIAL_CUE, shield)).toBeNull(); + const end = last(storyStart("lens"), Array(24).fill("wait")); + expect(end.after.outcome).toBe("turned"); + expect(retainedCue(INITIAL_CUE, end)).toBeNull(); + const bridge = last(storyStart("lens"), Array(9).fill("wait")); + expect(bridge.after.bridge).toBe(1); + expect(retainedCue("That wave moved the bridge to the left lane. Cross the channel there.", bridge)).toBeNull(); + expect(retainedCue(INITIAL_CUE, bridge)).toBe(INITIAL_CUE); +}); + +test("a real pickup and splash teaches the returned lens instead of obsolete possession", () => { + // Seed 59 exercises a legal engine edge case; the authored Chapter 1 seed stays 5. + const transition = last({ seed: 59, story: "lens" }, ["east", "west", "north", "wait", "east", "south", "west", "wait", "east", "north", "north", "wait", "west", "west", "north"]); + expect(transition.events.some(event => event.kind === "pickup" && event.item === "lens")).toBe(true); + expect(transition.events.some(event => event.kind === "splash" && event.lost === "lens")).toBe(true); + expect(transition.after.outcome).toBe("active"); + expect(observeTransition(transition, observedLessons(transition.before)).cue).toBe("The wave returned the Beacon Lens to the left shell. It is still there to collect."); + expect(consequence(transition)).not.toContain("Mochi carries"); +}); + +test("real terminal pickup and terminal banked lens transitions never show queued lessons", () => { + const pickup = last(storyStart("lens"), ["north", "east", "south", "west", "north", "wait", "east", "west", "south", "wait", "east", "north", "wait", "west", "wait", "west", "east", "wait", "east", "south", "west", "wait", "east", "north"]); + expect(pickup.events.some(event => event.kind === "pickup")).toBe(true); + expect(pickup.after.outcome).toBe("turned"); + expect(observeTransition(pickup, observedLessons(pickup.before)).cue).toBeNull(); + expect(consequence(pickup)).not.toContain("Mochi takes"); + const banked = last(storyStart("lens"), ["wait", "east", "wait", "north", "wait", "west", "west", "north", "wait", "north", "south", "east", "west", "wait", "wait", "wait", "south", "wait", "wait", "east", "wait", "east", "west", "north"]); + expect(banked.after.banked).toContain("lens"); + expect(banked.after.outcome).toBe("turned"); + expect(observeTransition(banked, observedLessons(banked.before))).toMatchObject({ cue: null, lensBanked: false }); +}); + +test("a real splash and bank keeps safety factual and does not teach a lost pickup", () => { + const transition = last({ seed: 20771 }, ["west", "east", "wait", "east", "wait", "west", "wait", "east", "west", "north", "wait", "east", "south", "north", "wait", "west", "north", "west", "east", "east", "south", "wait", "north", "west"]); + expect(transition.events.some(event => event.kind === "splash")).toBe(true); + expect(transition.events.some(event => event.kind === "bank")).toBe(true); + expect(transition.after.score).toBeGreaterThan(transition.before.score); + expect(transition.after.pack).toEqual([]); + expect(observeTransition(transition, observedLessons(transition.before)).cue).toBeNull(); + expect(consequence(transition)).toContain("Banked"); + expect(consequence(transition)).toContain("Splashed."); +}); + +test("return advice starts at nine timed moves, keeps story names and suppresses empty packs", () => { + const initial = startTide(storyStart("lens")); + expect(returnAdvice({ ...initial, wave: 5, beat: 15 })).toBeNull(); + expect(returnAdvice({ ...initial, wave: 4, beat: 14, pack: ["reed"] })).toBeNull(); + expect(returnAdvice({ ...initial, wave: 5, beat: 15, pack: ["reed"] })).toBe("Three waves or fewer remain. Start bringing the pack to the center dock now; the bridge may move."); + expect(returnAdvice({ ...initial, wave: 7, beat: 21, pack: ["reed"] })).toBe("Last wave. Bank what you can at the center dock."); + expect(returnAdvice({ ...initial, pack: ["lens"] })).toBe("Mochi carries the Beacon Lens. Bring it to the center dock to bank it."); + expect(returnAdvice({ ...initial, outcome: "turned", pack: ["lens"] })).toBeNull(); + const daily = startTide({ seed: 20771 }); + expect(returnAdvice({ ...daily, wave: 9, beat: 27, pack: ["glass"] })).toContain("Three waves or fewer"); +}); diff --git a/web/src/run/guidance.ts b/web/src/run/guidance.ts new file mode 100644 index 0000000..c760ced --- /dev/null +++ b/web/src/run/guidance.ts @@ -0,0 +1,93 @@ +import { applyMove, startTide, tideShape, type TideState, type TideTransition } from "./engine"; + +export const GUIDANCE_KEY = "familiar.guidance.keep-wrens-light.v1"; +export interface GuidancePreferences { version: 1; intro: null | "help" | "skip"; buttons: boolean } +const unset = (): GuidancePreferences => ({ version: 1, intro: null, buttons: false }); + +export function readGuidance(storage?: Pick): GuidancePreferences { + try { + const raw = (storage ?? localStorage).getItem(GUIDANCE_KEY); + if (raw === null) return unset(); + const value: unknown = JSON.parse(raw); + if (!value || typeof value !== "object") return unset(); + const preference = value as Partial; + if (preference.version !== 1 || (preference.intro !== null && preference.intro !== "help" && preference.intro !== "skip") || typeof preference.buttons !== "boolean") return unset(); + return { version: 1, intro: preference.intro, buttons: preference.buttons }; + } catch { return unset(); } +} + +export function writeGuidance(preferences: GuidancePreferences, storage?: Pick): void { + try { (storage ?? localStorage).setItem(GUIDANCE_KEY, JSON.stringify(preferences)); } catch { /* Guidance never blocks play. */ } +} +export const guidanceEnabled = (preferences: GuidancePreferences) => preferences.intro !== "skip"; + +export const INITIAL_CUE = "Swipe on the board, or tap a glowing neighboring stone. Mochi moves one step at a time."; +export const DISTANT_CUE = "Choose a glowing neighboring stone. Mochi moves one step at a time."; +export const LENS_SAFE_CUE = "Lens safe. Story finds restore the harbor; they add no points. Finish and return when you’re ready to fit it."; +const PICKUP_CUE = "Mochi picks up a find by stepping onto it. Carry it to the center dock to bank it."; +const LENS_PICKUP_CUE = "Mochi has the Beacon Lens. Bring it to the center dock before taking more risks."; +const LENS_LOSS_CUE = "The wave returned the Beacon Lens to the left shell. It is still there to collect."; +const bridgeCue = (lane: number) => `That wave moved the bridge to the ${["left", "center", "right"][lane]} lane. Cross the channel there.`; +type Lesson = "move" | "countdown" | "wave" | "bridge" | "crossing" | "pickup" | "lens-pickup" | "bank" | "lens-bank" | "lens-loss"; + +/** Observe all facts once, even when a more urgent fact supplies this move's single cue. */ +export function observeTransition(transition: TideTransition, previous: ReadonlySet) { + const { before, after, events } = transition, observed = new Set(previous); + const candidates: string[] = []; + const offer = (lesson: Lesson, condition: boolean, line: string) => { + if (!condition) return; + if (!observed.has(lesson)) candidates.push(line); + observed.add(lesson); + }; + offer("move", after.beat > before.beat, "Every step or wait advances the water by one move. Reading and menus do not."); + offer("countdown", after.beat === 2, "The numbers show moves until the next wave. Mochi moves first, then the wave lands."); + const wave = events.some(event => event.kind === "wave"), bridge = events.find(event => event.kind === "bridge"); + offer("wave", wave, "A wave arrives after every third move. Read the tinted lanes and the moves left before you move."); + offer("bridge", !!bridge, bridgeCue(after.bridge)); + offer("crossing", events.some(event => event.kind === "move" && Math.abs(event.to.y - event.from.y) === 2), "Mochi crossed the bridge in one move."); + const ordinaryPickup = events.some(event => event.kind === "pickup" && !["lens", "vane", "moth"].includes(event.item) && after.pack.includes(event.item) && !events.some(later => later.kind === "splash" && later.lost === event.item)); + offer("pickup", ordinaryPickup, PICKUP_CUE); + offer("lens-pickup", events.some(event => event.kind === "pickup" && event.item === "lens") && after.pack.includes("lens"), LENS_PICKUP_CUE); + offer("bank", events.some(event => event.kind === "bank" && event.gained > 0), "Cargo banked. Those points stay safe if the rest of the outing goes badly."); + const lensBanked = events.some(event => event.kind === "bank" && event.items.includes("lens")) && after.banked.includes("lens"); + offer("lens-bank", lensBanked, LENS_SAFE_CUE); + const lensLost = events.some(event => event.kind === "pickup" && event.item === "lens") && events.some(event => event.kind === "splash" && event.lost === "lens") && after.items.some(item => item.kind === "lens"); + offer("lens-loss", lensLost, LENS_LOSS_CUE); + const loss = events.some(event => event.kind === "splash" && event.lost !== null); + // Loss, protection and endings are already narrated by consequence(); never obscure them with an obsolete lesson. + const cue = after.outcome !== "active" || events.some(event => event.kind === "shield") || loss && !lensLost ? null : candidates.at(-1) ?? null; + return { observed, cue, lensBanked: lensBanked && !previous.has("lens-bank") && after.outcome === "active" }; +} + +/** Preserve a displayed lesson only while its state-dependent wording remains factual. */ +export function retainedCue(cue: string | null, transition: TideTransition): string | null { + const { after, events } = transition; + if (after.outcome !== "active" || events.some(event => event.kind === "shield" || event.kind === "splash" && event.lost !== null)) return null; + if (cue === LENS_PICKUP_CUE && !after.pack.includes("lens")) return null; + if (cue === PICKUP_CUE && !after.pack.some(item => item === "reed" || item === "glass" || item === "pearl")) return null; + if (cue === LENS_LOSS_CUE && !after.items.some(item => item.kind === "lens")) return null; + if ([0, 1, 2].some(lane => cue === bridgeCue(lane)) && cue !== bridgeCue(after.bridge)) return null; + return cue; +} + +/** Replaying a saved trace marks history observed without presenting any old lesson. */ +export function observedLessons(state: TideState): ReadonlySet { + let current = startTide({ seed: state.seed, ...(state.story ? { story: state.story } : {}) }); + let observed: ReadonlySet = new Set(); + for (const move of state.moves) { + const transition = applyMove(current, move); + if (!transition) break; + observed = observeTransition(transition, observed).observed; + current = transition.after; + } + return observed; +} + +export function returnAdvice(state: TideState): string | null { + if (state.outcome !== "active" || !state.pack.length) return null; + if (state.pack.includes("lens")) return "Mochi carries the Beacon Lens. Bring it to the center dock to bank it."; + if (state.pack.includes("vane")) return "Mochi carries the Signal Vane. Bring it to the center dock to bank it."; + if (state.pack.includes("moth")) return "Mochi cradles the wind-moth. Bring it to the center dock to bank it."; + const remainingMoves = (tideShape(state).waves - state.wave) * 3 - state.beat % 3; + return remainingMoves <= 3 ? "Last wave. Bank what you can at the center dock." : remainingMoves <= 9 ? "Three waves or fewer remain. Start bringing the pack to the center dock now; the bridge may move." : null; +} diff --git a/web/src/run/scene.test.ts b/web/src/run/scene.test.ts new file mode 100644 index 0000000..18b6377 --- /dev/null +++ b/web/src/run/scene.test.ts @@ -0,0 +1,75 @@ +import { expect, mock, test } from "bun:test"; +import { companionIdle } from "../expedition/companion"; +import { MOCHI_GROUND } from "../motion/mochi"; +import { legalMoves, startTide, stepDestination, type Position } from "./engine"; +import { storyStart } from "./story"; + +// Exercise scene geometry and input without opening a renderer or browser. +mock.module("phaser", () => ({ default: { Scene: class {} } })); +const { TideScene } = await import("./scene"); + +function board(width: number, height: number, readingTop: number | null) { + const scene = new TideScene({ tide: startTide(storyStart("lens")), reducedMotion: true }, {} as never); + Object.assign(scene, { scale: { width, height }, readingTop, hudBottom: 186, bottomInset: 10 }); + return scene as unknown as { + field(): { dx: number; dy: number }; + targetSize(): { width: number; height: number }; + actorSize(): number; + point(position: Position): { x: number; y: number }; + }; +} + +test("Mochi's complete idle bounds leave every legal destination's full 44px target usable", () => { + const breath = Math.max(...Array.from({ length: 110 }, (_, tick) => companionIdle(tick * 84, "player", false).breath)); + for (const [width, height, readingTop] of [[390, 844, 476.76], [390, 844, 622], [320, 480, 124], [390, 759, 204], [844, 390, 140], [1280, 800, 450]] as const) { + const scene = board(width, height, readingTop), { width: targetWidth, height: targetHeight } = scene.targetSize(); + const size = scene.actorSize(); + expect(targetWidth).toBeGreaterThanOrEqual(44); + expect(targetHeight).toBeGreaterThanOrEqual(44); + expect(size).toBeGreaterThan(0); + for (const y of [0, 1, 3, 4]) for (const x of [0, 1, 2] as const) { + const state = { ...startTide(storyStart("lens")), position: { x, y } }, at = scene.point(state.position); + const actor = { left: at.x - size / 2, right: at.x + size / 2, top: at.y - size * breath * MOCHI_GROUND, bottom: at.y + size * breath * (1 - MOCHI_GROUND) }; + for (const move of legalMoves(state)) { + const to = stepDestination(state, move); + if (!to) continue; + const target = scene.point(to); + expect(actor.right < target.x - targetWidth / 2 || actor.left > target.x + targetWidth / 2 || actor.bottom < target.y - targetHeight / 2 || actor.top > target.y + targetHeight / 2).toBe(true); + } + } + } +}); + +test("open phone controls accept north edge taps, while Mochi taps remain free and holds inspect", () => { + const scene = board(390, 844, 476.76), size = scene.actorSize(), at = scene.point({ x: 1, y: 0 }); + const move = mock(() => {}), target = mock(() => {}), inspect = mock(() => {}); + const canvas = { getBoundingClientRect: () => ({ left: 0, right: 390, top: 0, bottom: 844 }) }; + const contains = (x: number, y: number) => Math.abs(x - at.x) <= size / 2 && y >= at.y - size * MOCHI_GROUND && y <= at.y + size * (1 - MOCHI_GROUND); + Object.assign(scene, { game: { canvas }, actor: { getBounds: () => ({ contains }) }, hooks: { move, target, inspect } }); + const input = scene as unknown as { press(pointer: unknown, over: unknown[]): void; release(pointer: unknown, over: unknown[]): void }; + const destination = { x: 1, y: 1 } as const, zone = { getData: (key: string) => key === "cellTarget" ? destination : undefined }; + const tap = (x: number, y: number, duration = 20) => { + const pointer = { id: 0, x, y, event: { clientX: x, clientY: y }, downElement: canvas, wasTouch: true, wasCanceled: false, getDuration: () => duration, rightButtonReleased: () => false }; + input.press(pointer, [zone]); input.release(pointer, [zone]); + }; + const document = Object.getOwnPropertyDescriptor(globalThis, "document"); + Object.defineProperty(globalThis, "document", { configurable: true, value: { hidden: false, elementFromPoint: () => canvas } }); + try { + const north = scene.point(destination), area = scene.targetSize(); + for (const [dx, dy] of [[0, 0], [-1, -1], [1, -1], [-1, 1], [1, 1]]) { + tap(north.x + dx! * (area.width / 2 - 1), north.y + dy! * (area.height / 2 - 1)); + } + tap(195, 400); // The reported overlap must reach the legal north destination. + expect(target).toHaveBeenCalledTimes(6); + expect(target).toHaveBeenLastCalledWith(destination); + tap(at.x, at.y - size * .4); + expect(target).toHaveBeenCalledTimes(6); + expect(move).not.toHaveBeenCalled(); + tap(at.x, at.y - size * .4, 500); + expect(inspect).toHaveBeenCalledTimes(1); + expect(target).toHaveBeenCalledTimes(6); + } finally { + if (document) Object.defineProperty(globalThis, "document", document); + else Reflect.deleteProperty(globalThis, "document"); + } +}); diff --git a/web/src/run/scene.ts b/web/src/run/scene.ts index 113a67f..ea554ea 100644 --- a/web/src/run/scene.ts +++ b/web/src/run/scene.ts @@ -19,11 +19,12 @@ const same = (a: Position, b: Position) => a.x === b.x && a.y === b.y; export type TideAction="wait"|"home"; export interface TideActionAnchor {action:TideAction;x:number;y:number;width:number;height:number} export interface TideTile {position:Position;x:number;y:number;width:number;height:number} +export interface TideActorBounds {x:number;y:number;width:number;height:number} export interface TideSnapshot { readonly tide: TideState; readonly reducedMotion: boolean; readonly worldActions?:readonly TideAction[] } export interface TideHooks { move:(move:Move)=>void; inspect:()=>void; - geometry:(tiles:readonly TideTile[],actions:readonly TideActionAnchor[])=>void; + geometry:(tiles:readonly TideTile[],actions:readonly TideActionAnchor[],actor:TideActorBounds)=>void; target: (position: Position) => void; ready: () => void; fault: (message: string) => void; @@ -55,10 +56,12 @@ export class TideScene extends Phaser.Scene { private marks: Phaser.GameObjects.GameObject[] = []; private shell: Phaser.GameObjects.Image | null = null; private pack: Phaser.GameObjects.Image[] = []; - private presses=new Map(); + private presses=new Map(); private contacts=new Set(); private multipleContacts=false; private readingTop:number|null=null; + private hudBottom=0; + private bottomInset=0; private layoutRequested=false; private geometryFrame:number|null=null; private epoch = 0; @@ -99,7 +102,7 @@ export class TideScene extends Phaser.Scene { this.hints = this.add.graphics().setDepth(2.1); this.keeper = this.add.image(0, 0, "tide-keeper").setOrigin(.5, 1).setDepth(3); this.actorShadow = this.add.ellipse(0, 0, 50, 13, 0x342719, .25).setDepth(7); - this.actor = this.add.sprite(0, 0, "tide-mochi", 12).setOrigin(.5, MOCHI_GROUND).setDepth(10).setInteractive({useHandCursor:true}); + this.actor = this.add.sprite(0, 0, "tide-mochi", 12).setOrigin(.5, MOCHI_GROUND).setDepth(10); this.scale.on("resize", () => { this.presses.clear(); if (this.playing && this.presentationSize) { @@ -139,20 +142,28 @@ export class TideScene extends Phaser.Scene { /** Presentation coordinates are responsive. Logical cells and accepted state never resize. */ private field() { const portrait = this.w <= 900 && this.h > this.w; - if (portrait && this.h < 500) { const top = 144, bottom = Math.min(this.h-150,this.readingTop===null?Infinity:this.readingTop-24), width = this.w * .72; return { cx: this.w / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } + if (portrait && this.h < 760) { + const available = this.w - Math.min(182,this.w-168) - 20, width = Math.max(144, available * .84), top = Math.max(this.h <= 600 ? 156 : 238, this.hudBottom + 44), bottom = this.h - Math.max(72,this.bottomInset+44); + return { cx: available / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; + } if (this.h <= 500) { // The painted island and its rings extend below the dock anchor. - const available = this.w - 280, width = Math.max(240, Math.min(available * .91, 760)), top = 98, bottom = this.h - (portrait ? 34 : 56); + const available = this.w - 280, width = Math.max(240, Math.min(available * .91, 760)), top = 98, bottom = this.h - 56; return { cx: available / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } - const top = portrait ? (this.h < 650 ? 151 : Math.max(200, this.h * .29)) : Math.max(190, this.h * .31); + const top = portrait ? Math.max(200, this.h * .29, this.hudBottom + 24) : Math.max(190, this.h * .31); const bottom = portrait ? Math.min(this.h-170,this.readingTop===null?Infinity:this.readingTop-48) : this.h - 72; const width = Math.min(portrait ? this.w * .72 : this.w * .50, 760); return { cx: portrait ? this.w * .5 : this.w * .45, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } private point(position: Position) { const f = this.field(); return { x: f.cx + (position.x - 1) * f.dx, y: f.bottom - position.y * f.dy }; } private tileSize() { const f = this.field(); return { width: Math.min(f.dx * .99, 220), height: Math.max(33, Math.min(f.dy * .65, 72)) }; } - private actorSize() { return Math.min(this.field().dx * .66, this.field().dy * 1.1, 112); } + private targetSize() { const f = this.field(), tile = this.tileSize(); return { width: Math.max(44, tile.width), height: Math.max(44, Math.min(tile.height + 15, f.dy - 2)) }; } + private actorSize() { + const f = this.field(); + // Leave the full northern target clear of Mochi's bounds, including her idle breath. + return Math.min(f.dx * .66, (f.dy - this.targetSize().height / 2 - 2) / MOCHI_GROUND, 112); + } private prizeSize(kind: Item) { return Math.min(kind === "reed" ? 62 : kind === "moth" ? 58 : 50, this.tileSize().width * .55); } private pose(name: MochiPoseName) { this.actorPose = name; this.actor.setFrame(MOCHI_POSES[name].frame); } private keep(part: T) { this.parts.push(part); return part; } @@ -209,8 +220,12 @@ export class TideScene extends Phaser.Scene { this.presses.clear(); if(!this.playing){ this.layoutRequested=false; - const reading=this.game.canvas.closest(".exp-game")?.querySelector(".exp-command-tray"); - this.readingTop=reading?.getClientRects().length?reading.getBoundingClientRect().top-this.game.canvas.getBoundingClientRect().top:null; + const root=this.game.canvas.closest(".exp-game"),canvas=this.game.canvas.getBoundingClientRect(); + const reading=root?.querySelector(".exp-command-tray"),hud=root?.querySelector(".exp-hud"); + this.hudBottom=hud?.getClientRects().length?hud.getBoundingClientRect().bottom-canvas.top:0; + this.bottomInset=reading?Number.parseFloat(getComputedStyle(reading).bottom)||0:0; + root?.style.setProperty("--tide-board-top",`${this.field().top}px`); + this.readingTop=reading?.getClientRects().length?reading.getBoundingClientRect().top-canvas.top:null; } for(const zone of [...this.tileZones,...this.actionZones.values()])zone.disableInteractive(); for (const part of this.parts) part.destroy(); @@ -233,7 +248,7 @@ export class TideScene extends Phaser.Scene { this.ground.lineStyle(1, 0xe5edce, .35).strokeEllipse(p.x, p.y + tile.width * .1, tile.width * 1.09, tile.width * .24); this.keep(this.add.image(p.x, p.y, "tide-island").setOrigin(.5, .41).setDisplaySize(tile.width, tile.width * island.height / island.width).setDepth(1)); } else if (x !== tide.bridge) this.ground.lineStyle(2, 0xa8c8bd, .4).strokeEllipse(p.x, p.y + 6, tile.width * .6, tile.height * .45); - const width=Math.max(44,tile.width),height=Math.max(44,Math.min(tile.height+15,f.dy-2)); + const {width,height}=this.targetSize(); const index=y*3+x; let zone=this.tileZones[index]; if(!zone){zone=this.add.zone(p.x,p.y,width,height).setInteractive({useHandCursor:true}).setDepth(16).setData("cellTarget",position);this.tileZones[index]=zone;} @@ -260,13 +275,14 @@ export class TideScene extends Phaser.Scene { this.prizes.set(`${item.x},${item.y}`, this.keep(this.add.image(p.x + beside, p.y - size * .36, `tide-${item.kind}`).setDisplaySize(size, size).setDepth(6))); } const p = this.point(tide.position), size = this.actorSize(); - this.actor.setPosition(p.x, p.y).setDisplaySize(size, size).setFlipX(false).setData("worldAction",this.snapshot.worldActions?.includes("wait")?"wait":null); + this.actor.setPosition(p.x, p.y).setDisplaySize(size, size).setFlipX(false); this.actorShadow.setPosition(p.x, p.y + 2).setSize(size * .55, Math.max(4, size * .1)); this.pose(tide.outcome === "rescued" ? "startled" : tide.outcome !== "active" ? "relieved" : "curious"); this.drawPack(tide.pack); this.forecast(); this.resetIdle(); - this.hooks.geometry(targets,this.actionTargets(tide,targets)); + const actor=this.actor.getBounds(); + this.hooks.geometry(targets,this.actionTargets(tide,targets),{x:actor.centerX,y:actor.centerY,width:actor.width,height:actor.height}); } private clientPoint(pointer:Phaser.Input.Pointer){ @@ -285,7 +301,7 @@ export class TideScene extends Phaser.Scene { const touch=pointer.wasTouch||("pointerType" in event&&event.pointerType==="pen"); if(!touch&&!pointer.leftButtonDown()&&!pointer.rightButtonDown())return; const target=over.find(object=>object.getData("cellTarget")||object.getData("worldAction"))??null; - this.presses.set(pointer.id,{target,x:point.x,y:point.y,excursion:0,touch,edge:point.x-rect.left<24||rect.right-point.x<24}); + this.presses.set(pointer.id,{target,actor:this.actor.getBounds().contains(pointer.x,pointer.y),x:point.x,y:point.y,excursion:0,touch,edge:point.x-rect.left<24||rect.right-point.x<24}); } private release(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[]){ const press=this.presses.get(pointer.id);this.presses.delete(pointer.id);this.contacts.delete(pointer.id);this.afterRelease(); @@ -298,7 +314,10 @@ export class TideScene extends Phaser.Scene { const command=swipeCommand(point.x-press.x,point.y-press.y); if(command){this.hooks.move(command.slice(5) as Move);return;} } - if(excursion>12||!press.target||!over.includes(press.target))return; + if(excursion>12)return; + // Tapping Mochi is free; holding her opens inspection. + if(press.actor){if(pointer.rightButtonReleased()||pointer.getDuration()>450)this.hooks.inspect();return;} + if(!press.target||!over.includes(press.target))return; if(pointer.rightButtonReleased()||pointer.getDuration()>450){this.hooks.inspect();return;} if(!press.touch&&!pointer.leftButtonReleased())return; const action=press.target.getData("worldAction") as TideAction|undefined; @@ -307,9 +326,11 @@ export class TideScene extends Phaser.Scene { } private actionTargets(tide:TideState,tiles:readonly TideTile[]):TideActionAnchor[]{ const anchors:TideActionAnchor[]=[],canvas=this.game.canvas.getBoundingClientRect(),f=this.field(); - const blocked=Array.from(this.game.canvas.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-mast,.exp-feedback")??[]) + const blocked=Array.from(this.game.canvas.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-mast,.exp-feedback,.exp-button-controls[open] .exp-button-controls-body")??[]) .filter(element=>element.getClientRects().length&&getComputedStyle(element).visibility!=="hidden") .map(element=>{const r=element.getBoundingClientRect();return{x:r.left-canvas.left+r.width/2,y:r.top-canvas.top+r.height/2,width:r.width,height:r.height};}); + const actor=this.actor.getBounds(); + blocked.push({x:actor.centerX,y:actor.centerY,width:actor.width,height:actor.height}); const overlaps=(a:{x:number;y:number;width:number;height:number},b:typeof a)=>Math.abs(a.x-b.x)<(a.width+b.width)/2+2&&Math.abs(a.y-b.y)<(a.height+b.height)/2+2; const moves=legalMoves(tide),cells=tiles.filter(cell=>moves.some(move=>{const to=stepDestination(tide,move);return to&&same(to,cell.position);})); for(const action of this.snapshot.worldActions??[]){ diff --git a/web/src/run/story.ts b/web/src/run/story.ts index dd97d69..3a7e328 100644 --- a/web/src/run/story.ts +++ b/web/src/run/story.ts @@ -48,6 +48,19 @@ export function chapterFor(home: HarborStory): StoryPrize | null { } export const storyStart = (prize: StoryPrize): TideStart => ({ seed: CHAPTERS[prize].seed, story: prize }); +export interface HarborMemory { readonly id: string; readonly title: string; readonly lines: readonly string[] } + +/** Earned summaries have no invented route, date, or accepted return record. */ +export function harborMemories(home: HarborStory): HarborMemory[] { + const memories: HarborMemory[] = []; + if (home.banked.includes("lens")) memories.push({ id: "lens", title: "The lens comes home", lines: ["Mochi brought the Beacon Lens safely to the harbor."] }); + if (home.lit) memories.push({ id: "light", title: "Wren’s light", lines: ["The beacon shines again. The Tidekeeper stopped to watch."] }); + if (home.banked.includes("vane")) memories.push({ id: "vane", title: "The vane comes home", lines: ["Mochi recovered the Signal Vane."] }); + if (home.signaled) memories.push({ id: "keeper", title: "The light’s keeper", lines: CHAPTERS.vane.after }); + if (home.banked.includes("moth")) memories.push({ id: "moth", title: "Two familiars and one light", lines: ["The Tidekeeper let Mochi bring Wren’s wind-moth home. Bram made room beside the hearth.", ...CHAPTERS.moth.after] }); + return memories; +} + const LANES = ["Left", "Center", "Right"] as const; const NAMES: Readonly> = { reed: "reed", glass: "sea glass", pearl: "pearl", lens: "Beacon Lens", vane: "Signal Vane", moth: "wind-moth" }; export const itemName = (item: Item) => NAMES[item]; diff --git a/web/src/run/tide-run.css b/web/src/run/tide-run.css index 3a89d40..f48ccc1 100644 --- a/web/src/run/tide-run.css +++ b/web/src/run/tide-run.css @@ -65,7 +65,7 @@ .tide-run .passage-header-actions { grid-column: 2; grid-row: 1; } .tide-run .passage-header-actions button { padding-inline: 10px; } .tide-run h1.exp-place { grid-column: 1 / -1; justify-self: start; margin: 0; padding: 5px 10px; font-size: 13px; } - .tide-run .tide-hud { top: max(124px, calc(env(safe-area-inset-top) + 114px)); left: 10px; right: 10px; width: auto; max-width: none; gap: 10px; padding: 10px 12px; } + .tide-run .tide-hud { top: max(124px, calc(env(safe-area-inset-top,0px) + 114px)); left: 10px; right: 10px; width: auto; max-width: none; gap: 10px; padding: 10px 12px; } .tide-run .tide-portrait { width: 42px; height: 42px; } .tide-run .tide-vitals strong { font-size: 16px; } .tide-run .tide-hearts { gap: 3px; } @@ -73,7 +73,7 @@ .tide-run .tide-tally { gap: 5px; padding-left: 10px; } .tide-run .tide-tally > svg { width: 18px; height: 18px; } .tide-run .tide-tally b { font-size: 19px; } - .tide-run .passage-tray { left: 10px; right: 10px; width: auto; padding: 10px 12px; max-height: 212px; gap: 4px; } + .tide-run .passage-tray { left: 10px; right: 10px; bottom:max(10px,env(safe-area-inset-bottom,0px)); width: auto; padding: 10px 12px; max-height: 212px; gap: 4px; } .tide-run .exp-objective-row { gap: 8px; margin-bottom: 4px; } .tide-run .exp-objective { font-size: 15px; } .tide-run .exp-forecast { padding: 7px 0; margin-bottom: 8px!important; font-size: 13px; line-height: 1.35; } @@ -142,10 +142,11 @@ /* Direct play keeps only guidance visible; the full pad opens on request. */ -.tide-run .passage-tray{gap:8px;overflow:visible} +.tide-run .passage-tray{gap:8px;overflow:hidden} .tide-run .tide-controls{position:relative;display:grid;flex:1;min-height:0;grid-template-columns:minmax(0,1fr) auto auto;grid-template-rows:minmax(48px,1fr) auto;gap:4px} .tide-run .tide-controls .exp-control-hints{display:contents} -.tide-run .tide-controls .exp-input-reading{grid-column:1/-1;grid-row:1;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scroll-padding:6px;pointer-events:auto} +/* Override the display:contents hint wrapper's centered alignment so reading scrolls inside its row. */ +.tide-run .tide-controls .exp-input-reading{grid-column:1/-1;grid-row:1;align-self:stretch;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scroll-padding:6px;pointer-events:auto} .tide-run .exp-input-more{grid-column:2;grid-row:2;width:44px;min-height:44px;padding:8px;pointer-events:auto} .tide-run .tide-controls .exp-button-controls{position:static;grid-column:1;grid-row:2;align-self:stretch} .tide-run .exp-button-controls>summary{justify-content:flex-start;width:max-content} @@ -171,7 +172,7 @@ @media(max-width:599px) and (max-height:600px) and (orientation:portrait){ .tide-run .exp-brand small{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} .tide-run h1.exp-place{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);padding:0} - .tide-run .tide-hud{top:68px;padding:6px 8px;gap:8px} + .tide-run .tide-hud{top:max(68px,calc(env(safe-area-inset-top,0px) + 58px));padding:6px 8px;gap:8px} .tide-run .tide-portrait{width:30px;height:30px} .tide-run .tide-vitals strong{font-size:14px} .tide-run .tide-vitals{gap:3px} @@ -183,8 +184,47 @@ .tide-run .passage-tray:has(.tide-bank-actions){max-height:212px} } @media(orientation:landscape) and (max-height:500px){ - .tide-run .passage-tray{overflow:visible;gap:5px} + .tide-run .passage-tray{overflow-y:auto;gap:5px} .tide-run .tide-controls .exp-input-context{font-size:12px} .tide-run .tide-guide-control{font-size:13px;padding-inline:0} .tide-run .exp-button-controls-body{max-height:calc(100dvh - 160px)} } + +/* The open pad takes real layout space, so the board never sits beneath a popover. */ +.tide-run .exp-button-controls-body{position:static;inset:auto;width:100%;max-width:none;max-height:none;padding:8px 0 0;border-radius:0;background:transparent;box-shadow:none;overflow:visible} +.tide-run .exp-button-controls[open]{grid-column:1/-1} +.tide-run .exp-input-more{align-self:start} +.tide-run .passage-tray:focus-visible{outline-color:var(--exp-sea);outline-offset:-3px} +.tide-run .tide-guide-control{align-self:start;justify-self:end} +.tide-run .tide-dismiss-cue{min-width:44px;min-height:44px;padding:6px 0;text-align:left} +.tide-run .tide-lens-decision{padding:24px;color:var(--exp-ink);background:var(--exp-card);border:0;border-radius:var(--exp-card-radius);box-shadow:var(--exp-card-shadow)} +.tide-run .tide-lens-decision h2{margin:0 0 12px} +.tide-run .tide-lens-decision p{font-size:17px;line-height:1.5} +@media(max-width:899px) and (min-height:760px) and (orientation:portrait){ + .tide-run[data-buttons-open=true] .passage-tray{height:360px;max-height:min(360px,calc(100dvh - var(--tide-board-top,max(200px,29dvh)) - 184px - 48px - max(10px,env(safe-area-inset-bottom,0px))))} + .tide-run[data-buttons-open=true] .tide-controls{grid-template-rows:minmax(44px,1fr) auto} +} +@media(max-width:899px) and (max-height:759px) and (orientation:portrait){ + .tide-run .passage-tray{left:auto;right:10px;top:max(204px,calc(env(safe-area-inset-top,0px) + 190px));bottom:max(10px,env(safe-area-inset-bottom,0px));width:min(182px,calc(100vw - 168px));max-height:none;padding:8px;gap:6px;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scroll-padding:8px} + .tide-run .tide-controls{min-height:138px;flex-shrink:0;grid-template-columns:1fr;grid-template-rows:minmax(44px,1fr) auto auto;gap:4px} + .tide-run[data-buttons-open=true] .tide-controls{min-height:250px} + .tide-run .exp-button-controls{grid-column:1;grid-row:2} + .tide-run .tide-guide-control{grid-column:1;grid-row:3;justify-self:start} + .tide-run .exp-input-more{display:none} + .tide-run .exp-button-controls-body .exp-directions{display:grid;grid-template-columns:repeat(auto-fit,44px);justify-content:space-between;gap:6px} + .tide-run .exp-button-controls-body .exp-directions button{grid-column:auto;grid-row:auto} + .tide-run .tide-bank-actions{flex-direction:column;align-items:stretch;gap:0} + .tide-run .tide-bank-actions .exp-primary{font-size:15px;padding-inline:6px;white-space:normal} + .tide-run .tide-bank-actions .exp-text-button{max-width:none} + .tide-run .tide-asks{flex-wrap:wrap;justify-content:flex-start} +} +@media(max-width:599px) and (max-height:599px) and (orientation:portrait){ + .tide-run .passage-tray{top:max(124px,calc(env(safe-area-inset-top,0px) + 110px))} +} +@media(orientation:landscape) and (max-height:500px){ + .tide-run[data-buttons-open=true] .passage-tray{overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scroll-padding:8px} + .tide-run[data-buttons-open=true] .tide-controls{flex-shrink:0;min-height:200px} +} +@media(max-width:359px) and (max-height:759px) and (orientation:portrait){ + .tide-run[data-buttons-open=true] .tide-controls{min-height:300px} +} diff --git a/web/src/tide/TideLog.tsx b/web/src/tide/TideLog.tsx index 8f8c66d..0bfaf52 100644 --- a/web/src/tide/TideLog.tsx +++ b/web/src/tide/TideLog.tsx @@ -11,6 +11,7 @@ import TideStamp from "./TideStamp"; import AskIcon from "./AskIcon"; import { allKept, keptCount, type DayResult } from "./run-day"; import { HaulRow, StampList } from "./RunStamps"; +import type { HarborMemory } from "../run/story"; import "./tide.css"; export type LogPage = @@ -18,8 +19,10 @@ export type LogPage = | { kind: "tide"; day: number; card: TideCard; entry: TideEntry } | { kind: "run"; day: number; card: TideCard; result: DayResult }; -export default function TideLog({ pages, initialPage, reduced, sailBlockedReason, summary, onSail }: { +export default function TideLog({ pages, memories = [], device = true, initialPage, reduced, sailBlockedReason, summary, onSail }: { pages: readonly LogPage[]; initialPage?: number; reduced: boolean; sailBlockedReason: string | null; + memories?: readonly HarborMemory[]; + device?: boolean; summary: { sailed: number; kept: number; allThree: number }; onSail: (day: number) => void; }): JSX.Element { const id = useId(); @@ -68,7 +71,14 @@ export default function TideLog({ pages, initialPage, reduced, sailBlockedReason : Not collected yet)}
- {!page ?

The log is empty. Bring the lens home and Bram starts the first page.

: <> + {memories.length > 0 &&
+

Harbor memories

+ {memories.map(memory =>
+ {memory.title} + {memory.lines.map((line, i) =>

{line}

)} +
)} +
} + {!page ?

{device ? "Harbor memories appear as Mochi brings finds home. Daily pages appear after a finished daily outing." : "The log is empty. Bring the lens home and Bram starts the first page."}

: <>
{ if (event.key === "ArrowLeft" || event.key === "ArrowRight") { event.preventDefault(); move(event.key === "ArrowLeft" ? -1 : 1); } }}> diff --git a/web/src/tide/log-ui.test.tsx b/web/src/tide/log-ui.test.tsx index 72f2ee3..658e564 100644 --- a/web/src/tide/log-ui.test.tsx +++ b/web/src/tide/log-ui.test.tsx @@ -6,6 +6,7 @@ import { tideSummary, type TideEntry } from "./log"; import { logPages } from "./pages"; import type { DayResult } from "./run-day"; import TideLog from "./TideLog"; +import { CHAPTERS, harborMemories } from "../run/story"; const day = 20771, card = cardForDay(day); const result: DayResult = { @@ -88,3 +89,43 @@ test("mixed logs retain the legacy stamp label while crediting a run's brass sea expect(html).toContain("1 of 14 collected, 1 with the brass seal"); expect(html).toContain("Page 2 of 2"); }); + +test("harbor memories follow earned home state without creating route pages", () => { + expect(harborMemories({ banked: [], lit: false, signaled: false })).toEqual([]); + const filed = harborMemories({ banked: ["lens", "vane"], lit: false, signaled: false }); + expect(filed.map(memory => memory.id)).toEqual(["lens", "vane"]); + expect(filed.map(memory => memory.lines)).toEqual([ + ["Mochi brought the Beacon Lens safely to the harbor."], ["Mochi recovered the Signal Vane."], + ]); + const memories = harborMemories({ banked: ["lens", "vane", "moth"], lit: true, signaled: true }); + expect(memories.map(memory => memory.title)).toEqual(["The lens comes home", "Wren’s light", "The vane comes home", "The light’s keeper", "Two familiars and one light"]); + expect(memories[1]!.lines).toEqual(["The beacon shines again. The Tidekeeper stopped to watch."]); + expect(memories[3]!.lines).toEqual(CHAPTERS.vane.after); + expect(memories[4]!.lines).toEqual(["The Tidekeeper let Mochi bring Wren’s wind-moth home. Bram made room beside the hearth.", ...CHAPTERS.moth.after]); + expect(logPages([], [], [])).toEqual([]); + expect(JSON.stringify(memories)).not.toMatch(/\b(day|date|commands|decisions|accepted|stamps)\b/); +}); + +test("a milestone-only log has native expandable memories and no invented chart or daily result", () => { + const home = { banked: ["lens"], lit: true, signaled: false }; + const renderMemory = () => renderToStaticMarkup( {}}/>); + const html = renderMemory(); + expect(html).toContain('aria-label="Harbor memories"'); + expect(html).toContain("
The lens comes home"); + expect(html).toContain("
Wren’s light"); + expect(html).toContain("Harbor memories appear as Mochi brings finds home. Daily pages appear after a finished daily outing."); + expect(html).not.toContain("The log is empty"); + expect(html).not.toContain("Chart of Mochi’s route"); + expect(html).not.toContain("Page 1 of"); + expect(html).not.toContain("data-kept"); + expect(renderMemory()).toBe(html); +}); + +test("an empty saved-harbor log preserves its actual return-page promise", () => { + const html=renderToStaticMarkup( {}}/>); + expect(html).toContain("The log is empty. Bring the lens home and Bram starts the first page."); + expect(html).not.toContain("Harbor memories appear"); + expect(html).not.toContain('aria-label="Harbor memories"'); +});