All files / web/src/components/create/abacus ParkedJobCard.tsx

100% Statements 266/266
83.87% Branches 52/62
87.5% Functions 7/8
100% Lines 266/266

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 2671x 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 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 21x 15x 15x 15x 15x 15x 15x 15x 15x 5x 1x 4x 1x 3x 10x 9x 1x 8x 1x 7x 1x 15x 15x 3x 3x 3x 15x 2x 2x 1x 1x 1x 1x 1x 2x 15x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 15x 15x 15x 14x 14x 14x 14x 14x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 21x 21x 14x 14x 15x 15x 15x 15x 10x 10x 10x 10x 10x 10x 10x 1x 9x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 9x 8x 1x 10x 15x 15x 15x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 15x 15x 15x 15x 15x 15x 15x 15x 15x  
// Abacus Studio — the parked-job resolver (Gitea #9).
//
// When an auto-start print can't just go — the bed isn't clear, a verdict
// failed, the printer paused mid-print for a nozzle check or on a fault of its
// own (its codes are linked to the printer's own pages, never explained) — THH parks the job
// and captures why. This card turns that standstill into something the user
// can act on in place: it shows the situation honestly (the service's own
// reason sentences + the latest bed photo) AND the remediation (start it
// anyway, or cancel it). Start is one tap: the reasons are on the card, the
// button says what it does, and a start can be undone from this same card
// seconds later. Stop on a running print is the one two-tap, because that
// cannot be undone.
//
// Presentational and hook-free of data: the roster read + the start/cancel
// mutations live in useAbacusPrintJobs; here everything arrives as props, so
// every state is reproducible in Storybook without a live print service. The
// only local state is UI ceremony (arming Stop, hiding a broken photo).
 
import { useState } from 'react'
import { button, notice, STUDIO } from '@/components/studio/theme'
import { isParked, type JobRow } from './print-jobs'
import type { SubmitFailure } from './print-submit-failure'
 
export interface ParkedJobCardProps {
  job: JobRow
  /** Acknowledge every parked reason and start. Codes are passed for you. */
  onStart: (acknowledge: string[]) => void
  /** Cancel (`false`) a parked job, or stop (`true`) one that's printing. */
  onCancel: (stopPrint: boolean) => void
  startPending?: boolean
  cancelPending?: boolean
  /** The service's honest reason a start was refused, if the last one was. */
  startFailure?: SubmitFailure | null
  /** The service's honest reason a cancel/stop was refused, if the last one was. */
  cancelFailure?: SubmitFailure | null
}
 
const amber = STUDIO.color.warnInline
 
function reasonText(job: JobRow): string {
  return job.attention.map((r) => r.detail ?? r.code).join('; ')
}
 
/** A start/cancel refusal, rendered with the same honest copy as the submit panel. */
function ActionError({ failure }: { failure: SubmitFailure }) {
  return (
    <div
      data-element="parked-job-error"
      data-error-code={failure.code}
      role="alert"
      style={notice('danger')}
    >
      <div style={{ ...STUDIO.type.strong, color: 'inherit' }}>{failure.headline}</div>
      {failure.remediation && (
        <div style={{ ...STUDIO.type.note, color: 'inherit', opacity: 0.85, marginTop: 2 }}>
          {failure.remediation}
        </div>
      )}
    </div>
  )
}
 
