All files / web/src/components/create/abacus two-stage-print.ts

96.63% Statements 574/594
95.32% Branches 102/107
90% Functions 18/20
96.63% Lines 574/594

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 5951x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 3x 3x 3x 3x 10x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 2x 2x 6x 3x 6x 6x 6x 1x 1x 1x 1x 1x 24x 24x 24x 24x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 1x 5x 5x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x             1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 5x 5x 4x 4x 3x 3x 3x 3x 3x 2x 2x 8x 1x 1x 8x 1x 1x 4x 4x 4x 4x 4x 4x     4x 1x 1x 2x 2x 2x 2x 2x 2x     2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x     5x 1x 1x 3x 3x 1x 3x     3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 5x 4x 5x 5x 5x 5x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 4x 4x 4x 2x 2x 4x 8x 8x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Two-stage feet print (Gitea #38 — THH split/chain, things-haunt-house#456).
 *
 * The printed TPU feet stand the frame `feet_proud` mm off the bed. A two-stage
 * print runs the layers below that seam from the EXTERNAL spool (soft TPU95 the
 * AMS can't feed) and everything above it from the AMS, off ONE slice: Stage A
 * is the full AMS filament list + `split`, Stage B the same list + `chain`. THH
 * admits Stage B only when its model bytes AND resolved filament plan equal
 * Stage A's, so everything here is a pure function of the design and rides
 * both tickets identically.
 *
 * This is an OPTION at submit time, never a design parameter: with a TPU-for-AMS
 * tray loaded the single-job path stays the default, and the feet geometry is
 * the same either way — only the feed source differs.
 */
import type {
  ParamScalarValue,
  TicketChain,
  TicketSplit,
  TicketSplitPartition,
  TicketStyle,
} from '@eink/print-dialog'
import { coPrintGroup, type FilamentCatalog, type FilamentSpool } from './abacus-catalog'
import type { FilamentMap, Params } from './abacus-model'
 
/** How the gateway cuts the layers below the seam (things-haunt-house#465). */
export type TwoStagePartition = TicketSplitPartition
 
/** Stage A: split the slice at the seam; the below-seam half prints from the
 *  external feed. The package leaves `feed` optional (single-filament splits
 *  need none); an abacus always lists more than one filament, so here it is
 *  required. */
export interface TwoStageSplit extends TicketSplit {
  readonly feed: { readonly external: true; readonly family: string }
  /** Absent = `'layer'`: Stage A is every layer below the seam. The feet-only
   *  variant sends `'seam-tool-model'`: Stage A keeps only filament 0's model
   *  runs — the feet — and Stage B returns to layer 1 for the supports and the
   *  tower, its travels lifted over the standing feet (things-haunt-house#465). */
  readonly partition?: TwoStagePartition
}
 
/**
 * Which two-stage print this is (Gitea #45). `'tpu-floor'` is the original mode:
 * everything below the seam — feet, support base, interface — prints in Stage A
 * from the external TPU spool and Stage B lands the body on that TPU floor.
 * `'feet-only'` is the experimental variant: Stage A prints ONLY the foot
 * stand-offs (the gateway keeps just the seam tool's model runs below the seam,
 * things-haunt-house#465) and Stage B goes back to layer 1 to print the support
 * body in the frame's own PLA (`role: 'support'`, things-haunt-house#466) around
 * the standing feet, then the abacus. Nothing but the feet is TPU on the plate —
 * the point of it: the second physical two-stage print (2026-09-09, #39) held
 * and then would not release, because the TPU floor bonded to smooth PEI and
 * prying the frame tore the feet off. Off by default, beside the TPU-floor mode.
 */
export type TwoStageVariant = 'tpu-floor' | 'feet-only'
export const DEFAULT_TWO_STAGE_VARIANT: TwoStageVariant = 'tpu-floor'
 
/** Stage B: consume the half Stage A retained. */
export interface TwoStageChain extends TicketChain {
  /** The operator has looked at the plate and says the prior stage's output is on it
   *  (things-haunt-house `chain.vouchedByOperator`). Every check this skips is the service
   *  INFERRING what is on the plate — the prior job's phase, and whether anything else has
   *  touched the printer since. A human standing at the printer is direct evidence, so it
   *  wins. What it cannot do is conjure the other half of a split: the service still refuses
   *  a chain it holds no retained half for, rather than print a whole model onto the parts. */
  readonly vouchedByOperator?: true
  /** Start Stage B with no human tap once the printer reports the external feed clear
   *  (things-haunt-house `chain.startWhenFeedClears`). Opt-in per ticket, off by default:
   *  it is the one field that lets the nozzle move with nobody having pressed anything.
   *  The service still parks the job while its sensor sees a spool, and every OTHER reason
   *  to park still waits for a tap — only the feed park clears itself. */
  readonly startWhenFeedClears?: true
}
 
/** Said in full before the operator vouches, because the service will not check any of it. */
export const STAGE_B_VOUCH_DISCLAIMER: readonly string[] = [
  'Look at the plate first. Nothing downstream of this button checks it.',
  "Stage B prints onto Stage A's parts. Missing, damaged or moved parts mean it prints into air.",
  "Clear off anything a failed attempt left behind — but leave Stage A's parts exactly where they are.",
  'The printer is not re-levelled and the first layer is not inspected, as on any chained stage.',
]
 
/** A filament-class overlay for one ticket entry: vector keys carry exactly one
 *  element (each `filament_{i}.json` describes one filament). */
export type SeamToolOverrides = Readonly<
  Record<string, ParamScalarValue | readonly [ParamScalarValue]>
>
 
/** The external feed's family. THH alias-folds it against filaments[0]'s family
 *  (TPU-AMS ≡ TPU), so an AMS "TPU for AMS" tray as filament 0 matches. */
export const TWO_STAGE_FEED_FAMILY = 'TPU'
 
/**
 * How much of the bed's back edge a two-stage plate leaves empty, in mm.
 *
 * THH's Stage B preamble homes Z on a clear spot and lays a purge lane, both in
 * a band along one bed edge OUTSIDE the union of everything printed — every
 * object, the wipe tower, brims: Orca's plate bbox. The back edge is the cheap
 * one: the Z-home spot wants 15 mm of keep-away plus 10 mm of edge, and the
 * purge lane sits at y 244–251 on a 256 bed, so a union ending under y 231
 * satisfies both (`gcode_split.py` clear_spot / purge_lane). A one-piece abacus
 * is well short of that on its own; a module kit packs to the bed and has to be
 * told (`packKitPlate` `rearBandMm`). Not sent to the service — it is abaci's
 * reading of the service's rule, so a plate refuses here instead of at split.
 */
export const TWO_STAGE_REAR_BAND_MM = 25
 
/**
 * `style.process` keys the mode owns, on BOTH stages (the identity gate needs the
 * same resolved plan). Seam solidity first: a split through a merged solid leaves
 * Stage A's top layers with no top shell (the foot's top is interior to the
 * feet+frame union), so Stage B's first layer lands on whatever infill the feet
 * have. The feet print solid on their own account — `FEET_PART_PROCESS`, a
 * per-part key in the 3MF that `--load-settings` leaves alone — so this style
 * adds only the interface shells, and the operator's infill density stays on the
 * frame and beads (a plate-wide 100 % here printed every bead solid).
 * things-haunt-house#462 is the gateway-side seam band that retires the shells.
 * The speeds are the soft-TPU95 recipe proven on the #456 coupon: the slice takes
 * filament 0's AMS-TPU profile and TPU95 slips at those speeds (things-haunt-house#461
 * retires this by applying a feed-side profile below the seam only).
 *
 * Interface floor (from the first physical two-stage print, 2026-09-08): nothing
 * rigid on the seam layer lands on a foot — the feet continue upward in TPU, and
 * every bit of PLA (frame bottom, every bead bottom) lands on the TPU support
 * interface. With the stock 0.2 mm top gap over a 0.5 mm-spaced interface that is a
 * bridge onto a release material, and after the hand-off the interface is at plate
 * temp rather than seconds-old nozzle heat, so the pick that carries a single job
 * is gone (two bead colours held, two didn't). PLA won't fuse to TPU, so the gap
 * isn't needed for release: zero gap on a solid interface is Orca's own recipe for
 * a dedicated support material, and it turns the interface into a floor. These
 * must ride the style too — the 3MF's `support_top_z_distance` is overridden by
 * THH's `--load-settings` on a submitted print.
 *
 * Plate contact (from the second physical two-stage print, 2026-09-09): the print
 * held — seam and floor both worked — and then would not come off the plate. Orca
 * prints support layer 0 as its own thing: `raft_first_layer_density` (the gateway
 * presets pin 90 %) with `raft_first_layer_expansion` (2 mm) grown around it, "the
 * first raft OR support layer" per the tooltips. Under a two-stage abacus that is a
 * near-solid TPU sheet the size of the frame, welded to smooth PEI: too flexible to
 * pop with the plate, too thin to get a wedge under, and prying the frame loads
 * the feet (the only TPU joined to anything above the seam) until they tear. A
 * sparse first layer with no expansion turns that sheet into a comb of single TPU
 * lines — a peel started at a corner walks along it — and leaves the feet as the
 * only solid contact, which is small enough to peel. Both keys are open in the
 * gateway policy. Brim stays the operator's editor choice (this block never sets
 * brim keys).
 */
export const TWO_STAGE_PROCESS: Readonly<Record<string, TicketStyle['process'][string]>> = {
  interface_shells: true,
  initial_layer_speed: 15,
  initial_layer_infill_speed: 18,
  initial_layer_acceleration: 300,
  outer_wall_speed: 25,
  inner_wall_speed: 30,
  sparse_infill_speed: 30,
  internal_solid_infill_speed: 30,
  top_surface_speed: 25,
  gap_infill_speed: 25,
  support_top_z_distance: 0,
  support_interface_spacing: 0,
  // Plate contact: support layer 0 as a sparse comb, not the preset's 90 % sheet
  // grown 2 mm past the support. Percent, like `sparse_infill_density`.
  raft_first_layer_density: 30,
  raft_first_layer_expansion: 0,
  // Orca already ignores this with a prime tower (every multi-filament abacus);
  // pinned so a single-filament slice keeps support layers on the model's layer
  // grid, which the seam-at-a-layer-boundary rule needs.
  independent_support_layer_height: false,
}
 
/** `filaments[0].overrides` — the seam tool's filament overlay, on BOTH stages:
 *  3 mm³/s max volumetric, a 40 °C plate, fan off for the first 3 layers. Same
 *  provenance as the process keys above (the #456 coupon recipe). */
export const TWO_STAGE_SEAM_TOOL_OVERRIDES: SeamToolOverrides = {
  filament_max_volumetric_speed: [3],
  hot_plate_temp_initial_layer: [40],
  hot_plate_temp: [40],
  textured_plate_temp_initial_layer: [40],
  textured_plate_temp: [40],
  close_fan_the_first_x_layers: [3],
}
 
/**
 * `style.process` keys the feet-only variant owns, on BOTH stages, INSTEAD of
 * `TWO_STAGE_PROCESS` (the two modes are different prints, not a delta):
 *  - `interface_shells` stays — Stage A's top layer is still the foot's interior.
 *  - the zero-gap contact keys ride ONLY with a dedicated support-interface spool
 *    (`FEET_ONLY_DEDICATED_INTERFACE_PROCESS`): the body is PLA now, and PLA on
 *    PLA at zero gap fuses; without a pick the preset gap (0.2 / 0.5) stands.
 *  - `raft_first_layer_expansion 0` is mandatory: Orca inflates support layer 0
 *    AFTER the blockers apply, and the preset's 2 mm would grow the base into the
 *    nozzle void around each foot. `raft_first_layer_density` goes back to the
 *    preset's 90 — a PLA base wants adhesion (the 30 % comb is for the TPU floor).
 *  - `brim_type no_brim`: a brim hugs the feet at `brim_object_gap` 0.1 mm and by
 *    role lands in Stage B at z 0.2 with the nozzle cone 1.4 mm below the foot
 *    top — a certain collision; routed to Stage A it is a TPU sheet welded to the
 *    feet. TPU on PEI needs no brim, the PLA support slab is large and flat, and
 *    the prime tower keeps its own brim under a separate key. The TPU-floor mode
 *    keeps the operator's editor choice.
 *  - the plate-wide slow-TPU95 speeds are gone: Stage B is PLA at normal speed,
 *    and filament 0's own overlay (3 mm³/s) still caps the feet in Stage A.
 *    One stays: `initial_layer_infill_speed`. Orca prints the frame's contact
 *    layer over the interface as the `Bottom surface` role and takes that GLOBAL
 *    key for it, bypassing object modifiers — so the support-transition modifier
 *    (region keys only) cannot cap it, and the gateway's transition check refused
 *    the first feet-only slice at 39.51 mm/s (2026-09-09). The TPU-floor mode
 *    covers it with its plate-wide 18.
 */
export const FEET_ONLY_PROCESS: Readonly<Record<string, TicketStyle['process'][string]>> = {
  interface_shells: true,
  /** = `SUPPORT_TRANSITION_SPEED_MM_S` (the test binds them): the Bottom-surface cap. */
  initial_layer_infill_speed: 25,
  raft_first_layer_density: 90,
  raft_first_layer_expansion: 0,
  brim_type: 'no_brim',
  independent_support_layer_height: false,
}
 
/** The zero-gap contact recipe (a floor, not a bridge), added to
 *  `FEET_ONLY_PROCESS` only when a dedicated support-interface spool is picked —
 *  a release material under the PLA, never PLA under PLA. */
export const FEET_ONLY_DEDICATED_INTERFACE_PROCESS: Readonly<
  Record<string, TicketStyle['process'][string]>
> = {
  support_top_z_distance: 0,
  support_interface_spacing: 0,
}
 
export interface TwoStageProcessOpts {
  readonly variant?: TwoStageVariant
  /** A support-interface spool other than the model's rides the ticket (feet-only only). */
  readonly dedicatedInterface?: boolean
}
 
/** The style a two-stage ticket rides: the operator's style with the mode's keys
 *  forced over it. The editor's value is untouched — this applies at submit. */
export function withTwoStageProcess(
  style: TicketStyle,
  opts: TwoStageProcessOpts = {}
): TicketStyle {
  const variant = opts.variant ?? DEFAULT_TWO_STAGE_VARIANT
  const keys =
    variant === 'feet-only'
      ? {
          ...FEET_ONLY_PROCESS,
          ...(opts.dedicatedInterface ? FEET_ONLY_DEDICATED_INTERFACE_PROCESS : {}),
        }
      : TWO_STAGE_PROCESS
  return { ...style, process: { ...style.process, ...keys } }
}
 
export type FeetOnlyUnavailableReason =
  /** A module kit: the per-foot blockers need every module's foot positions, and
   *  only the one-piece abacus has a TS mirror of the scad's FEET_POS. */
  | 'kit'
  /** The frame prints from the feet's own spool (the no-TPU fallback) — there is
   *  no separate PLA to print the supports in. */
  | 'frame-shares-feet-slot'
 
export type FeetOnlyAvailability =
  | { readonly ok: true }
  | { readonly ok: false; readonly reason: FeetOnlyUnavailableReason }
 
/** Whether the feet-only variant can ride this print (on top of `twoStageAvailability`). */
export function feetOnlyAvailability(input: {
  filamentMap: Pick<FilamentMap, 'frame' | 'feet'>
  kit: boolean
}): FeetOnlyAvailability {
  if (input.kit) return { ok: false, reason: 'kit' }
  const { frame, feet } = input.filamentMap
  if (feet === undefined || frame === feet) return { ok: false, reason: 'frame-shares-feet-slot' }
  return { ok: true }
}
 
/** Why the checkbox is muted — shown beside it, never only in a title (touch has no hover). */
export const FEET_ONLY_UNAVAILABLE_COPY: Record<FeetOnlyUnavailableReason, string> = {
  kit: 'Not on a module kit yet — the support blockers around each foot need every module’s foot positions.',
  'frame-shares-feet-slot':
    'The frame prints from the feet spool, so there is no PLA to print the supports in.',
}
 
/** What each stage does, per variant — the checkbox, the prep card and the
 *  hand-off all say it the same way. */
export const TWO_STAGE_VARIANT_COPY: Record<
  TwoStageVariant,
  { readonly stageA: string; readonly stageB: string }
> = {
  'tpu-floor': {
    stageA: 'prints the feet and the support floor below the seam from the external spool',
    stageB: 'chains the body onto that floor',
  },
  'feet-only': {
    stageA: 'prints only the feet — no supports, no tower — a few minutes',
    stageB: 'returns to the plate and prints PLA supports around the feet, then the abacus',
  },
}
 
export type TwoStageUnavailableReason =
  /** `feet_mode` isn't `'printed'`, or the plan placed no feet role. */
  | 'feet-not-printed'
  /** The catalog isn't the live AMS roster — nothing to chain on. */
  | 'no-roster'
  /** The feet already print from the external spool (the #19 no-AMS shape). */
  | 'feet-slot-external'
  /** The feet tray isn't TPU — a TPU95 external feed has nothing to bond to. */
  | 'feet-not-tpu'
 
export type TwoStageAvailability =
  | {
      readonly ok: true
      /** The AMS tray the feet print from — filament 0, the seam tool. */
      readonly feetSlot: FilamentSpool
      readonly feedFamily: string
      /** The seam: the frame's bottom face sits `feet_proud` mm above the plate. */
      readonly atZMm: number
    }
  | { readonly ok: false; readonly reason: TwoStageUnavailableReason }
 
/** Whether the design + roster can print in two stages, and the seam if so. */
export function twoStageAvailability(input: {
  params: Pick<Params, 'feet_mode' | 'feet_proud'>
  filamentMap: Pick<FilamentMap, 'feet'>
  catalog: FilamentCatalog
}): TwoStageAvailability {
  const { params, filamentMap, catalog } = input
  if (params.feet_mode !== 'printed' || filamentMap.feet === undefined) {
    return { ok: false, reason: 'feet-not-printed' }
  }
  if (catalog.source !== 'thh-ams') return { ok: false, reason: 'no-roster' }
  const feetSlot = catalog.spools[filamentMap.feet]
  if (!feetSlot) return { ok: false, reason: 'feet-not-printed' }
  if (feetSlot.external) return { ok: false, reason: 'feet-slot-external' }
  if (coPrintGroup(feetSlot.material) !== TWO_STAGE_FEED_FAMILY) {
    return { ok: false, reason: 'feet-not-tpu' }
  }
  return { ok: true, feetSlot, feedFamily: TWO_STAGE_FEED_FAMILY, atZMm: params.feet_proud }
}
 
function positiveNumber(v: unknown): number | null {
  const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN
  return Number.isFinite(n) && n > 0 ? n : null
}
 
/** The layer height the ticket style resolves to: an explicit process override,
 *  else the height in the preset's name ("0.20mm-standard"). null = not knowable
 *  here — THH's slice is the ground truth and fails `split_failed` if it misses. */
export function effectiveLayerHeightMm(style: TicketStyle | null): number | null {
  const explicit = positiveNumber(style?.process?.layer_height)
  if (explicit !== null) return explicit
  const m = style?.basePreset ? /(\d+(?:\.\d+)?)\s*mm/i.exec(style.basePreset) : null
  return m ? positiveNumber(m[1]) : null
}
 
export interface SeamCheck {
  readonly atZMm: number
  readonly layerHeightMm: number | null
  readonly firstLayerMm: number | null
  /** true only when the heights are KNOWN and the seam lands between layers —
   *  THH can only split on a layer boundary (`split_failed` otherwise, minutes
   *  into a slice rather than at submit). Unknown heights don't block. */
  readonly misses: boolean
}
 
/** Does the seam land on a layer boundary? `feet_proud` 1.6 is 8 layers at 0.2
 *  and 10 at 0.16 — but a 0.25 layer, or a 0.2 first layer over 0.16 layers, misses. */
export function checkSeam(atZMm: number, style: TicketStyle | null): SeamCheck {
  const layerHeightMm = effectiveLayerHeightMm(style)
  const firstLayerMm = positiveNumber(style?.process?.initial_layer_print_height) ?? layerHeightMm
  if (layerHeightMm === null || firstLayerMm === null) {
    return { atZMm, layerHeightMm, firstLayerMm, misses: false }
  }
  const k = (atZMm - firstLayerMm) / layerHeightMm
  const onBoundary = k > -1e-6 && Math.abs(k - Math.round(k)) < 1e-6
  return { atZMm, layerHeightMm, firstLayerMm, misses: !onBoundary }
}
 
/**
 * What the panel keeps between Stage A and Stage B. THH does not persist or echo
 * `split`, so the client is the only party that knows which job was a Stage A —
 * and Stage A prints for the better part of an hour, so this outlives the tab.
 */
export interface TwoStageRecord {
  readonly v: 1
  readonly printerId: string
  readonly stageAJobId: string
  /** SHA-256 (hex) of the Stage A model bytes. Stage B refuses to submit anything
   *  else: a chained job with DIFFERENT bytes isn't rejected by THH — it slices on
   *  its own and silently prints the whole model. */
  readonly modelSha256: string
  /** The design signature Stage A was built from, so the hand-off can say "the
   *  design changed" before a rebuild even starts. */
  readonly designSig: string
  readonly atZMm: number
  readonly feedFamily: string
  readonly name: string
  readonly submittedAt: number
  /** Set once Stage B is submitted, so the hand-off can point at its job card
   *  (and offer a re-submit if that job fails or is canceled before it starts). */
  readonly stageBJobId?: string
  /** Which two-stage print this is (Gitea #45). Absent on records written before
   *  the variant existed = the TPU-floor mode. Stage B reads it from HERE, never
   *  from the panel's checkbox — its plan has to be Stage A's. */
  readonly variant?: TwoStageVariant
  /** The support-interface pick Stage A rode (the feet-only variant lifts the
   *  filament-0 rule), so Stage B repeats the same resolved plan whatever the
   *  editor says by then. */
  readonly supportInterfaceSlotId?: string | null
}
 
/** The record's variant, with the pre-#45 default. */
export const recordVariant = (record: Pick<TwoStageRecord, 'variant'>): TwoStageVariant =>
  record.variant ?? DEFAULT_TWO_STAGE_VARIANT
 
type RecordStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
 
/** The browser's localStorage, or null where there is none (SSR, sandboxed frames). */
export function safeStorage(): RecordStorage | null {
  try {
    return typeof window === 'undefined' ? null : window.localStorage
  } catch {
    return null
  }
}
 
export const twoStageStorageKey = (printerId: string): string => `abacus.two-stage.${printerId}`
 
export function loadTwoStageRecord(
  storage: RecordStorage | null | undefined,
  printerId: string
): TwoStageRecord | null {
  try {
    const raw = storage?.getItem(twoStageStorageKey(printerId))
    if (!raw) return null
    const rec = JSON.parse(raw) as Partial<TwoStageRecord> | null
    return rec &&
      rec.v === 1 &&
      rec.printerId === printerId &&
      typeof rec.stageAJobId === 'string' &&
      typeof rec.modelSha256 === 'string' &&
      typeof rec.designSig === 'string' &&
      typeof rec.atZMm === 'number' &&
      (rec.variant === undefined || rec.variant === 'tpu-floor' || rec.variant === 'feet-only')
      ? (rec as TwoStageRecord)
      : null
  } catch {
    return null
  }
}
 
export function saveTwoStageRecord(
  storage: RecordStorage | null | undefined,
  record: TwoStageRecord
): void {
  try {
    storage?.setItem(twoStageStorageKey(record.printerId), JSON.stringify(record))
  } catch {
    // quota / private mode: the hand-off then lives only as long as the tab
  }
}
 
export function clearTwoStageRecord(
  storage: RecordStorage | null | undefined,
  printerId: string
): void {
  try {
    storage?.removeItem(twoStageStorageKey(printerId))
  } catch {
    // nothing to clear
  }
}
 
// ---- the unattended Stage B start (things-haunt-house `chain.startWhenFeedClears`) ----
//
// Off by default. On, Stage B is submitted with `chain.startWhenFeedClears`, and a Stage B
// parked ONLY because the external spool is still loaded starts itself the moment the
// printer's sensor reports the feed clear — no tap. It is a preference about the operator's
// own printer, not about a design, so it is kept once per browser rather than on the
// two-stage record; and it is read at submit, so flipping it never changes a job the
// service already holds. Its own key: it must not ride along when a record is forgotten.
 
export const UNATTENDED_START_STORAGE_KEY = 'abacus.print.start-when-feed-clears'
 
export function loadUnattendedStart(storage: RecordStorage | null | undefined): boolean {
  try {
    return storage?.getItem(UNATTENDED_START_STORAGE_KEY) === '1'
  } catch {
    return false
  }
}
 
export function saveUnattendedStart(storage: RecordStorage | null | undefined, on: boolean): void {
  try {
    if (on) storage?.setItem(UNATTENDED_START_STORAGE_KEY, '1')
    else storage?.removeItem(UNATTENDED_START_STORAGE_KEY)
  } catch {
    // quota / private mode: the choice then lives only as long as the tab
  }
}
 
/** The toggle's words. The label is the promise; `on` is the caveat that has to sit right
 *  under a ticked box, because the sensor reports the spool and nothing else. */
export const UNATTENDED_START_COPY = {
  label: 'Start Stage B by itself once the spool is out',
  on: 'On: submit Stage B now and go swap the spool — the moment the printer reports the external feed clear, the print starts with no tap. The sensor sees the spool, not the AMS tube, the door or your hands: pull the spool, reconnect the tube, close the door, and expect it to go.',
  off: 'Off: a Stage B submitted before the spool is out parks until you unload it, then waits for one tap on its job card.',
} as const
 
/** Hex SHA-256 of the model bytes — the same digest THH keys the retained half on. */
export async function sha256Hex(bytes: Uint8Array): Promise<string> {
  // A fresh copy: `bytes` may be a view into a larger (or shared) buffer.
  const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes))
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
}
 
