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 | 'use client' // Abacus Studio — print-service panel (Phase 2b, Gitea #9). // // The right-side companion to the studio's control panel: submit the current // design to the paired THH print service as a multi-material 3MF + v2 ticket, // tune slicer settings through `@eink/print-dialog`'s schema-driven editor, // and watch the job move. All reads/writes go through abaci's own proxy // (#8.3) — the package client only ever sees the injected transport. // // Invariants this component holds: // • The settings editor is CONTROLLED — the TicketStyle here is the single // source of truth — and once opened it stays mounted (visibility toggles // via CSS), so solver re-runs and doorbell invalidations flow in as data, // never as a remount. // • Submission is v2-discipline: the ticket carries the editor's style // verbatim; per-key rejects render through `parseInvalidTicket` and the // service's `applied` clamp echoes feed straight back into the editor. // • The doorbell (#8.4) is a hint: rings invalidate the job queries and the // slow refetch below backstops missed rings (the ticket-sanctioned poll). import { type InvalidTicketDetail, type ParamScalarValue, parseInvalidTicket, type TicketStartPolicy, type TicketStyle, } from '@eink/print-dialog' import { PrintSettingsEditor } from '@eink/print-dialog/ui' import '@eink/print-dialog/ui/style.css' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMemo, useRef, useState } from 'react' import { usePrintJobRing } from '@/hooks/usePrintJobRing' import { useUserId } from '@/hooks/useUserId' import { createAbacusPrintClient } from '@/lib/abacus/print/browser-transport' import type { PrintUnavailableReason } from '@/lib/abacus/print/filament-wire' import { api } from '@/lib/queryClient' import { abacusPrintKeys } from '@/lib/queryKeys' import { buildAbacusThreeMf } from './abacus-3mf' import type { FilamentCatalog } from './abacus-catalog' import type { FilamentMap, Params } from './abacus-model' import { buildAbacusTicket } from './abacus-ticket' export interface PrintPanelProps { /** Rendered but hidden when false — internal state (style edits) survives. */ visible: boolean params: Params filamentMap: FilamentMap catalog: FilamentCatalog /** The discovered THH printer (multi-material preferred), or null. */ printerId: string | null unavailable: PrintUnavailableReason | null /** Solver gate — a design that won't print can't be submitted either. */ exportBlocked: boolean /** One-shot high-quality export render of the current params. */ requestExportStl: () => Promise<ArrayBuffer> } /** How long the export render may take before the submit gives up. */ const EXPORT_TIMEOUT_MS = 180_000 /** Host-named first-screen keys (#535) — the handful an abacus print actually * tweaks. Keys the capability document doesn't declare are dropped by the kit. */ const COMMON_KEYS = [ 'layer_height', 'sparse_infill_density', 'wall_loops', 'enable_support', 'brim_type', ] as const const UNAVAILABLE_COPY: Record<PrintUnavailableReason, string> = { 'not-configured': 'No print service paired — download the 3MF instead.', unreachable: 'Print service unreachable right now.', unauthorized: 'The print service rejected our credentials — re-pair to reconnect.', 'no-printer': 'The print service has no printers.', } /** A submit rejection, with the per-key detail when the body was invalid_ticket. */ class PrintSubmitError extends Error { readonly status: number readonly detail: InvalidTicketDetail | null constructor(status: number, body: unknown) { const detail = parseInvalidTicket(body) super( detail ? 'The print service rejected some settings — highlighted below.' : `Submit failed (${status}). Try again.` ) this.status = status this.detail = detail } } /** The service's clamp echoes (`style.applied`) from a submit response, if any. */ function extractApplied(body: unknown): Record<string, ParamScalarValue> | undefined { if (typeof body !== 'object' || body === null) return undefined const style = (body as { style?: unknown }).style if (typeof style !== 'object' || style === null) return undefined const applied = (style as { applied?: unknown }).applied if (typeof applied !== 'object' || applied === null) return undefined const out: Record<string, ParamScalarValue> = {} for (const [key, value] of Object.entries(applied)) { if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { out[key] = value } } return Object.keys(out).length > 0 ? out : undefined } type JobRow = { id: string; name: string; phase: string; progress: number | null } /** Defensive projection of the proxy's pass-through jobs read (open wire shape). */ function normalizeJobs(data: unknown): JobRow[] { const list = Array.isArray(data) ? data : typeof data === 'object' && data !== null && Array.isArray((data as { jobs?: unknown }).jobs) ? ((data as { jobs: unknown[] }).jobs as unknown[]) : [] const rows: JobRow[] = [] for (const item of list) { if (typeof item !== 'object' || item === null) continue const rec = item as Record<string, unknown> const id = [rec.jobId, rec.id].find((v): v is string => typeof v === 'string' && v.length > 0) if (!id) continue rows.push({ id, name: typeof rec.name === 'string' ? rec.name : id, phase: typeof rec.phase === 'string' ? rec.phase : typeof rec.status === 'string' ? rec.status : '—', progress: typeof rec.progress === 'number' ? rec.progress : null, }) } return rows } export function PrintPanel(props: PrintPanelProps) { const { visible, params, filamentMap, catalog, printerId, unavailable, exportBlocked, requestExportStl, } = props const queryClient = useQueryClient() const userId = useUserId().data ?? undefined // Doorbell listener: rings invalidate the job/filament queries read below. const ring = usePrintJobRing(userId) const serviceReady = unavailable === null && printerId !== null // ---- capabilities through the package client (ETag revalidation inside) --- const client = useMemo(() => createAbacusPrintClient(), []) const caps = useQuery({ queryKey: abacusPrintKeys.capabilities(), queryFn: () => client.getCapabilities(), enabled: visible && serviceReady, staleTime: 5 * 60_000, retry: 1, // contract-version skew is permanent — don't retry-storm it }) // ---- the controlled ticket style (single source of truth) ----------------- const [styleEdits, setStyleEdits] = useState<TicketStyle | null>(null) const seededStyle = useMemo<TicketStyle | null>(() => { const presets = caps.data?.basePresets if (!presets) return null const preset = presets.intents[presets.defaultIntent]?.preset return preset ? { basePreset: preset, process: {} } : null }, [caps.data]) const style = styleEdits ?? seededStyle const [settingsOpen, setSettingsOpen] = useState(false) // mount-once: after the first open the editor stays mounted, only hidden const settingsEverOpened = useRef(false) if (settingsOpen) settingsEverOpened.current = true const [startPolicy, setStartPolicy] = useState<TicketStartPolicy>('hold') // ---- submit --------------------------------------------------------------- // One idempotency key per submit intent: retries of a failed submit reuse it // (the service dedupes), a success mints fresh for the next job. const idemRef = useRef<string | null>(null) const submit = useMutation({ mutationFn: async (): Promise<unknown> => { if (!printerId) throw new Error('No printer available') if (!style) throw new Error('Print settings are still loading') const stl = await Promise.race([ requestExportStl(), new Promise<never>((_, reject) => setTimeout( () => reject(new Error("The 3D render didn't finish — try again")), EXPORT_TIMEOUT_MS ) ), ]) const model = buildAbacusThreeMf({ stl, params, filamentMap, slotLabels: catalog.spools.map((s) => s.name), }) idemRef.current ??= crypto.randomUUID() const ticket = buildAbacusTicket({ name: `Abacus — ${params.cols} columns`, source: { artifactId: `abacus-${params.cols}col-x${params.scale_factor}`, artifactUrl: `${window.location.origin}/create/abacus`, label: `${params.cols}-column abacus`, }, bodies: model.bodies, catalog, style, startPolicy, idempotencyKey: idemRef.current, }) const form = new FormData() form.set( 'model', new File([model.bytes as BlobPart], `abacus-${params.cols}col.3mf`, { type: 'model/3mf' }) ) form.set('job', JSON.stringify(ticket)) const res = await api(`abacus/print/printers/${encodeURIComponent(printerId)}/jobs`, { method: 'POST', body: form, }) const body: unknown = await res.json().catch(() => null) if (!res.ok) throw new PrintSubmitError(res.status, body) return body }, onSuccess: () => { idemRef.current = null queryClient.invalidateQueries({ queryKey: abacusPrintKeys.jobs() }) }, }) const invalidDetail = submit.error instanceof PrintSubmitError ? (submit.error.detail ?? undefined) : undefined const applied = useMemo(() => extractApplied(submit.data), [submit.data]) // ---- jobs roster (ring-invalidated; slow poll is the sanctioned backstop) -- const jobs = useQuery({ queryKey: abacusPrintKeys.jobs(), queryFn: async () => { const res = await api('abacus/print/jobs') if (!res.ok) throw new Error(`jobs read failed: ${res.status}`) return (await res.json()) as unknown }, enabled: visible && serviceReady, refetchInterval: 15_000, staleTime: 5_000, }) const jobRows = useMemo(() => normalizeJobs(jobs.data), [jobs.data]) const submitBlocked = exportBlocked || !serviceReady || !style || catalog.source !== 'thh-ams' || submit.isPending return ( <div data-component="abacus-studio-print-panel" style={{ position: 'absolute', top: 12, right: 12, width: settingsOpen ? 380 : 280, maxHeight: 'calc(100% - 24px)', overflowY: 'auto', display: visible ? 'flex' : 'none', flexDirection: 'column', gap: 10, padding: 12, borderRadius: 12, background: 'rgba(17,24,39,0.9)', border: '1px solid rgba(255,255,255,0.08)', color: 'rgba(226,232,240,0.95)', fontSize: 12, transition: 'width 0.15s ease', }} > <div style={{ fontWeight: 700, display: 'flex', alignItems: 'center', gap: 6 }}> <span aria-hidden="true">🖨</span> Print service {ring.connected && ( <span data-element="print-ring-live" title="Live job updates connected" style={{ fontSize: 10, color: 'rgba(74,222,128,0.9)', fontWeight: 600 }} > · live </span> )} </div> {unavailable !== null ? ( <div data-element="print-service-unavailable" style={{ color: 'rgba(148,163,184,0.95)' }}> {UNAVAILABLE_COPY[unavailable]} </div> ) : ( <> {/* start policy — hold is the cautious default for a first print */} <div data-element="print-start-policy" role="radiogroup" aria-label="When should the print start" style={{ display: 'flex', gap: 6 }} > {( [ { policy: 'hold', label: 'Hold for release' }, { policy: 'auto', label: 'Start right away' }, ] as const ).map(({ policy, label }) => ( <button key={policy} type="button" role="radio" aria-checked={startPolicy === policy} data-action="set-start-policy" data-policy={policy} onClick={() => setStartPolicy(policy)} style={{ flex: 1, padding: '6px 8px', borderRadius: 7, fontSize: 11, fontWeight: 600, cursor: 'pointer', border: startPolicy === policy ? '1px solid rgba(34,211,238,0.7)' : '1px solid rgba(255,255,255,0.14)', background: startPolicy === policy ? 'rgba(8,145,178,0.35)' : 'transparent', color: 'inherit', }} > {label} </button> ))} </div> <button type="button" data-action="submit-print-job" onClick={() => submit.mutate()} disabled={submitBlocked} title={ exportBlocked ? 'Fix the printability errors first' : catalog.source !== 'thh-ams' ? 'Waiting for the AMS filament roster' : 'Slice and print on the paired printer' } style={{ padding: '10px 12px', borderRadius: 8, border: 'none', background: submitBlocked ? 'rgba(75,85,99,0.55)' : 'linear-gradient(135deg, #06b6d4 0%, #0891b2 100%)', color: submitBlocked ? 'rgba(209,213,219,0.7)' : '#fff', fontSize: 13, fontWeight: 700, cursor: submitBlocked ? 'not-allowed' : 'pointer', }} > {submit.isPending ? 'Rendering & submitting…' : '🖨 Print this abacus'} </button> {submit.isSuccess && ( <div data-element="print-submit-success" style={{ padding: '8px 10px', borderRadius: 8, background: 'rgba(20,83,45,0.35)', border: '1px solid rgba(74,222,128,0.5)', color: 'rgba(220,252,231,0.96)', lineHeight: 1.45, }} > Job submitted{startPolicy === 'hold' ? ' — release it from the print service' : ''}. {applied && ' Some settings were adjusted by the printer — see the editor.'} </div> )} {submit.isError && ( <div data-element="print-submit-error" style={{ padding: '8px 10px', borderRadius: 8, background: 'rgba(127,29,29,0.35)', border: '1px solid rgba(248,113,113,0.5)', color: 'rgba(254,226,226,0.96)', lineHeight: 1.45, }} > {submit.error instanceof Error ? submit.error.message : 'Submit failed.'} </div> )} {/* settings disclosure — the editor mounts once and stays mounted */} <button type="button" data-action="toggle-print-settings" aria-expanded={settingsOpen} onClick={() => setSettingsOpen((v) => !v)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 2px', border: 'none', background: 'transparent', color: 'rgba(203,213,225,0.9)', fontSize: 12, fontWeight: 600, cursor: 'pointer', }} > <span>Print settings</span> <span aria-hidden="true">{settingsOpen ? '▾' : '▸'}</span> </button> {settingsEverOpened.current && ( <div data-element="print-settings-editor" style={{ display: settingsOpen ? 'block' : 'none' }} > {caps.isError ? ( <div style={{ color: 'rgba(252,165,165,0.95)', lineHeight: 1.45 }}> Couldn't load the printer's settings schema. </div> ) : caps.data && style ? ( <PrintSettingsEditor doc={caps.data} value={style} onChange={setStyleEdits} errors={invalidDetail} applied={applied} theme="dark" commonKeys={COMMON_KEYS} /> ) : ( <div style={{ color: 'rgba(148,163,184,0.95)' }}>Loading settings…</div> )} </div> )} {/* recent jobs — identifiers from the ring, truth from the proxy read */} {jobRows.length > 0 && ( <div data-element="print-jobs-list" style={{ display: 'flex', flexDirection: 'column', gap: 4 }} > <span style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.04em', color: 'rgba(148,163,184,0.9)', }} > Jobs </span> {jobRows.slice(0, 5).map((job) => ( <div key={job.id} data-element="print-job-row" style={{ display: 'flex', justifyContent: 'space-between', gap: 8, padding: '5px 8px', borderRadius: 6, background: 'rgba(255,255,255,0.05)', }} > <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', }} > {job.name} </span> <span style={{ color: 'rgba(148,163,184,0.95)', whiteSpace: 'nowrap' }}> {job.phase} {job.progress !== null && ` · ${Math.round(job.progress)}%`} </span> </div> ))} </div> )} </> )} </div> ) } |