From cd3c7f75ee620aca23d37985eae030999dcf5f71 Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 01:24:38 -0600 Subject: [PATCH 1/6] Add per-item target star force to the upgrade order An item can now carry a target star (starforce_target). When it is set above the current stars, every star up to the target is priced and ranked, not just the next one. Leaving it blank keeps the old next-star behaviour. - Each step gets a row for each plan. A step's rank score is capped at its predecessor's, so a later star never outranks the one it depends on. - A target above the item's limit (the lower of its scanned max stars and its level's cap) is saved as that limit. Ranking still clamps a target carried over to a replaced item, a reached target does nothing, and the target survives rescans and item replacement. - Steps of one item that sit next to each other in the list are shown as one combined row. "Best per item" still shows one row per item: its top upgrade plus only the target steps that directly follow it. - New route POST /equipment//starforce-target and a target box on the item's Star Force panel, capped at the item's star limit. Text the box cannot parse shows an error instead of clearing the target. - The suggestions model version moves to 7 and now lives in one constant, scouter.suggestions.MODEL_VERSION, which the page reads from the profile. Co-Authored-By: Claude Opus 5.5 --- app.py | 25 ++++++ src/enhancement_analysis.py | 2 + src/scouter/profiles.py | 4 +- src/scouter/service.py | 4 +- src/scouter/suggestions.py | 19 ++++- src/starforce/cost.py | 9 +++ src/starforce/stats.py | 15 ++++ src/starforce/suggestions.py | 110 ++++++++++++++++++--------- src/upgrade_skips.py | 2 +- tests/js/suggestion-filters.test.cjs | 37 +++++++++ tests/test_progression.py | 2 +- tests/test_scouter_suggestions.py | 23 +++++- tests/test_starforce_modes.py | 101 ++++++++++++++++++++++++ tests/test_upgrade_skips.py | 5 +- web/enhancement.js | 20 ++++- web/pages/scouter-suggestions.js | 4 +- web/pages/suggestion-filters.js | 68 +++++++++++++++-- web/scanner.css | 2 +- 18 files changed, 396 insertions(+), 56 deletions(-) diff --git a/app.py b/app.py index e2d3c33..a2b1f61 100644 --- a/app.py +++ b/app.py @@ -312,6 +312,31 @@ def item_starforce_modes(identifier, slot): return character(identifier) +@app.post("/api/characters//equipment//starforce-target") +def item_starforce_target(identifier, slot): + """Rank every star up to this item's target, or clear it to rank only the next star. + + A target above the item's star limit is saved as that limit.""" + from starforce.cost import item_target + from starforce.stats import star_limit + + target = item_target((request.get_json(silent=True) or {}).get("target")) + with characters.lock: + data = characters.load(identifier) + item = data["equipment"].get(slot) + if slot not in LAYOUT["slots"] or not isinstance(item, dict): + raise ValueError("Scan this item first") + limit = star_limit(slot, item) + if target is not None and limit is not None: + target = min(target, limit) + if target is None: + item.pop("starforce_target", None) + else: + item["starforce_target"] = target + characters.write(data) + return character(identifier) + + @app.post("/api/characters//equipment//skip-upgrades") def item_skip_upgrades(identifier, slot): """Leave flame, cube or starforce upgrades for this slot out of the recommendations.""" diff --git a/src/enhancement_analysis.py b/src/enhancement_analysis.py index 6e505ff..875aae4 100644 --- a/src/enhancement_analysis.py +++ b/src/enhancement_analysis.py @@ -65,6 +65,8 @@ def _add_starforce_row(result, detail, common, slot, item, options_config): if slot.split("_")[0] in sf_stats.EXCLUDED_SLOTS or reading.get("status") == "not_applicable": return + # The most stars this item can reach, so the target field can cap what is typed. + detail["starforce_limit"] = sf_stats.star_limit(slot, item) try: if reading.get("status") != "scanned": raise ValueError("Hover this item to scan its stars first.") diff --git a/src/scouter/profiles.py b/src/scouter/profiles.py index 582bef1..08c4b6d 100644 --- a/src/scouter/profiles.py +++ b/src/scouter/profiles.py @@ -274,10 +274,12 @@ def snapshot(identifier): data["history"] = [{k: v for k, v in with_boss_cuts(r).items() if k != "input"} for r in data["history"]] data["fingerprint"] = fingerprint(values) from flaming import characters + from scouter.suggestions import MODEL_VERSION, signature + # The page compares saved recommendations against this to flag an outdated model. + data["suggestions_model_version"] = MODEL_VERSION try: gear = characters.load(identifier) - from scouter.suggestions import signature data["gear_fingerprint"] = signature(gear) except (OSError, ValueError, KeyError, TypeError): diff --git a/src/scouter/service.py b/src/scouter/service.py index 683e146..cdab637 100644 --- a/src/scouter/service.py +++ b/src/scouter/service.py @@ -415,10 +415,10 @@ def ensure_suggestions(identifier): if not any(item.get("name") for item in gear.get("equipment",{}).values()): return {"active":False,"status":"needs_equipment","message":"Scan equipped gear to unlock upgrade recommendations."} sf = options(data.get("starforce_options")) - key = profiles.fingerprint([digest,suggestions.signature(gear),sf,6]) + key = profiles.fingerprint([digest,suggestions.signature(gear),sf,suggestions.MODEL_VERSION]) saved = data.get("suggestions") or {} if (saved.get("fingerprint")==digest and saved.get("gear_fingerprint")==suggestions.signature(gear) - and saved.get("starforce_options")==sf and saved.get("model_version")==6): + and saved.get("starforce_options")==sf and saved.get("model_version")==suggestions.MODEL_VERSION): return {"active":False,"status":"complete","message":"Upgrade recommendations are up to date."} if _job["active"]: return {**state(),"status":"busy"} diff --git a/src/scouter/suggestions.py b/src/scouter/suggestions.py index 5ee8646..ba97646 100644 --- a/src/scouter/suggestions.py +++ b/src/scouter/suggestions.py @@ -25,6 +25,9 @@ from starforce.suggestions import suggestions as starforce_suggestions from utils.payload_data import read_payload_json +# Stamped on saved recommendations; bump it whenever the ranking math changes so saved results recompute. +MODEL_VERSION = 7 + PROTECTED = {"Critical Damage %", "Skill Cooldown Reduction", "Item Drop Rate %", "Meso Amount %"} VALUE_METRICS = [ "STR", @@ -409,10 +412,20 @@ def hat_model(parsed): ) rows.extend(slot_rows) skipped.extend(slot_skipped) - rows.sort(key=lambda r: (-r["fd_per_billion"], r["expected_mesos"], r["slot"], r["method"])) + # Star Force steps toward a target share a capped score with the step before them; + # rank_mesos and step keep such a run together and in star order. + rows.sort( + key=lambda r: ( + -r["fd_per_billion"], + r.get("rank_mesos", r["expected_mesos"]), + r["slot"], + r.get("step", 1), + r["method"], + ) + ) return { "created": profiles.now(), - "model_version": 6, + "model_version": MODEL_VERSION, "starforce_options": starforce_options(data.get("starforce_options")), "cooldown_cache": cooldown_cache, "baseline_id": record["id"], @@ -425,5 +438,5 @@ def hat_model(parsed): "rows": rows, "skipped": skipped, "model": "Expected incremental FD at 380 DEF, using Scouter’s stat efficiencies and cooldown score curves. Gains are estimates, not exact full-build simulations.", - "basis": "Flames/cubes: expected cost and average FD of qualifying rolls. Star Force: expected tap cost and FD at the selected star target, including recovery costs. Use the same preset for scans and Scouter.", + "basis": "Flames/cubes: expected cost and average FD of qualifying rolls. Star Force: expected tap cost and FD of each star up to the item's target (or the next star), including recovery costs; a step never ranks above the one before it. Use the same preset for scans and Scouter.", } diff --git a/src/starforce/cost.py b/src/starforce/cost.py index 1d236f7..2eb6a5c 100644 --- a/src/starforce/cost.py +++ b/src/starforce/cost.py @@ -58,6 +58,15 @@ def item_modes(value): return {str(star): value[str(star)] for star in MODE_STARS} +def item_target(value): + """An item's target stars (1★–30★), or None to rank only the next star.""" + if value is None: + return None + if type(value) is not int or not 1 <= value <= 30: + raise ValueError("Target stars must be a whole number from 1 to 30") + return value + + def mode_summary(modes): """Item modes as runs of stars, e.g. "15–16★ Safeguard, 17–19★ Mode 1, 20–21★ Mode 4".""" runs = [] diff --git a/src/starforce/stats.py b/src/starforce/stats.py index 0a3d771..2407f42 100644 --- a/src/starforce/stats.py +++ b/src/starforce/stats.py @@ -62,6 +62,21 @@ def metadata(slot, item): } +def star_limit(slot, item): + """The most stars ITEM can reach: its scanned limit and its level's limit, whichever is lower. + + None when neither is known.""" + limits = [] + scanned = (item.get("starforce") or {}).get("max_stars") + if type(scanned) is int: + limits.append(scanned) + try: + limits.append(metadata(slot, item)["cap"]) + except ValueError: + pass + return min(limits, default=None) + + def _stat_and_hp_gain(meta, data, band, current, target): result = {} stat = sum(band["stat_per_star"][current + 1 : target + 1]) diff --git a/src/starforce/suggestions.py b/src/starforce/suggestions.py index 0abbcac..8654997 100644 --- a/src/starforce/suggestions.py +++ b/src/starforce/suggestions.py @@ -31,45 +31,85 @@ def suggestions(slot, item, weights, gear, settings=None): "Xenon's conversion needs a complete equipped-star total; fewer than 100 stars are confirmed." ) cfg = cost.options(settings) - target = current + 1 - delta = stats.gains(meta, current, target) - gain = sum(weights.get(key, 0) * value for key, value in delta.items()) - if gain <= 0: - raise ValueError("No positive modeled FD gain from the next star.") - custom = {**cost.expectations(meta["level"], current, target, cfg), "options": cfg} modes = cost.item_modes(item.get("starforce_modes")) + wanted = cost.item_target(item.get("starforce_target")) + # A target at or below the current stars does nothing; one above the cap stops at the cap. + end = min(wanted, cap) if wanted is not None and wanted > current else current + 1 + clamped = wanted if wanted is not None and wanted > cap else None strategies = [("custom", "Your modes")] if modes else [("mesos", "Least mesos"), ("booms", "Fewest booms")] + rows, previous, stopped = [], {}, None + for start in range(current, end): + target = start + 1 + delta = stats.gains(meta, start, target) + gain = sum(weights.get(key, 0) * value for key, value in delta.items()) + if gain <= 0: + if start == current: + raise ValueError("No positive modeled FD gain from the next star.") + stopped = start + break + rows.extend(_step_rows(meta, cfg, modes, strategies, start, target, delta, gain, previous)) + steps = len(rows) // len(strategies) + chain_target = current + steps + for row in rows: + row.update(steps=steps, chain_target=chain_target) + if wanted is not None and wanted > current + 1: + row["notes"].append(f"Step {row['step']} of {steps} toward your {wanted}★ target.") + if clamped is not None: + row["clamped_from"] = clamped + row["notes"].append(f"Your {clamped}★ target is above this item's {cap}★ limit; ranked up to {cap}★.") + if stopped is not None: + row["notes"].append(f"Stops at {stopped}★: the next star has no positive modeled FD gain.") + if row["raw_fd_per_billion"] > row["fd_per_billion"]: + row["notes"].append("Ranked no higher than the previous step, which must be done first.") + return rows + + +def _step_rows(meta, cfg, modes, strategies, start, target, delta, gain, previous): + """One row per strategy for the single star START→TARGET. + + PREVIOUS maps each strategy to the prior step's row and is updated in place. A step's + ranking score is capped at its predecessor's, so a later star never outranks an earlier one.""" + custom = {**cost.expectations(meta["level"], start, target, cfg), "options": cfg} rows = [] for strategy, label in strategies: expected = cost.optimize( - meta["level"], current, target, cfg, objective="booms" if strategy == "booms" else "mesos", modes=modes - ) - rows.append( - { - "method": "Star Force", - "kind": "starforce", - "strategy": strategy, - "strategy_label": label, - "current_stars": current, - "target_stars": target, - "stat_gains": delta, - **expected, - "custom_plan": custom, - "expected_fd": gain, - "fd_per_billion": gain / expected["expected_mesos"] * 1e9, - "current": [f"{current} stars · Lv. {meta['level']}"], - "goal": f"Reach {target} stars · {label.lower()}", - "examples": [f"{key}: +{value}" for key, value in delta.items()], - "protected": [], - "notes": [ - f"Uses this item's modes: {cost.mode_summary(modes)}, including recovery after destruction." - if modes - else "Optimizes the enhancement mode separately at every star, including recovery after destruction.", - "Expected booms is the average number of destroyed items before reaching the target. Replacement equipment prices are excluded.", - "22★ and above use standard rates; Mode 4 does not prevent destruction there.", - *(["30% meso discount included."] if cfg["discount"] else []), - *(["30% destruction reduction included through 21★."] if cfg["boom_reduction"] else []), - ], - } + meta["level"], start, target, cfg, objective="booms" if strategy == "booms" else "mesos", modes=modes ) + raw = gain / expected["expected_mesos"] * 1e9 + prior = previous.get(strategy) + row = { + "method": "Star Force", + "kind": "starforce", + "strategy": strategy, + "strategy_label": label, + "current_stars": start, + "target_stars": target, + "step": prior["step"] + 1 if prior else 1, + "requires": f"{prior['current_stars']}→{prior['target_stars']}" if prior else None, + "stat_gains": delta, + **expected, + "custom_plan": custom, + "expected_fd": gain, + "raw_fd_per_billion": raw, + "fd_per_billion": min(raw, prior["fd_per_billion"]) if prior else raw, + # Steps tied by the cap sort by their first step's cost, so they stay together and in order. + "rank_mesos": prior["rank_mesos"] + if prior and raw >= prior["fd_per_billion"] + else expected["expected_mesos"], + "current": [f"{start} stars · Lv. {meta['level']}"], + "goal": f"Reach {target} stars · {label.lower()}", + "examples": [f"{key}: +{value}" for key, value in delta.items()], + "protected": [], + "notes": [ + f"Uses this item's modes: {cost.mode_summary(modes)}, including recovery after destruction." + if modes + else "Optimizes the enhancement mode separately at every star, including recovery after destruction.", + "Expected booms is the average number of destroyed items before reaching the target. Replacement equipment prices are excluded.", + "22★ and above use standard rates; Mode 4 does not prevent destruction there.", + *(["30% meso discount included."] if cfg["discount"] else []), + *(["30% destruction reduction included through 21★."] if cfg["boom_reduction"] else []), + ], + } + previous[strategy] = row + rows.append(row) return rows diff --git a/src/upgrade_skips.py b/src/upgrade_skips.py index 3d50a04..fb1693a 100644 --- a/src/upgrade_skips.py +++ b/src/upgrade_skips.py @@ -3,7 +3,7 @@ KINDS = ("flame", "cube", "starforce") # Settings the player made on a slot; scans must carry them over to a rescanned or replaced item. -PRESERVED = ("skip_upgrades", "starforce_modes") +PRESERVED = ("skip_upgrades", "starforce_modes", "starforce_target") def normalize(value): diff --git a/tests/js/suggestion-filters.test.cjs b/tests/js/suggestion-filters.test.cjs index 908a0a7..f914e6a 100644 --- a/tests/js/suggestion-filters.test.cjs +++ b/tests/js/suggestion-filters.test.cjs @@ -9,3 +9,40 @@ test('all optimized targets retain multiple choices per item',async()=>{ assert.equal(selectSuggestionRows(rows,'all-mesos','cube').length,2); assert.equal(selectSuggestionRows(rows,'all-booms','starforce')[0].strategy,'booms'); }); +const step=(slot,from,stepNo,steps,strategy='mesos',extra={})=>({slot,kind:'starforce',method:'Star Force',strategy,strategy_label:strategy==='mesos'?'Least mesos':'Fewest booms',current_stars:from,target_stars:from+1,step:stepNo,steps,chain_target:19+steps,requires:stepNo>1?`${from-1}→${from}`:null,expected_fd:1,expected_mesos:100*stepNo,expected_rolls:2,expected_booms:0.1,stat_gains:{'Attack Power':stepNo},starforce_plan:[{star:from,mode:1,recovery:false}],notes:[`Step ${stepNo} of ${steps} toward your 22★ target.`],fd_per_billion:10-stepNo,raw_fd_per_billion:10-stepNo,...extra}); +test('best keeps one row per item, merging the target steps that follow it',async()=>{ + const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js'); + const rows=[step('face',19,1,3),step('face',20,2,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',21,3,3),step('face',19,1,3,'booms'),{slot:'face',kind:'cube',method:'Bright'}]; + const best=selectSuggestionRows(rows,'best'); + assert.deepEqual(best.map(r=>[r.slot,r.kind,r.current_stars,r.target_stars]),[['face','starforce',19,21],['eye','flame',undefined,undefined]]); + const merged=best[0]; + assert.deepEqual(merged.merged_steps,['19→20','20→21']); + assert.deepEqual(merged.step_range,[1,2]); + assert.equal(merged.expected_mesos,300); + assert.equal(merged.expected_booms,0.2); + assert.deepEqual(merged.stat_gains,{'Attack Power':3}); + assert.equal(merged.fd_per_billion,2/300*1e9); + assert.equal(merged.requires,null); + assert.deepEqual(merged.starforce_plan.map(s=>s.star),[19,20]); + assert.ok(merged.notes[0].startsWith('Combines steps 1–2 of 3 toward 22★')); + assert.ok(!merged.notes.some(n=>n.startsWith('Step '))); +}); +test('best never places another item between rows of one item',async()=>{ + const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js'); + const flameFirst=selectSuggestionRows([{slot:'face',kind:'flame',method:'Black Flame'},step('face',19,1,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',20,2,3)],'best'); + assert.deepEqual(flameFirst.map(r=>[r.slot,r.kind]),[['face','flame'],['eye','flame']]); + const skipped=selectSuggestionRows([step('face',19,1,3),{slot:'face',kind:'cube',method:'Bright'},step('face',20,2,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',21,3,3)],'best'); + assert.deepEqual(skipped.map(r=>[r.slot,r.current_stars,r.target_stars]),[['face',19,21],['eye',undefined,undefined]]); +}); +test('steps of different plans or items never merge',async()=>{ + const {mergeSequential}=await import('../../web/pages/suggestion-filters.js'); + const out=mergeSequential([step('face',19,1,3),step('face',20,2,3,'booms'),step('ring1',20,2,3),step('face',21,3,3)]); + assert.equal(out.length,4); + assert.ok(out.every(r=>!r.merged_steps)); +}); +test('rows without a target are untouched',async()=>{ + const {mergeSequential}=await import('../../web/pages/suggestion-filters.js'); + const a={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:19,target_stars:20,steps:1}; + const b={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:20,target_stars:21,steps:1}; + assert.deepEqual(mergeSequential([a,b]),[a,b]); +}); diff --git a/tests/test_progression.py b/tests/test_progression.py index 84e7d3a..291c972 100644 --- a/tests/test_progression.py +++ b/tests/test_progression.py @@ -24,7 +24,7 @@ def test_background_comparison_only_once_per_revision(saved,monkeypatch): def test_background_reuses_current_result(saved,monkeypatch): data,gear=saved - data["suggestions"]={"fingerprint":data["history"][0]["fingerprint"],"gear_fingerprint":suggestions.signature(gear),"starforce_options":options(None),"model_version":6} + data["suggestions"]={"fingerprint":data["history"][0]["fingerprint"],"gear_fingerprint":suggestions.signature(gear),"starforce_options":options(None),"model_version":suggestions.MODEL_VERSION} profiles.write(ID,data) start=Mock() monkeypatch.setattr(service,"start_suggestions",start) diff --git a/tests/test_scouter_suggestions.py b/tests/test_scouter_suggestions.py index 379c10e..d091302 100644 --- a/tests/test_scouter_suggestions.py +++ b/tests/test_scouter_suggestions.py @@ -291,7 +291,7 @@ def unavailable(*args, **kwargs): monkeypatch.setattr(s, "flame_suggestion", unavailable) monkeypatch.setattr(s, "cube_suggestions", unavailable) built = s.build(loaded, gear) - assert built["model_version"] == 6 + assert built["model_version"] == s.MODEL_VERSION assert built["starforce_options"]["discount"] is True assert {r["kind"] for r in built["rows"]} == {"starforce"} assert {r["target_stars"] for r in built["rows"]} == {24} @@ -413,3 +413,24 @@ def test_zero_secondary_is_listed_as_mirroring_the_weapon(): ) assert rows == [] assert [(r["kind"], r["reason"]) for r in skipped] == [("cube", zero.MIRROR_NOTE), ("starforce", zero.MIRROR_NOTE)] + + +def test_target_steps_stay_in_order_with_other_items_between(saved, monkeypatch): + data, gear = saved + gear["equipment"]["face"] = {"name": "Face", "starforce": {"status": "scanned"}} + gear["equipment"]["eye"]["starforce"] = {"status": "scanned"} + + def row(slot, start, step, score, mesos, rank=None): + return {"method": "Star Force", "kind": "starforce", "strategy": "mesos", "current_stars": start, + "target_stars": start + 1, "step": step, "fd_per_billion": score, "raw_fd_per_billion": score, + "expected_mesos": mesos, "rank_mesos": rank if rank is not None else mesos} + + face = [row("face", 19, 1, 5.0, 900), row("face", 20, 2, 3.0, 2_000), + # Capped at its predecessor's score; ties sort by the predecessor's cost. + row("face", 21, 3, 3.0, 100, rank=2_000)] + eye = [row("eye", 23, 1, 4.0, 50), row("eye", 0, 1, 3.0, 1_000)] + monkeypatch.setattr(s, "starforce_suggestions", lambda slot, *a: face if slot == "face" else eye[:1] if slot == "eye" else []) + monkeypatch.setattr(s, "flame_suggestion", lambda *a: (_ for _ in ()).throw(ValueError("none"))) + monkeypatch.setattr(s, "cube_suggestions", lambda *a: (_ for _ in ()).throw(ValueError("none"))) + rows = s.build(data, gear)["rows"] + assert [(r["slot"], r["current_stars"]) for r in rows] == [("face", 19), ("eye", 23), ("face", 20), ("face", 21)] diff --git a/tests/test_starforce_modes.py b/tests/test_starforce_modes.py index d3ff581..98c25f5 100644 --- a/tests/test_starforce_modes.py +++ b/tests/test_starforce_modes.py @@ -92,3 +92,104 @@ def test_modes_route_saves_and_clears(client): assert post(client, path, {"modes": None}).status_code == 200 assert "starforce_modes" not in characters.load(ID)["equipment"]["hat"] assert post(client, f"/api/characters/{ID}/equipment/top/starforce-modes", {"modes": SAFE}).status_code == 400 + + +HAT = {"name": "Royal Dunwitch Hat", "required_level": 150, "starforce": {"status": "scanned", "stars": 19, "max_stars": 30}} +HAT_GEAR = {"class": "Shadower", "equipment": {"hat": HAT}} +ALL = {"LUK": 1, "DEX": 1, "STR": 1, "INT": 1, "Attack Power": 1, "Magic Attack": 1, "Max HP": 1} + + +def test_target_validation(): + assert cost.item_target(None) is None + assert cost.item_target(22) == 22 + for bad in (0, 31, 21.0, True, "22"): + with pytest.raises(ValueError): + cost.item_target(bad) + + +def test_no_target_or_reached_target_ranks_only_the_next_star(): + plain = suggestions("hat", HAT, ALL, HAT_GEAR) + assert [(r["current_stars"], r["target_stars"], r["step"], r["steps"]) for r in plain] == [(19, 20, 1, 1)] * 2 + assert all(r["requires"] is None and r["fd_per_billion"] == r["raw_fd_per_billion"] for r in plain) + for reached in (19, 12): + assert suggestions("hat", {**HAT, "starforce_target": reached}, ALL, HAT_GEAR) == plain + + +def test_target_ranks_every_star_and_steps_add_up_to_the_whole_climb(): + rows = suggestions("hat", {**HAT, "starforce_target": 22}, ALL, HAT_GEAR) + for strategy in ("mesos", "booms"): + chain = [r for r in rows if r["strategy"] == strategy] + assert [(r["current_stars"], r["target_stars"], r["step"]) for r in chain] == [(19, 20, 1), (20, 21, 2), (21, 22, 3)] + assert [r["requires"] for r in chain] == [None, "19→20", "20→21"] + assert all(r["steps"] == 3 and r["chain_target"] == 22 for r in chain) + whole = cost.optimize(150, 19, 22, objective=strategy) + for key in ("expected_mesos", "expected_rolls", "expected_booms"): + assert sum(r[key] for r in chain) == pytest.approx(whole[key]) + # A later star never outranks the one it depends on. + scores = [r["fd_per_billion"] for r in chain] + assert scores == sorted(scores, reverse=True) + assert all(r["fd_per_billion"] <= r["raw_fd_per_billion"] for r in chain) + assert chain[0]["fd_per_billion"] == chain[0]["raw_fd_per_billion"] + + +def test_capped_step_keeps_its_predecessors_score_and_cost_rank(): + # Valuing only attack, 20→21 is cheaper per FD than 19→20, yet it must be done after it. + rows = suggestions("hat", {**HAT, "starforce_target": 21}, {"Attack Power": 1}, HAT_GEAR) + for strategy in ("mesos", "booms"): + first, second = [r for r in rows if r["strategy"] == strategy] + assert second["raw_fd_per_billion"] > first["fd_per_billion"] + assert second["fd_per_billion"] == first["fd_per_billion"] + assert second["rank_mesos"] == first["rank_mesos"] == first["expected_mesos"] + assert any(n.startswith("Ranked no higher") for n in second["notes"]) + assert not any(n.startswith("Ranked no higher") for n in first["notes"]) + + +def test_target_above_the_items_limit_is_clamped(): + item = {"name": "Royal Dunwitch Hat", "required_level": 130, + "starforce": {"status": "scanned", "stars": 18, "max_stars": 20}, "starforce_target": 25} + rows = suggestions("hat", item, ALL, {"class": "Shadower", "equipment": {"hat": item}}) + assert sorted({r["target_stars"] for r in rows}) == [19, 20] + assert all(r["clamped_from"] == 25 and r["chain_target"] == 20 for r in rows) + + +def test_chain_stops_at_a_star_with_no_modeled_gain(): + item = {**HAT, "starforce": {**HAT["starforce"], "stars": 21}, "starforce_target": 24} + rows = suggestions("hat", item, {"LUK": 1}, HAT_GEAR) + assert {(r["current_stars"], r["target_stars"]) for r in rows} == {(21, 22)} + assert all(r["steps"] == 1 and any(n.startswith("Stops at 22★") for n in r["notes"]) for r in rows) + with pytest.raises(ValueError, match="next star"): + suggestions("hat", {**item, "starforce": {**HAT["starforce"], "stars": 22}}, {"LUK": 1}, HAT_GEAR) + + +def test_target_route_saves_and_clears(client): + p = characters.load(ID) + p["equipment"]["hat"] = {"name": "Hat", "starforce": {"status": "scanned", "stars": 17, "max_stars": 30}} + characters.write(p) + path = f"/api/characters/{ID}/equipment/hat/starforce-target" + assert post(client, path, {"target": 22}).status_code == 200 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 22 + for bad in (0, 31, "22", 21.5): + assert post(client, path, {"target": bad}).status_code == 400 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 22 + assert post(client, path, {"target": None}).status_code == 200 + assert "starforce_target" not in characters.load(ID)["equipment"]["hat"] + assert post(client, f"/api/characters/{ID}/equipment/top/starforce-target", {"target": 22}).status_code == 400 + + +def test_target_route_lowers_a_target_above_the_items_limit(client): + path = f"/api/characters/{ID}/equipment/hat/starforce-target" + p = characters.load(ID) + # Scanned limit: 20 stars. + p["equipment"]["hat"] = {"name": "Hat", "starforce": {"status": "scanned", "stars": 17, "max_stars": 20}} + characters.write(p) + assert post(client, path, {"target": 25}).status_code == 200 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 20 + # Level limit: a level 130 item stops at 20 stars even when the scan reads 30. + p = characters.load(ID) + p["equipment"]["hat"] = {"name": "Royal Dunwitch Hat", "required_level": 130, + "starforce": {"status": "scanned", "stars": 17, "max_stars": 30}} + characters.write(p) + assert post(client, path, {"target": 28}).status_code == 200 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 20 + assert post(client, path, {"target": 19}).status_code == 200 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 19 diff --git a/tests/test_upgrade_skips.py b/tests/test_upgrade_skips.py index 300cfcd..72cbc47 100644 --- a/tests/test_upgrade_skips.py +++ b/tests/test_upgrade_skips.py @@ -40,7 +40,7 @@ def test_slot_kinds_leave_out_only_skipped_kinds(): def test_skip_settings_survive_rescan_and_replacement(client): - settings = {"skip_upgrades": ["flame"], "starforce_modes": {str(s): 1 for s in range(15, 22)}} + settings = {"skip_upgrades": ["flame"], "starforce_modes": {str(s): 1 for s in range(15, 22)}, "starforce_target": 22} save(characters.load(ID), grid(frame("grid")), icons(frame("grid"), grid(frame("grid")))) result = hover(frame("hat"), replay, "hat") save(characters.load(ID), result, icons(frame("hat"), result)) @@ -78,7 +78,7 @@ def test_flame_order_drops_skipped_flame_but_costs_keep_it(client): @pytest.mark.parametrize("return_scan", ["equipment", "hover"]) def test_slot_settings_survive_empty_grid_scans(client, return_scan): - settings = {"skip_upgrades": ["flame", "cube"], "starforce_modes": {str(s): 1 for s in range(15, 22)}} + settings = {"skip_upgrades": ["flame", "cube"], "starforce_modes": {str(s): 1 for s in range(15, 22)}, "starforce_target": 22} profile = characters.load(ID) profile["equipment"] = { "hat": {"name": "Old Hat", "icon_hash": "old", "occupied": True, **settings}, @@ -106,6 +106,7 @@ def test_slot_settings_survive_empty_grid_scans(client, return_scan): assert post(client, f"/api/characters/{ID}/equipment/hat/skip-upgrades", {"skip": []}).status_code == 200 profile = characters.load(ID) profile["equipment"]["hat"].pop("starforce_modes") + profile["equipment"]["hat"].pop("starforce_target") characters.write(profile) save(profile, empty_hat, {}) assert characters.load(ID)["equipment_slot_settings"] == {} diff --git a/web/enhancement.js b/web/enhancement.js index fd4fc02..642be01 100644 --- a/web/enhancement.js +++ b/web/enhancement.js @@ -123,6 +123,18 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { panels.querySelectorAll('[data-enhancement-slot]').forEach(b=>b.onclick=()=>onSelect(b.dataset.enhancementSlot)); }else panels.querySelectorAll('[data-enhancement-slot]').forEach(b=>b.classList.toggle('selected',b.dataset.enhancementSlot===slot)); } + // Per-item target stars: blank ranks only the next star; a number ranks every star up to it. + function bindTarget(){ + const input=root.querySelector('#sf-target');if(!input)return; + input.onchange=async()=>{ + const status=root.querySelector('#sf-target-status'),raw=input.value.trim(),value=raw===''?null:Number(raw); + // A number field reports text it cannot parse as '', which must not clear the saved target. + if(input.validity.badInput||value!==null&&!(Number.isInteger(value)&&value>=1&&value<=30)){status.textContent='Enter a whole number from 1 to 30, or leave it blank.';return;} + input.disabled=true;status.textContent='Saving…'; + try{const fresh=await api.post(`/api/characters/${profile.id}/equipment/${encodeURIComponent(slot)}/starforce-target`,{target:value});Object.assign(profile,fresh);await refresh();} + catch(e){status.textContent=e.message;input.disabled=false;} + }; + } // Per-item Star Force modes, one per attempt: sliders and range presets save on the item, then costs refresh. function bindModes(table,saved){ const own=root.querySelector('#sf-own-modes');if(!own)return; @@ -171,8 +183,12 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { return `
${r.star} → ${r.star+1}
${r.choices.map((choice,i)=>``).join('')}
${chance(c.success)}${chance(c.boom)}${cost(c.cost)}
`; }; const modeControls=gear.starforce?.status==='scanned'&&!item.mirror&&table.length?`