/** The job id in a submit response, as the proxy relays it (`jobId`, `id`, or `job.id`). */
export function jobIdFromSubmitBody(body: unknown): string | null {
  if (!body || typeof body !== 'object') return null
  const rec = body as Record<string, unknown>
  const job = rec.job && typeof rec.job === 'object' ? (rec.job as Record<string, unknown>) : null
  const id = rec.jobId ?? rec.id ?? job?.id
  return typeof id === 'string' && id.length > 0 ? id : null
}
 
/** Stage B was asked for with a model whose bytes are not the ones Stage A shipped. */
export class TwoStageDriftError extends Error {
  readonly record: TwoStageRecord
  constructor(record: TwoStageRecord) {
    super(
      'The design changed since Stage A — its 3MF no longer matches the bytes the print service retained, and a chained job with different bytes would silently print the whole model. Print Stage A again, or restore the design.'
    )
    this.name = 'TwoStageDriftError'
    this.record = record
  }
}
 
/** What the hand-off card shows, from the record and the roster's phases. */
export type HandoffView =
  /** Stage A hasn't completed (phase null = not in the job list yet). */
  | { readonly kind: 'stage-a-running'; readonly phase: string | null }
  | { readonly kind: 'stage-a-ended'; readonly phase: string }
  /** `retry`: a submitted Stage B failed or was canceled before it started. */
  | { readonly kind: 'ready-for-b'; readonly retry: boolean }
  | { readonly kind: 'stage-b-open'; readonly phase: string | null }
  | { readonly kind: 'done' }
 