export function ParkedJobCard({
  job,
  onStart,
  onCancel,
  startPending = false,
  cancelPending = false,
  startFailure = null,
  cancelFailure = null,
}: ParkedJobCardProps) {
  // Stop is two-tap: the first tap arms, the second commits, onBlur disarms.
  // Start is not — see the header.
  const [stopArmed, setStopArmed] = useState(false)
  // A verdict-only park has no bed photo (404); hide the <img> when it fails.
  // Key the broken flag to updatedAt so a re-park's fresh frame gets a new try:
  // a different token makes frameBroken derive back to false with no effect.
  const frameToken = String(job.updatedAt ?? '')
  const [brokenToken, setBrokenToken] = useState<string | null>(null)
  const frameBroken = brokenToken === frameToken
 
  const parked = isParked(job.phase)
  const printing = job.phase === 'printing'
  const hasReasons = job.attention.length > 0
  // A chained Stage B (Gitea #38) the gateway prepared but refuses to start:
  // `chain_start_disabled` is the one reason acknowledging can't clear (the
  // gateway re-parks it), so the start button says so instead of round-tripping.
  const chainStartDisabled = job.attention.some((reason) => reason.code === 'chain_start_disabled')
  const hasUnverifiedProfile = job.attention.some((reason) =>
    reason.code.startsWith('filament_profile_unverified:')
  )
  // A mid-print pause the printer raised itself (THH `print_paused_fault` /
  // `print_paused`): the service reports the printer's own facts and no
  // diagnosis, and nothing resumes on its own — unlike the nozzle-confirm pause.
  const faultPause = job.attention.some((reason) => reason.code === 'print_paused_fault')
  const plainPause = job.attention.some((reason) => reason.code === 'print_paused')
 
  const title = printing
    ? faultPause
      ? 'Paused mid-print — the printer reported an error. Read its codes, then resume or stop at the printer.'
      : plainPause
        ? 'Paused mid-print — the printer reported no error. Resume or stop at the printer.'
        : 'Paused mid-print — confirm at the printer, then it resumes.'
    : job.phase === 'needs_attention'
      ? chainStartDisabled
        ? 'Prepared, but chained starts are switched off on this print service.'
        : hasUnverifiedProfile
          ? 'Review required — this filament was sliced with a fallback profile.'
          : 'Paused before printing — the printer flagged something to check.'
      : 'Sliced and waiting — start it when you’re ready.'
 
  const handleStart = () => {
    if (startPending) return
    onStart(job.attention.map((r) => r.code))
  }
  const handleStop = () => {
    if (cancelPending) return
    if (!stopArmed) {
      setStopArmed(true)
      return
    }
    setStopArmed(false)
    onCancel(true)
  }
  const handleCancel = () => {
    if (cancelPending) return
    onCancel(false)
  }
 
  return (
    <div
      data-component="abacus-parked-job-card"
      data-element="parked-job-card"
      data-phase={job.phase}
      // status, not alert: the card holds a polled camera frame and a live
      // phase/progress, so every print-ring invalidation would re-announce it.
      role="status"
      style={{
        ...notice('warn'),
        display: 'flex',
        flexDirection: 'column',
        gap: 6,
        marginTop: 6,
      }}
    >
      <div data-element="parked-job-title" style={{ ...STUDIO.type.strong, color: 'inherit' }}>
        <span aria-hidden="true">⏸ </span>
        {title}
      </div>
 
      {job.attention.length > 0 && !frameBroken && (
        // The service's latest camera view of the bed, so the override is an
        // informed one. Job-level endpoint (not the per-reason frameRef); 404s
        // to hidden for parks that carry no photo.
        // biome-ignore lint/performance/noImgElement: live camera JPEG streamed from the print proxy; next/image can't optimize a per-park dynamic frame
        <img
          data-element="parked-job-frame"
          src={`/api/abacus/print/jobs/${encodeURIComponent(job.id)}/attention-frame?t=${job.updatedAt ?? ''}`}
          alt="Latest camera view of the printer bed"
          onError={() => setBrokenToken(frameToken)}
          style={{ width: '100%', borderRadius: STUDIO.radius.notice, display: 'block' }}
        />
      )}
 
      {hasReasons && (
        <ul
          data-element="parked-job-reasons"
          style={{ margin: 0, paddingLeft: 16, display: 'flex', flexDirection: 'column', gap: 2 }}
        >
          {job.attention.map((reason) => (
            <li
              key={reason.code}
              data-element="parked-job-reason"
              data-reason-code={reason.code}
              style={{ color: amber, overflowWrap: 'anywhere' }}
            >
              {reason.detail ?? reason.code}
              {reason.printer && reason.printer.hms.length > 0 && (
                // Each code links to the printer maker's own page for it — the
                // printer's word on what its code means, not ours.
                <div data-element="parked-job-printer-codes" style={{ marginTop: 2 }}>
                  Printer codes:{' '}
                  {reason.printer.hms.map((alert, i) => (
                    <span key={alert.hex}>
                      {i > 0 && ', '}
                      {alert.wiki ? (
                        <a
                          data-element="parked-job-hms"
                          href={alert.wiki}
                          target="_blank"
                          rel="noreferrer"
                          style={{ color: 'inherit' }}
                        >
                          {alert.hex}
                        </a>
                      ) : (
                        <span data-element="parked-job-hms">{alert.hex}</span>
                      )}
                    </span>
                  ))}
                </div>
              )}
            </li>
          ))}
        </ul>
      )}
 
      <div style={{ display: 'flex', gap: 6 }}>
        {parked && (
          <button
            type="button"
            data-action="acknowledge-start"
            onClick={handleStart}
            disabled={startPending || chainStartDisabled}
            title={
              chainStartDisabled
                ? 'The print service refuses chained same-plate starts (CHAINED_START_ENABLED is off) — acknowledging cannot override it.'
                : undefined
            }
            aria-label={
              hasReasons ? `Acknowledge and start, despite: ${reasonText(job)}` : undefined
            }
            style={{
              ...button('primary', { disabled: startPending || chainStartDisabled }),
              flex: 1,
            }}
          >
            {startPending
              ? 'Starting…'
              : job.phase === 'needs_attention'
                ? 'Acknowledge & start'
                : 'Start print'}
          </button>
        )}
 
        {printing ? (
          <button
            type="button"
            data-action="stop-print"
            onClick={handleStop}
            onBlur={() => setStopArmed(false)}
            disabled={cancelPending}
            style={{ ...button('danger', { disabled: cancelPending }), flex: 1 }}
          >
            {cancelPending ? 'Stopping…' : stopArmed ? 'Stop the print?' : 'Stop print'}
          </button>
        ) : (
          parked && (
            <button
              type="button"
              data-action="cancel-job"
              onClick={handleCancel}
              disabled={cancelPending}
              style={{ ...button('secondary', { disabled: cancelPending }), color: 'inherit' }}
            >
              {cancelPending ? 'Canceling…' : 'Cancel'}
            </button>
          )
        )}
      </div>
 
      {startFailure && <ActionError failure={startFailure} />}
      {cancelFailure && <ActionError failure={cancelFailure} />}
    </div>
  )
}