Enhancement modes for this item

Quick presetsApply a strategy to a range of stars${presetSelect('low')}${presetSelect('high')}
AttemptStrategySuccessBoomCost
${table.map(modeRow).join('')}

Safeguard (15–17★) and Mode 4 (18–21★) prevent destruction. Success, boom and cost are per attempt, with your event settings.

${modes?'The upgrade order and costs for this item use these modes.':'Off: each star uses whichever mode is cheapest, and the upgrade order also shows a fewest-booms plan.'}

`:''; - root.querySelector('#enhancement-selected').innerHTML=(current?`

Current Star Force cost

${totalValue('0 to '+current.stars+' stars',current.expected_mesos,1)}

${number(current.expected_booms)} expected booms · Level ${current.level}

${basisText}

`:`

${esc(item.mirror||item.starforce_error||'Hover this item to scan its stars.')}

`)+modeControls+skipControls(); - bindModes(table,modes);bindSkips(); + const sf=gear.starforce||{},target=gear.starforce_target,limit=item.starforce_limit??sf.max_stars; + const targetHint=target==null?'Blank: the upgrade order ranks only the next star.':target<=sf.stars?`Reached: ${sf.stars}★ already meets your ${target}★ target, so only the next star is ranked.`:limit!=null&&target>limit?`Above this item's ${limit}★ limit; steps are ranked up to ${limit}★.`:`The upgrade order ranks every star from ${sf.stars}★ to ${target}★.`; + const targetField=sf.status==='scanned'&&!item.mirror?`
Target stars
`:''; + const targetStatus=targetField?`