const ended = (phase: string | null): phase is string => phase === 'failed' || phase === 'canceled'
 
export function handoffView(
  record: TwoStageRecord,
  phaseOf: (jobId: string) => string | null
): HandoffView {
  if (record.stageBJobId) {
    const b = phaseOf(record.stageBJobId)
    if (b === 'completed') return { kind: 'done' }
    if (ended(b)) return { kind: 'ready-for-b', retry: true }
    return { kind: 'stage-b-open', phase: b }
  }
  const a = phaseOf(record.stageAJobId)
  if (a === 'completed') return { kind: 'ready-for-b', retry: false }
  if (ended(a)) return { kind: 'stage-a-ended', phase: a }
  return { kind: 'stage-a-running', phase: a }
}
 
/** The hand-off between the stages, in the order the operator does it. */
export const STAGE_B_HANDOFF_STEPS: readonly string[] = [
  'Leave the plate exactly where it is — Stage B prints onto the feet.',
  'Unload the external TPU95 spool and reconnect the AMS PTFE tube.',
  'Check the AMS TPU tray the feet were mapped to is still loaded.',
  'Print Stage B below — with the spool already out it starts straight away; submitted sooner, it parks until the printer sees the spool gone.',
]
 
/** The hand-off per variant: the feet-only Stage B goes back to layer 1 around
 *  the standing feet, so its first step says so; the spool swap is the same. */
export function stageBHandoffSteps(variant: TwoStageVariant): readonly string[] {
  if (variant === 'tpu-floor') return STAGE_B_HANDOFF_STEPS
  return [
    'Leave the plate exactly where it is — Stage B prints supports around the standing feet, then the abacus onto them.',
    ...STAGE_B_HANDOFF_STEPS.slice(1),
  ]
}
 
/**
 * What the operator must do at the printer BEFORE submitting Stage A. The gateway gates the
 * AMS-fed stage on the external spool being gone (`awaiting_spool_swap`) and, since
 * things-haunt-house #463, parks the external-fed stage on `awaiting_external_spool` while an
 * AMS tray is still at the nozzle. It cannot see whether the PTFE tube is pulled or what material
 * sits on the external spool, so the checklist stays.
 */
export const STAGE_A_PREP_STEPS: readonly string[] = [
  'Pull the AMS PTFE tube out of the toolhead inlet.',
  'Feed the external TPU95 spool through the external path until it reaches the nozzle.',
  'On the printer screen, set the external spool to TPU.',
  'Leave the AMS TPU tray the feet are mapped to loaded — Stage B chains from it.',
]