${esc(targetHint)}

`:''; + root.querySelector('#enhancement-selected').innerHTML=(current?`

Current Star Force cost

${totalValue('0 to '+current.stars+' stars',current.expected_mesos,1)}${targetField}

${number(current.expected_booms)} expected booms · Level ${current.level}

${targetStatus}

${basisText}

`:`

${esc(item.mirror||item.starforce_error||'Hover this item to scan its stars.')}

${targetField}${targetStatus}`)+modeControls+skipControls(); + bindTarget();bindModes(table,modes);bindSkips(); if(!selectionOnly){ panels.innerHTML=`

Current Star Force costs

Cost to reach scanned stars · Lowest cost first.

${rows.map(r=>`
`).join('')||'

Scan Star Force equipment to see costs.

'}
${unpriced('starforce')}
How costs are calculated

${basis}

Uses the discount and boom-reduction options above. These are modeled costs.

`; panels.querySelectorAll('[data-enhancement-slot]').forEach(b=>b.onclick=()=>onSelect(b.dataset.enhancementSlot)); diff --git a/web/pages/scouter-suggestions.js b/web/pages/scouter-suggestions.js index 665816e..d97bc9c 100644 --- a/web/pages/scouter-suggestions.js +++ b/web/pages/scouter-suggestions.js @@ -53,14 +53,14 @@ export function createSuggestions(root, {onGenerate, onOptions=async()=>{}, scop const result=profile.suggestions; button.title='Recompute after equipment or event settings change. Recommendations also refresh in the background.'; const ready=!dirty&&profile.history.some(r=>r.fingerprint===profile.fingerprint); - const oldModel=result&&result.model_version!==6; + const oldModel=result&&result.model_version!==profile.suggestions_model_version; const stale=result&&(oldModel||JSON.stringify(sfOptions(result))!==JSON.stringify(sfOptions(profile))||dirty||result.fingerprint!==profile.fingerprint||result.gear_fingerprint!==profile.gear_fingerprint); if(!result) { body.innerHTML=`
${!ready?'Calculate Scouter with your current inputs first.':!profile.gear_fingerprint?'Scan this character’s equipment in Equipment first.':'Compare your saved flames, potentials and stars to find the best estimated FD gains per meso.'}

Use the same equipment preset for your equipment scans and Scouter calculation.

`; return; } const rows=selectSuggestionRows(result.rows,filter,scope); - body.innerHTML=`${stale?`

Saved comparison · ${!ready?'inputs changed. Calculate Scouter again, then compare upgrades.':oldModel?'Damage potential scoring updated. Compare upgrades again to refresh.':'equipment, targets or Star Force options changed. Compare upgrades again to refresh.'}

`:''} + body.innerHTML=`${stale?`

Saved comparison · ${!ready?'inputs changed. Calculate Scouter again, then compare upgrades.':oldModel?'Recommendation model updated. Compare upgrades again to refresh.':'equipment, targets or Star Force options changed. Compare upgrades again to refresh.'}

`:''}
Estimated gains · 380 DEF

${esc(result.model)}

${esc(result.basis)}

Data used · ${esc(date(result.created))}

Scouter: ${esc(date(result.baseline_created))}
Equipment: ${esc(date(result.equipment_scanned))}
Potentials: ${esc(date(result.potential_scanned))}

${rows.length} of ${result.rows.filter(r=>!scope||r.kind===scope).length} options · highest FD / meso first
diff --git a/web/pages/suggestion-filters.js b/web/pages/suggestion-filters.js index c209960..f1ba3c9 100644 --- a/web/pages/suggestion-filters.js +++ b/web/pages/suggestion-filters.js @@ -1,18 +1,76 @@ export const filters = [ - ['best','Best per item - meso plan','One recommendation per equipment slot, ranked by FD per meso. Star Force uses its least-meso plan; other targets for that slot are hidden.'], - ['best-booms','Best per item - low-boom plan','One recommendation per equipment slot. Star Force uses its fewest-booms plan; other targets for that slot are hidden.'], + ['best','Best per item - meso plan','One recommendation per equipment slot, ranked by FD per meso. Star Force uses its least-meso plan; steps toward an item’s target that rank together are shown as one row.'], + ['best-booms','Best per item - low-boom plan','One recommendation per equipment slot. Star Force uses its fewest-booms plan; steps toward an item’s target that rank together are shown as one row.'], ['all-mesos','All targets - meso optimized','Every flame/cube target, plus the least-meso Star Force plan for each item. Multiple recommendations per slot are shown.'], ['all-booms','All targets - boom optimized','Every flame/cube target, plus the fewest-booms Star Force plan for each item. Multiple recommendations per slot are shown.'], ['all','All options','Every modeled target and both Star Force strategies. Several entries may refer to the same equipment slot.'], ['Black Flame','Black Flames','Only improving flames, evaluated with Scouter stat efficiencies.'], ['Bright','Bright cubes','Only Bright cube targets.'],['Glowing','Glowing cubes','Only Glowing cube targets.'], - ['Star Force','Star Force','Next-star upgrades only, including least-meso and fewest-booms plans.'] + ['Star Force','Star Force','The next star, or every star up to the item\'s target, including least-meso and fewest-booms plans.'] ]; +const targetStep=r=>r.kind==='starforce'&&r.steps>1; +// R is the next star of PREV's Star Force plan for the same item. +const continues=(prev,r)=>prev.kind==='starforce'&&r.kind==='starforce'&&r.slot===prev.slot&&r.strategy===prev.strategy&&r.current_stars===prev.target_stars; export function selectSuggestionRows(rows,filter,scope=null){ const best=['best','best-booms'].includes(filter); const strategy=['best-booms','all-booms'].includes(filter)?'booms':'mesos'; const restrictPlan=best||['all-mesos','all-booms'].includes(filter); let selected=rows.filter(r=>(!scope||r.kind===scope)&&(best||filter.startsWith('all')||r.method===filter)&&(!restrictPlan||r.kind!=='starforce'||r.strategy===strategy||r.strategy==='custom')); - if(best){const seen=new Set();selected=selected.filter(r=>!seen.has(r.slot)&&seen.add(r.slot));} - return selected; + // One row per item: its top-ranked upgrade, plus any target steps that directly follow it, + // so another item never lands between two of one item's rows. + if(best){ + const seen=new Set(),kept=[]; + for(const r of selected){ + if(!seen.has(r.slot)){seen.add(r.slot);kept.push(r);} + else if(targetStep(r)&&kept.length&&continues(kept[kept.length-1],r))kept.push(r); + } + selected=kept; + } + return mergeSequential(selected); +} + +const sum=(rows,key)=>rows.reduce((total,r)=>total+(r[key]??0),0); +function mergeRun(run){ + if(run.length===1)return run[0]; + const first=run[0],last=run[run.length-1]; + const stat_gains={}; + for(const r of run)for(const [key,value] of Object.entries(r.stat_gains||{}))stat_gains[key]=(stat_gains[key]||0)+value; + const plan=new Map(); + for(const r of run)for(const s of r.starforce_plan||[])if(!plan.has(s.star)||plan.get(s.star).recovery)plan.set(s.star,s); + const custom=first.custom_plan&&{...first.custom_plan,...Object.fromEntries(['expected_mesos','expected_rolls','expected_booms'].map(key=>[key,run.reduce((t,r)=>t+(r.custom_plan?.[key]??0),0)]))}; + const expected_fd=sum(run,'expected_fd'),expected_mesos=sum(run,'expected_mesos'); + const toward=first.chain_target>last.target_stars?` of ${first.steps} toward ${first.chain_target}★`:''; + return { + ...first, + target_stars:last.target_stars, + merged_steps:run.map(r=>`${r.current_stars}→${r.target_stars}`), + step_range:[first.step,last.step], + stat_gains, + expected_fd, + expected_mesos, + expected_rolls:sum(run,'expected_rolls'), + expected_booms:sum(run,'expected_booms'), + custom_plan:custom, + starforce_plan:[...plan.values()].sort((a,b)=>a.star-b.star).map(s=>({...s,recovery:s.star`${key}: +${value}`), + notes:[ + `Combines steps ${first.step}–${last.step}${toward} (${run.map(r=>`${r.current_stars}→${r.target_stars}★`).join(', ')}), which rank next to each other. FD per 1B is their combined average; the position comes from the first step.`, + // Only the first step's own rank cap matters; later steps were capped by steps inside this row. + ...new Set([...first.notes,...run.slice(1).flatMap(r=>r.notes).filter(note=>!note.startsWith('Ranked no higher than the previous step'))].filter(note=>!/^Step \d+ of \d+ toward/.test(note))), + ], + }; +} +// Consecutive stars of one item and plan that sit next to each other in the list read as one upgrade. +export function mergeSequential(rows){ + const out=[];let run=[]; + for(const r of rows){ + const prev=run[run.length-1]; + if(prev&&continues(prev,r))run.push(r); + else{if(run.length)out.push(mergeRun(run));run=r.kind==='starforce'&&r.steps>1?[r]:[];if(!run.length)out.push(r);} + } + if(run.length)out.push(mergeRun(run)); + return out; } diff --git a/web/scanner.css b/web/scanner.css index 08650a6..5af435a 100644 --- a/web/scanner.css +++ b/web/scanner.css @@ -216,7 +216,7 @@ body{height:100vh;min-height:0;display:flex;flex-direction:column;overflow:hidde .gear-cost { margin-top:10px; padding-top:8px; border-top:1px solid #ffffff20; } .gear-cost .fl-help { margin:6px 0 0; font-size:11px; } .roster-card[draggable=true]{cursor:grab}.roster-card.dragging{opacity:.45;cursor:grabbing;outline:2px dashed var(--accent)} -.sf-item-modes{margin-top:16px}.sf-mode-fields{margin-top:12px}.sf-mode-fields>.sub{margin:8px 0 0} +.sf-item-target .input{width:4.5em;margin-right:4px}.sf-item-target label{display:flex;align-items:center}.sf-item-modes{margin-top:16px}.sf-mode-fields{margin-top:12px}.sf-mode-fields>.sub{margin:8px 0 0} /* Per-attempt modes: range presets, then a slider per attempt with its odds and cost. */ .sf-presets{display:flex;flex-wrap:wrap;align-items:flex-end;gap:10px 16px;padding:12px 14px;border:1px solid var(--border);border-radius:10px;background:var(--surface-2)} .sf-presets>span{display:flex;flex-direction:column;margin-right:auto}.sf-presets small{color:var(--text-muted);font-size:11px} From 0476a4ac831d2088e95f9ac42bccc14134e2feff Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 01:24:39 -0600 Subject: [PATCH 2/6] Tidy the Star Force and gear detail panels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Collapse the own-modes table into one card whose header row shows the current modes with an Edit/Hide toggle. It opens when the switch is turned on and starts collapsed when modes are already set. - Merge the separate "Current Star Force" card into the cost section, which is now titled "Star Force", and shorten the custom-modes text. - Move the per-item scan button next to "Scan equipped gear…" and drop the hover hint. - Show "Edit flame stats" only on the Flame tab. Co-Authored-By: Claude Opus 5.5 --- web/app.js | 5 +++-- web/enhancement.js | 13 ++++++++----- web/scanner.css | 6 +++--- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/web/app.js b/web/app.js index 18bec8c..99c37b8 100644 --- a/web/app.js +++ b/web/app.js @@ -65,12 +65,13 @@ async function render(){ if(epoch!==renderEpoch)return; const slots=all.layout.slots;if(!slots[slot])slot=Object.keys(slots)[0]; let item=profile.equipment[slot]||{},pot=item.potential; - const detailMarkup=()=>`

${esc(human(slot))}

${esc(item.name||'Not scanned yet')}

${page==='equipment'?`

${item.flameable===false?'No flames':item.stats?'Flame score '+item.flame_score?.toFixed(1):'Flames not scanned'} / ${item.cubeable===false?'No potential':item.potential?.rank||'Potential not scanned'}

`:''}

${item.required_level?'Level '+item.required_level:'Item level unknown'}${item.starforce?.status==='scanned'?' / '+item.starforce.stars+' stars':item.starforce?.status==='not_applicable'?' / No Star Force':item.starforce?' / Stars not scanned':''}

${page==='equipment'&&item.stats?.length?`
Flames / ${item.flame_score?.toFixed(1)} score${item.stats.map(s=>`

${esc(s.name)} +${s.value}${s.percent?'%':''}

`).join('')}
`:''}
${page==='starforce'?`

Current Star Force: ${item.starforce?.status==='scanned'?item.starforce.stars+' stars':'Not scanned'}

Recommendations below compare the next star, expected cost and destruction risk. Event settings apply to this character.

`:page==='flame'?(item.stats?item.stats.map(s=>`

${esc(s.name)} +${s.value}${s.percent?'%':''}

`).join('')+'

Flame score '+item.flame_score.toFixed(1)+'

':'No flame saved for this slot.'):(pot?`${potentialMarkup(item)}

${esc(item.equivalent?.label||'Equivalent')}: ${item.equivalent?.value?.toFixed(2)??'Unavailable'}%

${esc(item.equivalent?.formula||'')}

`:'No potential saved for this slot.')}
${['equipment','flame'].includes(page)&&item.name&&(item.flameable??slots[slot].flameable)!==false?'':''}

Hover the highlighted slot in Equipment to update all its readings. Keep the tooltip unobstructed.

${item.updated?`

Last saved ${esc(new Date(item.updated).toLocaleString())}

`:''}`; - view.innerHTML=`

${page==='equipment'?'Equipment':page==='flame'?'Flame':page==='starforce'?'Star Force':'Potential'} scanner

Capture your equipment, then hover each item. Stars, flames and potentials are saved together.

${equipGrid({characterId:selected,name:profile.name,slots,equipment:profile.equipment,captured:profile.equipment_captured,selected:slot,portraitExtra:refreshButton(selected,profile.name),slotClass:(key,saved)=>page!=='flame'?esc(saved?.potential?.rank||''):'',badge:(key,saved)=>page==='flame'&&saved?.stats?`${flameIcon}${saved.flame_score?.toFixed(1)||'0.0'}`:['equipment','starforce'].includes(page)&&saved?.starforce?.status==='scanned'?`${saved.starforce.stars}*`:''})}

${page==='flame'?'Numbers show flame score.':['equipment','starforce'].includes(page)?'Numbers show stars. Colored borders show potential tier.':'Borders show potential tier. Hover to see saved lines.'}

${detailMarkup()}
`; + const detailMarkup=()=>`

${esc(human(slot))}

${esc(item.name||'Not scanned yet')}

${page==='equipment'?`

${item.flameable===false?'No flames':item.stats?'Flame score '+item.flame_score?.toFixed(1):'Flames not scanned'} / ${item.cubeable===false?'No potential':item.potential?.rank||'Potential not scanned'}

`:''}

${item.required_level?'Level '+item.required_level:'Item level unknown'}${item.starforce?.status==='scanned'?' / '+item.starforce.stars+' stars':item.starforce?.status==='not_applicable'?' / No Star Force':item.starforce?' / Stars not scanned':''}

${page==='equipment'&&item.stats?.length?`
Flames / ${item.flame_score?.toFixed(1)} score${item.stats.map(s=>`

${esc(s.name)} +${s.value}${s.percent?'%':''}

`).join('')}
`:''}${page==='starforce'?'':`
${page==='flame'?(item.stats?item.stats.map(s=>`

${esc(s.name)} +${s.value}${s.percent?'%':''}

`).join('')+'

Flame score '+item.flame_score.toFixed(1)+'

':'No flame saved for this slot.'):(pot?`${potentialMarkup(item)}

${esc(item.equivalent?.label||'Equivalent')}: ${item.equivalent?.value?.toFixed(2)??'Unavailable'}%

${esc(item.equivalent?.formula||'')}

`:'No potential saved for this slot.')}
`}${page==='flame'&&item.name&&(item.flameable??slots[slot].flameable)!==false?'':''}
${item.updated?`

Last saved ${esc(new Date(item.updated).toLocaleString())}

`:''}`; + view.innerHTML=`

${page==='equipment'?'Equipment':page==='flame'?'Flame':page==='starforce'?'Star Force':'Potential'} scanner

Capture your equipment, then hover each item. Stars, flames and potentials are saved together.

${equipGrid({characterId:selected,name:profile.name,slots,equipment:profile.equipment,captured:profile.equipment_captured,selected:slot,portraitExtra:refreshButton(selected,profile.name),slotClass:(key,saved)=>page!=='flame'?esc(saved?.potential?.rank||''):'',badge:(key,saved)=>page==='flame'&&saved?.stats?`${flameIcon}${saved.flame_score?.toFixed(1)||'0.0'}`:['equipment','starforce'].includes(page)&&saved?.starforce?.status==='scanned'?`${saved.starforce.stars}*`:''})}

${page==='flame'?'Numbers show flame score.':['equipment','starforce'].includes(page)?'Numbers show stars. Colored borders show potential tier.':'Borders show potential tier. Hover to see saved lines.'}

${detailMarkup()}
`; const selectGear=key=>{ const x=pageScroller().scrollLeft,y=pageScroller().scrollTop; slot=key;item=profile.equipment[slot]||{};pot=item.potential; view.querySelector('.detail-panel').innerHTML=detailMarkup(); + view.querySelector('#scan-level').textContent='Scan '+human(slot); view.querySelectorAll('[data-slot]').forEach(b=>b.classList.toggle('selected',b.dataset.slot===slot)); bindDetail();dispose?.select?.(slot); pageScroller().scrollTo({left:x,top:y,behavior:'instant'}); diff --git a/web/enhancement.js b/web/enhancement.js index 642be01..a225838 100644 --- a/web/enhancement.js +++ b/web/enhancement.js @@ -31,6 +31,8 @@ const cubeBasis = 'Bright: 22M; Glowing: 12M per cube. Match current main-stat o export function mountEnhancement(root,{profile,page,slot,onSelect}) { let disposed=false,model=null,cube=localStorage.getItem('hascone.costCube')==='Glowing'?'Glowing':'Bright'; + // The own-modes table opens when the switch is turned on, and starts collapsed otherwise. + let modesOpen=false; let showScores=localStorage.getItem('hascone.flameScores')!=='false'; const totals=root.querySelector('#enhancement-totals'),selected=root.querySelector('#enhancement-selected'),panels=root.querySelector('#enhancement-panels'); totals.innerHTML='

Calculating equipment costs…

'; @@ -157,7 +159,8 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { try{const fresh=await api.post(`/api/characters/${profile.id}/equipment/${encodeURIComponent(slot)}/starforce-modes`,body);Object.assign(profile,fresh);await refresh();} catch(e){status.textContent=e.message;root.querySelectorAll('.sf-item-modes input,.sf-item-modes select').forEach(el=>el.disabled=false);} } - own.onchange=()=>{fields.hidden=!own.checked;save();}; + own.onchange=()=>{modesOpen=own.checked;fields.hidden=!own.checked;fields.open=own.checked;save();}; + fields.ontoggle=()=>{if(!fields.hidden)modesOpen=fields.open;}; sliders.forEach(el=>{el.oninput=()=>show(el);el.onchange=save;}); root.querySelectorAll('[data-stop]').forEach(stop=>stop.onclick=()=>{const el=stop.closest('.sf-mode-row').querySelector('[data-mode-star]');if(el.value===stop.dataset.stop)return;el.value=stop.dataset.stop;show(el);save();}); root.querySelectorAll('[data-preset]').forEach(select=>select.onchange=()=>{ @@ -174,7 +177,7 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { const basis='Expected cost from 0 stars to the scanned level, using the least-meso mode at each step and including recovery after destruction. Replacement items are excluded.'; totals.innerHTML=`

Current Star Force cost

${totalValue('Total',model.totals['Star Force'],rows.length)}

${rows.length} items${model.unpriced.starforce.length?' · Partial estimate':''}

${cfg.discount?'30% meso discount':'No meso discount'} · ${cfg.boom_reduction?'30% boom reduction':'No boom reduction'}

`; const item=model.items[slot]||{},current=item.starforce_current,gear=profile.equipment[slot]||{},modes=perStarModes(gear.starforce_modes); - const basisText=modes?`Expected cost from 0 stars to the scanned level using this item's modes (${modeSummary(modes)}), including recovery after destruction. Replacement items are excluded.`:basis; + const basisText=`${modes?"Expected cost from 0 stars to the scanned level using this item's custom modes, including recovery after destruction. Replacement items are excluded.":basis} Event settings apply to this character.`; const table=item.starforce_mode_table||[],picked=modes||{}; const presetValue=range=>{const pattern=PRESET_STARS[range].map(star=>String(picked[star]??1)).join(',');return PRESETS[range].some(([value])=>value===pattern)?pattern:'custom';}; const presetSelect=range=>table.some(r=>PRESET_STARS[range].includes(r.star))?``:''; @@ -182,12 +185,12 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { const index=Math.max(0,r.choices.findIndex(c=>String(c.mode)===String(picked[r.star]??1))),c=r.choices[index]; return `
${r.star} → ${r.star+1}
${r.choices.map((choice,i)=>``).join('')}
${chance(c.success)}${chance(c.boom)}${cost(c.cost)}
`; }; - const modeControls=gear.starforce?.status==='scanned'&&!item.mirror&&table.length?`

Enhancement modes for this item

Quick presetsApply a strategy to a range of stars${presetSelect('low')}${presetSelect('high')}
AttemptStrategySuccessBoomCost
${table.map(modeRow).join('')}

Safeguard (15–17★) and Mode 4 (18–21★) prevent destruction. Success, boom and cost are per attempt, with your event settings.

${modes?'The upgrade order and costs for this item use these modes.':'Off: each star uses whichever mode is cheapest, and the upgrade order also shows a fewest-booms plan.'}

`:''; + const modeControls=gear.starforce?.status==='scanned'&&!item.mirror&&table.length?`

Enhancement modes for this item

Modes${modes?esc(modeSummary(modes)):''}
Quick presetsApply a strategy to a range of stars${presetSelect('low')}${presetSelect('high')}
AttemptStrategySuccessBoomCost
${table.map(modeRow).join('')}

Safeguard (15–17★) and Mode 4 (18–21★) prevent destruction. Success, boom and cost are per attempt, with your event settings.

${modes?'The upgrade order and costs for this item use these modes.':'Off: each star uses whichever mode is cheapest, and the upgrade order also shows a fewest-booms plan.'}

`:''; const sf=gear.starforce||{},target=gear.starforce_target,limit=item.starforce_limit??sf.max_stars; const targetHint=target==null?'Blank: the upgrade order ranks only the next star.':target<=sf.stars?`Reached: ${sf.stars}★ already meets your ${target}★ target, so only the next star is ranked.`:limit!=null&&target>limit?`Above this item's ${limit}★ limit; steps are ranked up to ${limit}★.`:`The upgrade order ranks every star from ${sf.stars}★ to ${target}★.`; const targetField=sf.status==='scanned'&&!item.mirror?`
Target stars
`:''; const targetStatus=targetField?`

${esc(targetHint)}

`:''; - root.querySelector('#enhancement-selected').innerHTML=(current?`

Current Star Force cost

${totalValue('0 to '+current.stars+' stars',current.expected_mesos,1)}${targetField}

${number(current.expected_booms)} expected booms · Level ${current.level}

${targetStatus}

${basisText}

`:`

${esc(item.mirror||item.starforce_error||'Hover this item to scan its stars.')}

${targetField}${targetStatus}`)+modeControls+skipControls(); + root.querySelector('#enhancement-selected').innerHTML=(current?`

Star Force

${totalValue('0 to '+current.stars+' stars',current.expected_mesos,1)}${targetField}

${number(current.expected_booms)} expected booms · Level ${current.level}

${targetStatus}

${basisText}

`:`

${esc(item.mirror||item.starforce_error||'Hover this item to scan its stars.')}

${targetField}${targetStatus}`)+modeControls+skipControls(); bindTarget();bindModes(table,modes);bindSkips(); if(!selectionOnly){ panels.innerHTML=`

Current Star Force costs

Cost to reach scanned stars · Lowest cost first.

${rows.map(r=>`
`).join('')||'

Scan Star Force equipment to see costs.

'}
${unpriced('starforce')}
How costs are calculated

${basis}

Uses the discount and boom-reduction options above. These are modeled costs.

`; @@ -203,7 +206,7 @@ export function mountEnhancement(root,{profile,page,slot,onSelect}) { refresh(); const dispose=()=>{disposed=true;}; dispose.refresh=refresh; - dispose.select=key=>{slot=key;if(model&&!disposed)draw(true);}; + dispose.select=key=>{if(key!==slot)modesOpen=false;slot=key;if(model&&!disposed)draw(true);}; // undefined while loading; null when the item has no priced parts. dispose.combined=key=>model?(model.items[key]?.combined??null):undefined; return dispose; diff --git a/web/scanner.css b/web/scanner.css index 5af435a..681dafb 100644 --- a/web/scanner.css +++ b/web/scanner.css @@ -216,13 +216,13 @@ body{height:100vh;min-height:0;display:flex;flex-direction:column;overflow:hidde .gear-cost { margin-top:10px; padding-top:8px; border-top:1px solid #ffffff20; } .gear-cost .fl-help { margin:6px 0 0; font-size:11px; } .roster-card[draggable=true]{cursor:grab}.roster-card.dragging{opacity:.45;cursor:grabbing;outline:2px dashed var(--accent)} -.sf-item-target .input{width:4.5em;margin-right:4px}.sf-item-target label{display:flex;align-items:center}.sf-item-modes{margin-top:16px}.sf-mode-fields{margin-top:12px}.sf-mode-fields>.sub{margin:8px 0 0} +.sf-item-target .input{width:4.5em;margin-right:4px}.sf-item-target label{display:flex;align-items:center}.sf-item-modes{margin-top:16px}.sf-mode-fields{margin-top:12px;border:1px solid var(--border);border-radius:10px;overflow:hidden}.sf-mode-fields>summary{display:flex;align-items:center;gap:14px;padding:10px 14px;background:var(--surface-2);cursor:pointer;list-style:none}.sf-mode-fields>summary::-webkit-details-marker{display:none}.sf-mode-fields>summary:hover{background:var(--surface-3)}.sf-mode-fields>summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}.sf-fields-label{color:var(--text-muted);font-size:11px;text-transform:uppercase;letter-spacing:.4px}.sf-fields-summary{flex:1;min-width:0;font-size:13px}.sf-fields-toggle{display:flex;align-items:center;gap:6px;color:var(--accent);font-size:12px;font-weight:600;white-space:nowrap}.sf-fields-toggle::before{content:'Edit'}.sf-mode-fields[open] .sf-fields-toggle::before{content:'Hide'}.sf-fields-toggle::after{content:'';width:6px;height:6px;border-right:2px solid currentColor;border-bottom:2px solid currentColor;transform:translateY(-2px) rotate(45deg);transition:transform .15s}.sf-mode-fields[open] .sf-fields-toggle::after{transform:translateY(2px) rotate(-135deg)}.sf-mode-fields[open]>summary{border-bottom:1px solid var(--border)}.sf-mode-fields>.sub{margin:0;padding:10px 14px;border-top:1px solid var(--border);font-size:12px}.sf-item-modes>#sf-modes-status{margin-top:8px} /* Per-attempt modes: range presets, then a slider per attempt with its odds and cost. */ -.sf-presets{display:flex;flex-wrap:wrap;align-items:flex-end;gap:10px 16px;padding:12px 14px;border:1px solid var(--border);border-radius:10px;background:var(--surface-2)} +.sf-presets{display:flex;flex-wrap:wrap;align-items:flex-end;gap:10px 16px;padding:12px 14px} .sf-presets>span{display:flex;flex-direction:column;margin-right:auto}.sf-presets small{color:var(--text-muted);font-size:11px} .sf-presets label{display:grid;gap:4px;font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.4px} .sf-presets select{min-width:140px;text-transform:none;letter-spacing:0} -.sf-modes-table{margin-top:10px;border:1px solid var(--border);border-radius:10px;overflow:hidden} +.sf-modes-table{border-top:1px solid var(--border)} .sf-mode-row{display:grid;grid-template-columns:72px minmax(240px,1fr) 64px 64px 76px;align-items:center;gap:14px;padding:10px 14px;border-top:1px solid var(--border)} .sf-mode-row.is-head{padding:8px 14px;border-top:0;background:var(--surface-2);color:var(--text-muted);font-size:11px;text-transform:uppercase;letter-spacing:.4px} .sf-mode-row.is-head span:nth-child(n+3){text-align:right} From fd705910bd423298f2251a56426caef4ec1af6fc Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 01:59:00 -0600 Subject: [PATCH 3/6] Snap capped whole-number fields to their max while typing One input listener for the whole page lowers any whole-number field with a max (Star Force target, Hyper Stat levels, flame values, swap levels and stars, Scouter tiles) to that max as soon as the typed value goes over it. It runs before each field's own handlers. Co-Authored-By: Claude Opus 5.5 --- tests/js/number-caps.test.cjs | 16 ++++++++++++++++ web/app.js | 4 +++- web/ui.js | 12 ++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 tests/js/number-caps.test.cjs diff --git a/tests/js/number-caps.test.cjs b/tests/js/number-caps.test.cjs new file mode 100644 index 0000000..af976e8 --- /dev/null +++ b/tests/js/number-caps.test.cjs @@ -0,0 +1,16 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const field=(value,{max='20',step=null,type='number'}={})=>({tagName:'INPUT',type,max,value:String(value),get valueAsNumber(){return this.value===''?NaN:Number(this.value);},getAttribute:name=>name==='step'?step:null}); +test('whole-number fields snap down to their max while typing',async()=>{ + const {capWholeNumber}=await import('../../web/ui.js'); + for(const [value,step] of [['25',null],['21','1'],['999','5']]){ + const el=field(value,{step}); + assert.equal(capWholeNumber(el),true); + assert.equal(el.value,'20'); + } +}); +test('values within the cap, blanks and non-whole fields are left alone',async()=>{ + const {capWholeNumber}=await import('../../web/ui.js'); + const cases=[field('20'),field('2'),field(''),field('25',{max:''}),field('80',{max:'75',step:'0.01'}),field('80',{max:'75',step:'any'}),field('25',{type:'text'})]; + for(const el of cases){const before=el.value;assert.equal(capWholeNumber(el),false);assert.equal(el.value,before);} +}); diff --git a/web/app.js b/web/app.js index 99c37b8..cde5aa6 100644 --- a/web/app.js +++ b/web/app.js @@ -8,7 +8,7 @@ import {mountHome} from './home.js'; import {mountProgression} from './progression.js'; import {mountPotentialWeights} from './potential_weights.js'; import {api} from './api.js'; -import {escapeHtml as esc,toast} from './ui.js'; +import {escapeHtml as esc,toast,capNumbersWhileTyping} from './ui.js'; import {mountScouter} from './pages/scouter.js'; import {watchScouterCompletion} from './scouter_completion.js'; import {mountHexa} from './pages/hexa.js'; @@ -23,6 +23,8 @@ import {createGearTooltip} from './components/gear_tooltip.js'; import {mountFlameWeights} from './flame_weights.js'; import {refreshButton} from './portrait.js'; import {equipGrid} from './components/equip_grid.js'; +// Capped whole-number fields never show a value above their max. +capNumbersWhileTyping(); let renderEpoch=0; const view=document.querySelector('#view'); let page='home',dispose=null,slot='hat',selected=localStorage.getItem('hascone.character'); diff --git a/web/ui.js b/web/ui.js index 20f8854..a93e96c 100644 --- a/web/ui.js +++ b/web/ui.js @@ -1,3 +1,15 @@ export function escapeHtml(value){return String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));} let timer; export function toast(message){const el=document.querySelector('#toast');el.textContent=message;el.classList.add('visible');clearTimeout(timer);timer=setTimeout(()=>el.classList.remove('visible'),6000);} +// A whole-number field (no step, or a whole step) at or over its max shows the max while typing. +export function capWholeNumber(el){ + if(el?.tagName!=='INPUT'||el.type!=='number'||el.max==='')return false; + const step=el.getAttribute('step'); + if(step!==null&&!Number.isInteger(Number(step)))return false; + const max=Number(el.max); + if(!Number.isFinite(max)||!(el.valueAsNumber>max))return false; + el.value=String(max); + return true; +} +// Runs before each field's own input handlers, so they only ever see the capped value. +export function capNumbersWhileTyping(root=document){root.addEventListener('input',e=>capWholeNumber(e.target),true);} From a4942c14d7b1e0c53853dace8b7c3dcde306917a Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 02:02:49 -0600 Subject: [PATCH 4/6] Add a launch config for a local test server Starts the app on port 5077 so it can run beside the installed app. Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .claude/launch.json diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..59d6446 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,13 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "hascone-dev", + "runtimeExecutable": ".venv/Scripts/python.exe", + "runtimeArgs": ["app.py", "--desktop"], + "env": {"HASCONE_PORT": "5077"}, + "port": 5077, + "url": "http://127.0.0.1:5077" + } + ] +} From 6009b0f5c077ba42c12906b6ae95116f304e8566 Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 02:32:10 -0600 Subject: [PATCH 5/6] Simplify target Star Force ranking and step merging - Send a capped flag instead of step and rank-cap note text, so the page no longer matches backend wording to merge steps. - Move step merging into its own module, separate from filtering. - Share one helper between the per-item modes and target endpoints. - Reuse star_limit in ranking and keep a typed target above the limit; ranking stops at the limit instead. - Drop row fields only tests read and bump the model version. Co-Authored-By: Claude Opus 5.5 --- app.py | 29 +++++--------- src/scouter/suggestions.py | 2 +- src/starforce/stats.py | 6 +-- src/starforce/suggestions.py | 10 ++--- tests/js/suggestion-filters.test.cjs | 23 +++++++---- tests/test_starforce_modes.py | 23 +++-------- web/pages/starforce-steps.js | 57 ++++++++++++++++++++++++++++ web/pages/suggestion-filters.js | 51 +------------------------ 8 files changed, 97 insertions(+), 104 deletions(-) create mode 100644 web/pages/starforce-steps.js diff --git a/app.py b/app.py index a2b1f61..cc0f1d0 100644 --- a/app.py +++ b/app.py @@ -299,40 +299,31 @@ def item_starforce_modes(identifier, slot): from starforce.cost import item_modes modes = item_modes((request.get_json(silent=True) or {}).get("modes")) - with characters.lock: - data = characters.load(identifier) - item = data["equipment"].get(slot) - if slot not in LAYOUT["slots"] or not isinstance(item, dict): - raise ValueError("Scan this item first") - if modes: - item["starforce_modes"] = modes - else: - item.pop("starforce_modes", None) - characters.write(data) - return character(identifier) + return _set_item_setting(identifier, slot, "starforce_modes", modes) @app.post("/api/characters//equipment//starforce-target") def item_starforce_target(identifier, slot): """Rank every star up to this item's target, or clear it to rank only the next star. - A target above the item's star limit is saved as that limit.""" + A target above the item's star limit is kept as typed; ranking stops at the limit.""" from starforce.cost import item_target - from starforce.stats import star_limit target = item_target((request.get_json(silent=True) or {}).get("target")) + return _set_item_setting(identifier, slot, "starforce_target", target) + + +def _set_item_setting(identifier, slot, key, value): + """Save a player setting on this slot's scanned item, or clear it when VALUE is empty.""" with characters.lock: data = characters.load(identifier) item = data["equipment"].get(slot) if slot not in LAYOUT["slots"] or not isinstance(item, dict): raise ValueError("Scan this item first") - limit = star_limit(slot, item) - if target is not None and limit is not None: - target = min(target, limit) - if target is None: - item.pop("starforce_target", None) + if value: + item[key] = value else: - item["starforce_target"] = target + item.pop(key, None) characters.write(data) return character(identifier) diff --git a/src/scouter/suggestions.py b/src/scouter/suggestions.py index ba97646..35d816d 100644 --- a/src/scouter/suggestions.py +++ b/src/scouter/suggestions.py @@ -26,7 +26,7 @@ from utils.payload_data import read_payload_json # Stamped on saved recommendations; bump it whenever the ranking math changes so saved results recompute. -MODEL_VERSION = 7 +MODEL_VERSION = 8 PROTECTED = {"Critical Damage %", "Skill Cooldown Reduction", "Item Drop Rate %", "Meso Amount %"} VALUE_METRICS = [ diff --git a/src/starforce/stats.py b/src/starforce/stats.py index 2407f42..961f0ed 100644 --- a/src/starforce/stats.py +++ b/src/starforce/stats.py @@ -62,16 +62,16 @@ def metadata(slot, item): } -def star_limit(slot, item): +def star_limit(slot, item, meta=None): """The most stars ITEM can reach: its scanned limit and its level's limit, whichever is lower. - None when neither is known.""" + Pass META when it is already loaded. None when neither limit is known.""" limits = [] scanned = (item.get("starforce") or {}).get("max_stars") if type(scanned) is int: limits.append(scanned) try: - limits.append(metadata(slot, item)["cap"]) + limits.append((meta or metadata(slot, item))["cap"]) except ValueError: pass return min(limits, default=None) diff --git a/src/starforce/suggestions.py b/src/starforce/suggestions.py index 8654997..96dc5da 100644 --- a/src/starforce/suggestions.py +++ b/src/starforce/suggestions.py @@ -11,7 +11,7 @@ def suggestions(slot, item, weights, gear, settings=None): current, cap = reading.get("stars"), reading.get("max_stars") if type(current) is not int or type(cap) is not int or not 0 <= current <= cap <= 30: raise ValueError("Invalid scanned Star Force count; scan again.") - cap = min(cap, meta["cap"]) + cap = stats.star_limit(slot, item, meta) if current >= cap: raise ValueError("This item is already at its star limit.") if gear["class"] == "Demon Avenger": @@ -52,15 +52,10 @@ def suggestions(slot, item, weights, gear, settings=None): chain_target = current + steps for row in rows: row.update(steps=steps, chain_target=chain_target) - if wanted is not None and wanted > current + 1: - row["notes"].append(f"Step {row['step']} of {steps} toward your {wanted}★ target.") if clamped is not None: - row["clamped_from"] = clamped row["notes"].append(f"Your {clamped}★ target is above this item's {cap}★ limit; ranked up to {cap}★.") if stopped is not None: row["notes"].append(f"Stops at {stopped}★: the next star has no positive modeled FD gain.") - if row["raw_fd_per_billion"] > row["fd_per_billion"]: - row["notes"].append("Ranked no higher than the previous step, which must be done first.") return rows @@ -85,13 +80,14 @@ def _step_rows(meta, cfg, modes, strategies, start, target, delta, gain, previou "current_stars": start, "target_stars": target, "step": prior["step"] + 1 if prior else 1, - "requires": f"{prior['current_stars']}→{prior['target_stars']}" if prior else None, "stat_gains": delta, **expected, "custom_plan": custom, "expected_fd": gain, "raw_fd_per_billion": raw, "fd_per_billion": min(raw, prior["fd_per_billion"]) if prior else raw, + # Held to the previous step's score; the page explains this beside the step. + "capped": bool(prior) and raw > prior["fd_per_billion"], # Steps tied by the cap sort by their first step's cost, so they stay together and in order. "rank_mesos": prior["rank_mesos"] if prior and raw >= prior["fd_per_billion"] diff --git a/tests/js/suggestion-filters.test.cjs b/tests/js/suggestion-filters.test.cjs index f914e6a..a876036 100644 --- a/tests/js/suggestion-filters.test.cjs +++ b/tests/js/suggestion-filters.test.cjs @@ -9,23 +9,20 @@ test('all optimized targets retain multiple choices per item',async()=>{ assert.equal(selectSuggestionRows(rows,'all-mesos','cube').length,2); assert.equal(selectSuggestionRows(rows,'all-booms','starforce')[0].strategy,'booms'); }); -const step=(slot,from,stepNo,steps,strategy='mesos',extra={})=>({slot,kind:'starforce',method:'Star Force',strategy,strategy_label:strategy==='mesos'?'Least mesos':'Fewest booms',current_stars:from,target_stars:from+1,step:stepNo,steps,chain_target:19+steps,requires:stepNo>1?`${from-1}→${from}`:null,expected_fd:1,expected_mesos:100*stepNo,expected_rolls:2,expected_booms:0.1,stat_gains:{'Attack Power':stepNo},starforce_plan:[{star:from,mode:1,recovery:false}],notes:[`Step ${stepNo} of ${steps} toward your 22★ target.`],fd_per_billion:10-stepNo,raw_fd_per_billion:10-stepNo,...extra}); +const step=(slot,from,stepNo,steps,strategy='mesos',extra={})=>({slot,kind:'starforce',method:'Star Force',strategy,strategy_label:strategy==='mesos'?'Least mesos':'Fewest booms',current_stars:from,target_stars:from+1,step:stepNo,steps,chain_target:19+steps,expected_fd:1,expected_mesos:100*stepNo,expected_rolls:2,expected_booms:0.1,stat_gains:{'Attack Power':stepNo},starforce_plan:[{star:from,mode:1,recovery:false}],notes:['Shared plan note.'],capped:false,fd_per_billion:10-stepNo,raw_fd_per_billion:10-stepNo,...extra}); test('best keeps one row per item, merging the target steps that follow it',async()=>{ const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js'); const rows=[step('face',19,1,3),step('face',20,2,3),{slot:'eye',kind:'flame',method:'Black Flame'},step('face',21,3,3),step('face',19,1,3,'booms'),{slot:'face',kind:'cube',method:'Bright'}]; const best=selectSuggestionRows(rows,'best'); assert.deepEqual(best.map(r=>[r.slot,r.kind,r.current_stars,r.target_stars]),[['face','starforce',19,21],['eye','flame',undefined,undefined]]); const merged=best[0]; - assert.deepEqual(merged.merged_steps,['19→20','20→21']); - assert.deepEqual(merged.step_range,[1,2]); assert.equal(merged.expected_mesos,300); assert.equal(merged.expected_booms,0.2); assert.deepEqual(merged.stat_gains,{'Attack Power':3}); assert.equal(merged.fd_per_billion,2/300*1e9); - assert.equal(merged.requires,null); assert.deepEqual(merged.starforce_plan.map(s=>s.star),[19,20]); assert.ok(merged.notes[0].startsWith('Combines steps 1–2 of 3 toward 22★')); - assert.ok(!merged.notes.some(n=>n.startsWith('Step '))); + assert.deepEqual(merged.notes.slice(1),['Shared plan note.']); }); test('best never places another item between rows of one item',async()=>{ const {selectSuggestionRows}=await import('../../web/pages/suggestion-filters.js'); @@ -35,14 +32,24 @@ test('best never places another item between rows of one item',async()=>{ assert.deepEqual(skipped.map(r=>[r.slot,r.current_stars,r.target_stars]),[['face',19,21],['eye',undefined,undefined]]); }); test('steps of different plans or items never merge',async()=>{ - const {mergeSequential}=await import('../../web/pages/suggestion-filters.js'); + const {mergeSequential}=await import('../../web/pages/starforce-steps.js'); const out=mergeSequential([step('face',19,1,3),step('face',20,2,3,'booms'),step('ring1',20,2,3),step('face',21,3,3)]); assert.equal(out.length,4); - assert.ok(out.every(r=>!r.merged_steps)); + assert.ok(out.every(r=>r.target_stars===r.current_stars+1&&r.notes.some(n=>/^Step \d of 3 toward 22★/.test(n)))); }); test('rows without a target are untouched',async()=>{ - const {mergeSequential}=await import('../../web/pages/suggestion-filters.js'); + const {mergeSequential}=await import('../../web/pages/starforce-steps.js'); const a={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:19,target_stars:20,steps:1}; const b={slot:'hat',kind:'starforce',strategy:'mesos',current_stars:20,target_stars:21,steps:1}; assert.deepEqual(mergeSequential([a,b]),[a,b]); }); +test('capped steps explain their rank once, alone or merged',async()=>{ + const {mergeSequential}=await import('../../web/pages/starforce-steps.js'); + const capped=note=>note.startsWith('Ranked no higher'); + const [alone]=mergeSequential([step('face',20,2,3,'mesos',{capped:true})]); + assert.equal(alone.notes.filter(capped).length,1); + const [merged]=mergeSequential([step('face',20,2,3,'mesos',{capped:true}),step('face',21,3,3,'mesos',{capped:true})]); + assert.equal(merged.notes.filter(capped).length,1); + const [uncappedFirst]=mergeSequential([step('face',19,1,3),step('face',20,2,3,'mesos',{capped:true})]); + assert.equal(uncappedFirst.notes.filter(capped).length,0); +}); diff --git a/tests/test_starforce_modes.py b/tests/test_starforce_modes.py index 98c25f5..ffca151 100644 --- a/tests/test_starforce_modes.py +++ b/tests/test_starforce_modes.py @@ -110,7 +110,7 @@ def test_target_validation(): def test_no_target_or_reached_target_ranks_only_the_next_star(): plain = suggestions("hat", HAT, ALL, HAT_GEAR) assert [(r["current_stars"], r["target_stars"], r["step"], r["steps"]) for r in plain] == [(19, 20, 1, 1)] * 2 - assert all(r["requires"] is None and r["fd_per_billion"] == r["raw_fd_per_billion"] for r in plain) + assert all(not r["capped"] and r["fd_per_billion"] == r["raw_fd_per_billion"] for r in plain) for reached in (19, 12): assert suggestions("hat", {**HAT, "starforce_target": reached}, ALL, HAT_GEAR) == plain @@ -120,7 +120,6 @@ def test_target_ranks_every_star_and_steps_add_up_to_the_whole_climb(): for strategy in ("mesos", "booms"): chain = [r for r in rows if r["strategy"] == strategy] assert [(r["current_stars"], r["target_stars"], r["step"]) for r in chain] == [(19, 20, 1), (20, 21, 2), (21, 22, 3)] - assert [r["requires"] for r in chain] == [None, "19→20", "20→21"] assert all(r["steps"] == 3 and r["chain_target"] == 22 for r in chain) whole = cost.optimize(150, 19, 22, objective=strategy) for key in ("expected_mesos", "expected_rolls", "expected_booms"): @@ -140,8 +139,7 @@ def test_capped_step_keeps_its_predecessors_score_and_cost_rank(): assert second["raw_fd_per_billion"] > first["fd_per_billion"] assert second["fd_per_billion"] == first["fd_per_billion"] assert second["rank_mesos"] == first["rank_mesos"] == first["expected_mesos"] - assert any(n.startswith("Ranked no higher") for n in second["notes"]) - assert not any(n.startswith("Ranked no higher") for n in first["notes"]) + assert second["capped"] and not first["capped"] def test_target_above_the_items_limit_is_clamped(): @@ -149,7 +147,7 @@ def test_target_above_the_items_limit_is_clamped(): "starforce": {"status": "scanned", "stars": 18, "max_stars": 20}, "starforce_target": 25} rows = suggestions("hat", item, ALL, {"class": "Shadower", "equipment": {"hat": item}}) assert sorted({r["target_stars"] for r in rows}) == [19, 20] - assert all(r["clamped_from"] == 25 and r["chain_target"] == 20 for r in rows) + assert all(r["chain_target"] == 20 and any(n.startswith("Your 25★ target is above") for n in r["notes"]) for r in rows) def test_chain_stops_at_a_star_with_no_modeled_gain(): @@ -176,20 +174,11 @@ def test_target_route_saves_and_clears(client): assert post(client, f"/api/characters/{ID}/equipment/top/starforce-target", {"target": 22}).status_code == 400 -def test_target_route_lowers_a_target_above_the_items_limit(client): +def test_target_route_keeps_a_target_above_the_items_limit(client): + # Ranking stops at the limit, so the typed target survives a later item with a higher limit. path = f"/api/characters/{ID}/equipment/hat/starforce-target" p = characters.load(ID) - # Scanned limit: 20 stars. p["equipment"]["hat"] = {"name": "Hat", "starforce": {"status": "scanned", "stars": 17, "max_stars": 20}} characters.write(p) assert post(client, path, {"target": 25}).status_code == 200 - assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 20 - # Level limit: a level 130 item stops at 20 stars even when the scan reads 30. - p = characters.load(ID) - p["equipment"]["hat"] = {"name": "Royal Dunwitch Hat", "required_level": 130, - "starforce": {"status": "scanned", "stars": 17, "max_stars": 30}} - characters.write(p) - assert post(client, path, {"target": 28}).status_code == 200 - assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 20 - assert post(client, path, {"target": 19}).status_code == 200 - assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 19 + assert characters.load(ID)["equipment"]["hat"]["starforce_target"] == 25 diff --git a/web/pages/starforce-steps.js b/web/pages/starforce-steps.js new file mode 100644 index 0000000..ace6825 --- /dev/null +++ b/web/pages/starforce-steps.js @@ -0,0 +1,57 @@ +// Star Force steps toward an item's target: consecutive stars of one item's plan that sit +// next to each other in the list read as one upgrade. +const CAPPED_NOTE='Ranked no higher than the previous step, which must be done first.'; +const PLAN_TOTALS=['expected_mesos','expected_rolls','expected_booms']; +// R is the next star of PREV's Star Force plan for the same item. +export const continues=(prev,r)=>prev.kind==='starforce'&&r.kind==='starforce'&&r.slot===prev.slot&&r.strategy===prev.strategy&&r.current_stars===prev.target_stars; +const isTargetStep=r=>r.kind==='starforce'&&r.steps>1; +const sum=(rows,key)=>rows.reduce((total,r)=>total+(r[key]??0),0); +const cappedNotes=r=>r.capped?[CAPPED_NOTE]:[]; + +// A step shown alone names its place in the climb. +function single(r){ + return {...r,notes:[...r.notes,`Step ${r.step} of ${r.steps} toward ${r.chain_target}★.`,...cappedNotes(r)]}; +} +function mergeRun(run){ + if(run.length===1)return single(run[0]); + const first=run[0],last=run[run.length-1]; + const stat_gains={}; + for(const r of run)for(const [key,value] of Object.entries(r.stat_gains||{}))stat_gains[key]=(stat_gains[key]||0)+value; + const plan=new Map(); + for(const r of run)for(const s of r.starforce_plan||[])if(!plan.has(s.star)||plan.get(s.star).recovery)plan.set(s.star,s); + const totals=rows=>Object.fromEntries(PLAN_TOTALS.map(key=>[key,sum(rows,key)])); + const custom=first.custom_plan&&{...first.custom_plan,...totals(run.map(r=>r.custom_plan??{}))}; + const expected_fd=sum(run,'expected_fd'),combined=totals(run),fd_per_billion=expected_fd/combined.expected_mesos*1e9; + const toward=first.chain_target>last.target_stars?` of ${first.steps} toward ${first.chain_target}★`:''; + return { + ...first, + ...combined, + target_stars:last.target_stars, + stat_gains, + expected_fd, + custom_plan:custom, + starforce_plan:[...plan.values()].sort((a,b)=>a.star-b.star).map(s=>({...s,recovery:s.star`${key}: +${value}`), + // Every step of one plan shares its notes; only the first step's own rank cap matters, + // since later steps were capped by steps inside this row. + notes:[ + `Combines steps ${first.step}–${last.step}${toward} (${run.map(r=>`${r.current_stars}→${r.target_stars}★`).join(', ')}), which rank next to each other. FD per 1B is their combined average; the position comes from the first step.`, + ...first.notes, + ...cappedNotes(first), + ], + }; +} +export function mergeSequential(rows){ + const out=[];let run=[]; + const flush=()=>{if(run.length)out.push(mergeRun(run));run=[];}; + for(const r of rows){ + if(run.length&&continues(run[run.length-1],r)){run.push(r);continue;} + flush(); + if(isTargetStep(r))run=[r];else out.push(r); + } + flush(); + return out; +} diff --git a/web/pages/suggestion-filters.js b/web/pages/suggestion-filters.js index f1ba3c9..e59eaca 100644 --- a/web/pages/suggestion-filters.js +++ b/web/pages/suggestion-filters.js @@ -1,3 +1,4 @@ +import {continues,mergeSequential} from './starforce-steps.js'; export const filters = [ ['best','Best per item - meso plan','One recommendation per equipment slot, ranked by FD per meso. Star Force uses its least-meso plan; steps toward an item’s target that rank together are shown as one row.'], ['best-booms','Best per item - low-boom plan','One recommendation per equipment slot. Star Force uses its fewest-booms plan; steps toward an item’s target that rank together are shown as one row.'], @@ -8,9 +9,6 @@ export const filters = [ ['Bright','Bright cubes','Only Bright cube targets.'],['Glowing','Glowing cubes','Only Glowing cube targets.'], ['Star Force','Star Force','The next star, or every star up to the item\'s target, including least-meso and fewest-booms plans.'] ]; -const targetStep=r=>r.kind==='starforce'&&r.steps>1; -// R is the next star of PREV's Star Force plan for the same item. -const continues=(prev,r)=>prev.kind==='starforce'&&r.kind==='starforce'&&r.slot===prev.slot&&r.strategy===prev.strategy&&r.current_stars===prev.target_stars; export function selectSuggestionRows(rows,filter,scope=null){ const best=['best','best-booms'].includes(filter); const strategy=['best-booms','all-booms'].includes(filter)?'booms':'mesos'; @@ -22,55 +20,10 @@ export function selectSuggestionRows(rows,filter,scope=null){ const seen=new Set(),kept=[]; for(const r of selected){ if(!seen.has(r.slot)){seen.add(r.slot);kept.push(r);} - else if(targetStep(r)&&kept.length&&continues(kept[kept.length-1],r))kept.push(r); + else if(kept.length&&continues(kept[kept.length-1],r))kept.push(r); } selected=kept; } return mergeSequential(selected); } -const sum=(rows,key)=>rows.reduce((total,r)=>total+(r[key]??0),0); -function mergeRun(run){ - if(run.length===1)return run[0]; - const first=run[0],last=run[run.length-1]; - const stat_gains={}; - for(const r of run)for(const [key,value] of Object.entries(r.stat_gains||{}))stat_gains[key]=(stat_gains[key]||0)+value; - const plan=new Map(); - for(const r of run)for(const s of r.starforce_plan||[])if(!plan.has(s.star)||plan.get(s.star).recovery)plan.set(s.star,s); - const custom=first.custom_plan&&{...first.custom_plan,...Object.fromEntries(['expected_mesos','expected_rolls','expected_booms'].map(key=>[key,run.reduce((t,r)=>t+(r.custom_plan?.[key]??0),0)]))}; - const expected_fd=sum(run,'expected_fd'),expected_mesos=sum(run,'expected_mesos'); - const toward=first.chain_target>last.target_stars?` of ${first.steps} toward ${first.chain_target}★`:''; - return { - ...first, - target_stars:last.target_stars, - merged_steps:run.map(r=>`${r.current_stars}→${r.target_stars}`), - step_range:[first.step,last.step], - stat_gains, - expected_fd, - expected_mesos, - expected_rolls:sum(run,'expected_rolls'), - expected_booms:sum(run,'expected_booms'), - custom_plan:custom, - starforce_plan:[...plan.values()].sort((a,b)=>a.star-b.star).map(s=>({...s,recovery:s.star`${key}: +${value}`), - notes:[ - `Combines steps ${first.step}–${last.step}${toward} (${run.map(r=>`${r.current_stars}→${r.target_stars}★`).join(', ')}), which rank next to each other. FD per 1B is their combined average; the position comes from the first step.`, - // Only the first step's own rank cap matters; later steps were capped by steps inside this row. - ...new Set([...first.notes,...run.slice(1).flatMap(r=>r.notes).filter(note=>!note.startsWith('Ranked no higher than the previous step'))].filter(note=>!/^Step \d+ of \d+ toward/.test(note))), - ], - }; -} -// Consecutive stars of one item and plan that sit next to each other in the list read as one upgrade. -export function mergeSequential(rows){ - const out=[];let run=[]; - for(const r of rows){ - const prev=run[run.length-1]; - if(prev&&continues(prev,r))run.push(r); - else{if(run.length)out.push(mergeRun(run));run=r.kind==='starforce'&&r.steps>1?[r]:[];if(!run.length)out.push(r);} - } - if(run.length)out.push(mergeRun(run)); - return out; -} From c7810699633b5431ea135cffc3fbb799cc71d271 Mon Sep 17 00:00:00 2001 From: Eric Joseph Pham Date: Wed, 11 Nov 2026 02:32:10 -0600 Subject: [PATCH 6/6] Remember each upgrade list's Show filter Each page and section keeps its own choice across tab switches and reloads. Co-Authored-By: Claude Opus 5.5 --- web/pages/scouter-suggestions.js | 13 +++++++++---- web/pages/scouter.js | 2 +- web/progression.js | 1 + 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/web/pages/scouter-suggestions.js b/web/pages/scouter-suggestions.js index d97bc9c..fe48afe 100644 --- a/web/pages/scouter-suggestions.js +++ b/web/pages/scouter-suggestions.js @@ -25,10 +25,16 @@ function flameDetails(row) { return `

Example improving flames

${money(row.expected_mesos)} buys the first modeled FD improvement on average. It is not the cost to hit any specific example. The +${number(row.expected_fd,4)}% shown above averages all qualifying results.

${row.flame_examples.map(example=>`
${esc(example.label)}
+${number(example.fd_gain,4)}% FD
${example.stats.map(stat=>`
${esc(stat)}
`).join('')}
`).join('')}
`; } -export function createSuggestions(root, {onGenerate, onOptions=async()=>{}, scope=null, layout='list',showOptions=true}) { - let profile, dirty=false, busy=false, disposed=false, filter='best', savingOptions=false; +// SECTION names the page this panel sits on, so each page and layout keeps its own Show choice. +export function createSuggestions(root, {onGenerate, onOptions=async()=>{}, scope=null, layout='list',showOptions=true,section=scope||'all'}) { + const allowed=layout==='cards'?(scope==='cube'?['best','all','Bright','Glowing']:['best','best-booms','all']):filters.map(([value])=>value); + const filterKey=`hascone.suggestFilter.${section}.${layout}`; + let profile, dirty=false, busy=false, disposed=false, filter=storedFilter(), savingOptions=false; const urls=new Map(); const prefix=layout==='cards'?'upgrade':'sc'; + function storedFilter() { + try {const saved=localStorage.getItem(filterKey);return allowed.includes(saved)?saved:'best';} catch {return 'best';} + } root.dataset.collapsible='recommendations-'+layout; if(layout==='cards')root.classList.add('analysis-panel','upgrade-cards-panel'); root.innerHTML=`

${scope==='cube'?(layout==='cards'?'Potential upgrade order':'Potential gains by FD / meso'):scope==='starforce'?(layout==='cards'?'Star Force upgrade order':'Star Force gains by FD / meso'):scope==='flame'?'Flame gains by FD / meso':'Upgrade recommendations'}

More damage for your mesos · ranked by estimated FD per 1B

${scope==='cube'?'

Follows your potential weight setting (Scouter or manual, above). This order ranks all positive FD gains per meso, including tiny gains; open Details to see qualifying rolls.

':''}
Star Force${[['mode_15_17','15–17★',[[1,'Mode 1'],[2,'Mode 2'],[3,'Mode 3'],['safeguard','Safeguard · no destruction']]],['mode_18_21','18–21★',[[1,'Mode 1'],[2,'Mode 2'],[3,'Mode 3'],[4,'Mode 4 · no destruction']]]].map(([key,label,choices])=>``).join('')}${[['discount','30% meso discount','Discounts the entire mode fee; excludes the Safeguard surcharge at 15–17★.'],['boom_reduction','30% destruction reduction','Applies to all modes through 21★.']].map(([key,label,hint])=>``).join('')}Ranking compares all modes for least mesos and fewest booms. Select a custom plan above to compare in the details. 22★+ uses standard rates.
`; @@ -86,10 +92,9 @@ export function createSuggestions(root, {onGenerate, onOptions=async()=>{}, scop details.innerHTML='Calculation details'+intro.innerHTML; intro.replaceWith(details); } - const allowed=scope==='cube'?['best','all','Bright','Glowing']:['best','best-booms','all']; body.querySelectorAll(`#${prefix}-suggest-filter option`).forEach(option=>{if(!allowed.includes(option.value))option.remove();}); } - body.querySelector(`#${prefix}-suggest-filter`).onchange=e=>{filter=e.target.value;render();body.querySelector(`#${prefix}-suggest-filter`).focus({preventScroll:true});}; + body.querySelector(`#${prefix}-suggest-filter`).onchange=e=>{filter=e.target.value;try{localStorage.setItem(filterKey,filter);}catch{}render();body.querySelector(`#${prefix}-suggest-filter`).focus({preventScroll:true});}; const id=profile.character.id; for(const img of body.querySelectorAll('[data-equip]')) { const path=`/api/characters/${encodeURIComponent(id)}/equipment/${encodeURIComponent(img.dataset.equip)}/icon?v=${encodeURIComponent(profile.gear_fingerprint||result.gear_fingerprint||'')}`; diff --git a/web/pages/scouter.js b/web/pages/scouter.js index 699cf75..8d94c9d 100644 --- a/web/pages/scouter.js +++ b/web/pages/scouter.js @@ -126,7 +126,7 @@ export async function mountScouter(view,{resultId=null}={}) { await save();const state=await api.post(`${endpoint()}/suggestions`,{}); lastSuggestions=state.active;suggestions.setBusy(state.active);status(state.message); if(!state.active)await load(); - }),onOptions:async options=>{ + }),section:'scouter',onOptions:async options=>{ await action(async()=>{await save();await api.post(`${endpoint()}/starforce-options`,options);await load();}); }}); diff --git a/web/progression.js b/web/progression.js index 2f22ced..3486577 100644 --- a/web/progression.js +++ b/web/progression.js @@ -10,6 +10,7 @@ export function mountProgression(view,character,page,onOptionsChanged=async()=>{ const scope=({potential:'cube',starforce:'starforce',flame:'flame'})[page]; const handlers={ scope, + section:page, onGenerate:async()=>{try{await api.post(endpoint+'/suggestions',{});signature='';await refresh();}catch(e){help.textContent=e.message;}}, onOptions:async value=>{await api.post(endpoint+'/starforce-options',value);await onOptionsChanged();signature='';await refresh();} };