All files / src/apps/user/pages/agents/skills/run SkillRun.tsx

38.02% Statements 27/71
8.18% Branches 14/171
16.66% Functions 5/30
40.62% Lines 26/64

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 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713                                                                                                                                        1x     1x 6x 6x 3x       6x     1x                           1x                                                                                                                                                                                                 1x           1x                                                                                               1x                                                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x         1x                                     1x 6x 6x 6x 6x   6x     3x         18x       6x 6x     6x                                                                                 6x                                                        
import { makerLabel } from "@/objects/modelOrigin";
import CitationRow from "@/components/chat/Citations/CitationRow";
import RuleEvaluationList from "@/components/chat/ExecutionPipeline/RuleEvaluationList";
import {
  systemNodeIcon,
  systemNodeLabel,
} from "@/components/chat/ExecutionPipeline/nodeMeta";
import RichMarkdown from "@/components/chat/RichMarkdown/RichMarkdown";
import {
  DocumentDownloadProvider,
  DownloadPdfButton,
} from "@/components/document";
import {
  CopyButton,
  DetailPage,
  MetaGrid,
  MetaItem,
  RUN_STATUS,
  SectionCard,
  StatusBadge,
  useResourceId,
} from "@/components/detail";
import { Citation } from "@/objects/Model";
import { SkillRun, SkillRunStep } from "@/objects/Skill";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import { useQuery } from "@tanstack/react-query";
import {
  AlertTriangle,
  ArrowDownToLine,
  ArrowUpFromLine,
  BookOpen,
  Calendar,
  Clock,
  Coins,
  FileText,
  GitCommit,
  Hand,
  ListTree,
  Loader2,
  RotateCcw,
  ScanSearch,
  ShieldCheck,
  Sparkles,
  Wrench,
  XCircle,
  Zap,
} from "lucide-react";
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { describeCost, formatCount, formatUsd } from "@/components/cost";
import { decisionHref } from "@/routes/resourceHref";
import RunPausePanel from "./RunPausePanel";
import RunValue from "./RunValue";
import { formatElapsed, runDuration, skillHref } from "./runDisplay";
 
/**
 * One run of a skill: what it was asked, what came back, and how.
 *
 * Reads top to bottom the way someone checking a workflow's result does —
 * the typed outputs first (the reason the skill was run), then the full
 * answer, then the inputs that produced them, then the evidence: each node's
 * work, the governance rules that applied, and the sources it cited. A run
 * is a record, so there is no edit history; the skill revision it ran under
 * is linked instead.
 */
 
const POLL_MS = 2000;
 
/** Re-render once a second while a run is going, for the elapsed clock. */
const useTicker = (active: boolean) => {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    Eif (!active) return;
    const timer = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(timer);
  }, [active]);
  return now;
};
 
const RunningBanner: React.FC<{ run: SkillRun; now: number }> = ({
  run,
  now,
}) => (
  <div className="flex items-center gap-3 mb-4 px-4 py-3 rounded-xl border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/30">
    <Loader2 className="size-4 animate-spin text-blue-600 dark:text-blue-400 shrink-0" />
    <div className="text-sm text-blue-800 dark:text-blue-200">
      Running for {runDuration(run, now) ?? "a moment"}. Each node runs in
      turn; this page fills in when the skill finishes. You can leave — the run
      carries on and stays in the skill's run list.
    </div>
  </div>
);
 
const StepCard: React.FC<{ step: SkillRunStep; index: number }> = ({
  step,
  index,
}) => {
  const system = step.kind === "system";
  const tokens = step.input_tokens + step.output_tokens;
  return (
    <li className="relative pl-8">
      <span
        className={`absolute left-0 top-2.5 flex size-5 items-center justify-center rounded-full text-[10px] font-semibold ${
          step.error
            ? "bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300"
            : system
              ? "bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400"
              : "bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300"
        }`}
      >
        {index + 1}
      </span>
      <details
        open={!system}
        className="group rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/60"
      >
        <summary className="flex items-center gap-2 px-3 py-2 cursor-pointer select-none list-none">
          {system ? (
            <span className="text-gray-400">{systemNodeIcon(step.node_id)}</span>
          ) : (
            <Sparkles className="size-3.5 text-violet-500 shrink-0" />
          )}
          <span
            className={`text-sm truncate ${
              system
                ? "text-gray-600 dark:text-gray-400"
                : "font-mono font-semibold text-gray-800 dark:text-gray-100"
            }`}
          >
            {system ? systemNodeLabel(step.node_id) : step.node_id}
          </span>
          {step.error && (
            <StatusBadge status="failed" scale={RUN_STATUS} label="error" />
          )}
          <span className="ml-auto flex items-center gap-3 text-[11px] text-gray-400 shrink-0">
            {step.tool_calls.length > 0 && (
              <span className="flex items-center gap-0.5">
                <Wrench className="size-3" />
                {step.tool_calls.length}
              </span>
            )}
            {tokens > 0 && <span>{tokens.toLocaleString()} tok</span>}
          </span>
        </summary>
        <div className="px-3 pb-3 space-y-2 border-t border-gray-100 dark:border-gray-700 pt-2">
          {step.structured ? (
            <RunValue value={step.structured} />
          ) : step.output ? (
            <div className="max-h-72 overflow-y-auto">
              <RichMarkdown content={step.output} className="text-sm" />
            </div>
          ) : (
            <p className="text-xs text-gray-400 italic">No output.</p>
          )}
          {step.truncated && (
            <p className="text-[10px] text-gray-400 italic">
              Shortened — the full answer is in Result above.
            </p>
          )}
          {step.tool_calls.map((call, i) => (
            <details
              key={i}
              className="rounded-md bg-gray-50 dark:bg-gray-900/40 border border-gray-100 dark:border-gray-700"
            >
              <summary className="flex items-center gap-1.5 px-2 py-1 cursor-pointer text-xs text-gray-600 dark:text-gray-300">
                <Wrench className="size-3 text-gray-400" />
                <span className="font-mono">{call.name}</span>
                {call.error && (
                  <span className="text-red-500 text-[10px]">failed</span>
                )}
              </summary>
              <div className="px-2 pb-2 space-y-1">
                <pre className="text-[11px] font-mono whitespace-pre-wrap text-gray-600 dark:text-gray-400">
                  {JSON.stringify(call.args, null, 2)}
                </pre>
                {call.output && (
                  <pre className="text-[11px] font-mono whitespace-pre-wrap max-h-40 overflow-y-auto text-gray-500 dark:text-gray-400 border-t border-gray-100 dark:border-gray-700 pt-1">
                    {call.output}
                  </pre>
                )}
              </div>
            </details>
          ))}
        </div>
      </details>
    </li>
  );
};
 
/** The policy and audit nodes of the stored trace, in order. */
const ruleNodes = (trace: SkillRun["rule_trace"]) =>
  (trace ?? []).filter(
    (frame) => frame.type === "system_node_result" && frame.node_id,
  ) as Array<{ node_id: string; result: unknown }>;
 
/** Where each model's share of the run went — the split svc-ai measured. */
const CostByModel: React.FC<{ run: SkillRun }> = ({ run }) => {
  const rows = run.cost_detail ?? [];
  if (rows.length === 0) return null;
  return (
    <SectionCard
      icon={Coins}
      title="Cost by model"
      subtitle={`${run.llm_calls} model call${run.llm_calls === 1 ? "" : "s"}`}
      className="mb-4"
    >
      <table className="w-full text-xs">
        <thead>
          <tr className="text-left text-[10px] uppercase tracking-wide text-gray-400">
            <th className="font-medium pb-1">Model</th>
            <th className="font-medium pb-1 text-right">Calls</th>
            <th className="font-medium pb-1 text-right">Tokens in / out</th>
            <th className="font-medium pb-1 text-right">Cost</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
          {rows.map((row) => (
            <tr key={`${row.provider}/${row.model}`}>
              <td className="py-1.5 text-gray-700 dark:text-gray-200 break-all">
                {row.provider ? `${makerLabel(row.provider, row.model)} · ` : ""}
                <span className="font-mono">{row.model}</span>
              </td>
              <td className="py-1.5 text-right tabular-nums text-gray-700 dark:text-gray-200">
                {row.calls}
              </td>
              <td className="py-1.5 text-right tabular-nums text-gray-500 dark:text-gray-400">
                {formatCount(row.input_tokens)} / {formatCount(row.output_tokens)}
              </td>
              <td className="py-1.5 text-right tabular-nums text-gray-800 dark:text-gray-100">
                {row.cost_usd === null ? (
                  <span className="text-amber-600 dark:text-amber-400">unpriced</span>
                ) : (
                  formatUsd(row.cost_usd)
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </SectionCard>
  );
};
 
/** Every answer given to a pause, in order — part of the run's record. */
const Decisions: React.FC<{ run: SkillRun }> = ({ run }) => {
  const responses = run.responses ?? [];
  if (responses.length === 0) return null;
  return (
    <SectionCard icon={Hand} title="Decisions" className="mb-4">
      <ol className="space-y-2">
        {responses.map((r, i) => (
          <li key={i} className="text-sm text-gray-700 dark:text-gray-300">
            <span className="text-[11px] text-gray-400 mr-2">
              {parseServerDate(r.answered_at).toLocaleString(undefined, {
                dateStyle: "medium",
                timeStyle: "short",
              })}
            </span>
            {r.kind === "approval" ? (
              <>
                {r.approved ? "Approved" : "Rejected"}
                {r.node_id && (
                  <>
                    {" "}
                    before <span className="font-mono">{r.node_id}</span>
                  </>
                )}
                {r.feedback && (
                  <span className="text-gray-500 dark:text-gray-400">
                    {" "}
                    — “{r.feedback}”
                  </span>
                )}
              </>
            ) : Object.keys(r.answers ?? {}).length === 0 ? (
              "Skipped the questions"
            ) : (
              <>
                Answered:{" "}
                {Object.entries(r.answers ?? {})
                  .map(([k, v]) => `${k} = ${v.join(", ")}`)
                  .join(" · ")}
              </>
            )}
          </li>
        ))}
      </ol>
    </SectionCard>
  );
};
 
const RunBody: React.FC<{ run: SkillRun; now: number; skillId: string }> = ({
  run,
  now,
  skillId,
}) => {
  const { getApiHandler } = useApiHandler();
  const outputs = Object.entries(run.outputs ?? {});
  const inputs = Object.entries(run.inputs ?? {});
  const steps = run.steps ?? [];
  const skillSteps = steps.filter((s) => s.kind === "skill").length;
  const rules = ruleNodes(run.rule_trace);
  const citations = (run.citations ?? []) as unknown as Citation[];
  const duration = runDuration(run, now);
 
  return (
    <>
      {run.status === "running" && <RunningBanner run={run} now={now} />}
      {run.status === "awaiting_input" && (
        <RunPausePanel skillId={skillId} run={run} />
      )}
      {(run.status === "rejected" || run.status === "cancelled") && (
        <div className="flex items-start gap-2 mb-4 px-4 py-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 text-sm text-gray-700 dark:text-gray-300">
          <Hand className="size-4 shrink-0 mt-0.5" />
          <span>
            {run.status === "rejected"
              ? "Stopped at an approval gate — the reviewer did not approve the next step."
              : run.error ?? "Cancelled while waiting for input."}
          </span>
        </div>
      )}
      {(run.status === "failed" || run.status === "blocked") && run.error && (
        <div className="flex items-start gap-2 mb-4 px-4 py-3 rounded-xl border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/30 text-sm text-red-800 dark:text-red-200">
          <XCircle className="size-4 shrink-0 mt-0.5" />
          <span>{run.error}</span>
        </div>
      )}
      {run.warnings?.map((w) => (
        <div
          key={w}
          className="flex items-start gap-2 mb-4 px-4 py-3 rounded-xl border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/30 text-sm text-amber-800 dark:text-amber-200"
        >
          <AlertTriangle className="size-4 shrink-0 mt-0.5" />
          <span>{w}</span>
        </div>
      ))}
 
      <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm mb-4 p-5">
        <MetaGrid columns={4}>
          <MetaItem
            icon={Zap}
            label="Status"
            value={<StatusBadge status={run.status} scale={RUN_STATUS} />}
          />
          <MetaItem
            icon={GitCommit}
            label="Skill revision"
            value={
              run.skill_id && run.skill_version !== null ? (
                <Link
                  to={`${skillHref(run.skill_id)}?version=${run.skill_version}`}
                  title="Open the skill's history on the revision this run used"
                  className="text-sm text-violet-600 dark:text-violet-400 hover:underline"
                >
                  v{run.skill_version}
                </Link>
              ) : (
                <span className="text-sm text-gray-400">
                  {run.skill_id ? "—" : "skill deleted"}
                </span>
              )
            }
          />
          <MetaItem
            icon={Calendar}
            label="Started"
            value={
              <span className="text-sm text-gray-800 dark:text-gray-200">
                {parseServerDate(run.started_at).toLocaleString(undefined, {
                  dateStyle: "medium",
                  timeStyle: "short",
                })}
              </span>
            }
          />
          <MetaItem
            icon={Clock}
            label={run.status === "running" ? "Elapsed" : "Duration"}
            value={
              <span className="text-sm text-gray-800 dark:text-gray-200">
                {duration ?? "—"}
              </span>
            }
          />
          <MetaItem
            icon={Coins}
            label="Tokens"
            value={
              <span className="text-sm text-gray-800 dark:text-gray-200">
                {run.input_tokens.toLocaleString()} in ·{" "}
                {run.output_tokens.toLocaleString()} out
              </span>
            }
          />
          <MetaItem
            icon={Coins}
            label="Cost"
            value={
              <span
                className="text-sm text-gray-800 dark:text-gray-200 tabular-nums"
                title={
                  run.unpriced_calls
                    ? `${run.unpriced_calls} call(s) used a model with no price — the real cost is higher`
                    : undefined
                }
              >
                {run.llm_calls === 0 && run.cost_usd === null
                  ? "—"
                  : describeCost({
                      cost_usd: run.cost_usd,
                      unpriced: run.unpriced_calls,
                    }).text}
              </span>
            }
          />
          <MetaItem
            icon={ListTree}
            label="Nodes run"
            value={
              <span className="text-sm text-gray-800 dark:text-gray-200">
                {steps.length ? `${skillSteps} skill · ${steps.length - skillSteps} pipeline` : "—"}
              </span>
            }
          />
        </MetaGrid>
      </div>
 
      {outputs.length > 0 && run.status !== "awaiting_input" && (
        <SectionCard
          icon={ArrowUpFromLine}
          title="Outputs"
          subtitle="the skill's declared result"
          className="mb-4"
          action={
            <CopyButton
              value={JSON.stringify(run.outputs, null, 2)}
              label="Copy JSON"
            />
          }
        >
          <div className="space-y-4">
            {outputs.map(([name, value]) => (
              <div key={name}>
                <div className="flex items-center justify-between gap-2 mb-1">
                  <span className="text-[11px] font-mono font-medium text-violet-700 dark:text-violet-300">
                    {name}
                  </span>
                  <CopyButton
                    variant="bare"
                    value={
                      typeof value === "string"
                        ? value
                        : JSON.stringify(value, null, 2)
                    }
                  />
                </div>
                <RunValue value={value} />
              </div>
            ))}
          </div>
        </SectionCard>
      )}
 
      {run.output && (
        <SectionCard
          icon={FileText}
          title="Result"
          className="mb-4"
          action={<CopyButton value={run.output} label="Copy" />}
        >
          <DocumentDownloadProvider
            download={
              run.status === "completed" && run.skill_id
                ? (index, document) =>
                    getApiHandler().skill_router.downloadRunDocument(
                      skillId,
                      run.id,
                      index,
                      `${document.title}.pdf`,
                    )
                : null
            }
            imageUrl={
              run.status === "completed" && run.skill_id
                ? (asset) =>
                    getApiHandler().skill_router.runImageUrl(
                      skillId,
                      run.id,
                      asset,
                    )
                : null
            }
          >
            <RichMarkdown content={run.output} className="text-sm" />
          </DocumentDownloadProvider>
        </SectionCard>
      )}
 
      <SectionCard icon={ArrowDownToLine} title="Inputs" className="mb-4">
        <div className="space-y-3">
          {inputs.length > 0 ? (
            <RunValue value={run.inputs} />
          ) : (
            <p className="text-xs text-gray-400 italic">No form inputs.</p>
          )}
          {run.prompt && (
            <div>
              <div className="text-[10px] font-medium text-gray-400 uppercase tracking-wide mb-1">
                Instructions
              </div>
              <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap">
                {run.prompt}
              </p>
            </div>
          )}
          {run.task && (
            <details>
              <summary className="text-xs text-gray-400 dark:text-gray-500 cursor-pointer select-none">
                Task text the skill was given
              </summary>
              <pre className="mt-1 text-[11px] font-mono whitespace-pre-wrap bg-gray-50 dark:bg-gray-900/50 rounded-lg p-3 text-gray-600 dark:text-gray-400">
                {run.task}
              </pre>
            </details>
          )}
        </div>
      </SectionCard>
 
      <Decisions run={run} />
 
      {steps.length > 0 && (
        <SectionCard
          icon={ListTree}
          title="Steps"
          subtitle={`${steps.length} node${steps.length === 1 ? "" : "s"}, in the order they ran`}
          className="mb-4"
        >
          <ol className="space-y-2">
            {steps.map((step, i) => (
              <StepCard key={`${step.node_id}-${i}`} step={step} index={i} />
            ))}
          </ol>
        </SectionCard>
      )}
 
      {run.status !== "running" && (
        <SectionCard icon={ShieldCheck} title="Governance" className="mb-4">
          {rules.length === 0 ? (
            <p className="text-xs text-gray-400 italic">
              No governance rules applied to this run.
            </p>
          ) : (
            <div className="space-y-4">
              {rules.map((node) => (
                <RuleEvaluationList
                  key={node.node_id}
                  nodeId={node.node_id}
                  result={node.result}
                />
              ))}
            </div>
          )}
        </SectionCard>
      )}
 
      <CostByModel run={run} />
 
      {citations.length > 0 && (
        <SectionCard
          icon={BookOpen}
          title="Sources"
          subtitle={`${citations.length} cited`}
          className="mb-4"
        >
          <CitationRow citations={citations} />
        </SectionCard>
      )}
 
      {run.state && Object.keys(run.state).length > 0 && (
        <details className="mb-4">
          <summary className="text-xs text-gray-400 dark:text-gray-500 cursor-pointer select-none">
            Final state ({Object.keys(run.state).length} variables)
          </summary>
          <pre className="mt-2 text-[11px] font-mono bg-gray-50 dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-lg p-3 overflow-x-auto max-h-80 text-gray-600 dark:text-gray-400">
            {JSON.stringify(run.state, null, 2)}
          </pre>
        </details>
      )}
    </>
  );
};
 
/** A completed run with something to show has a PDF of it — its report, or
 *  its outputs laid out — rendered by svc-core from what the run stored. A
 *  run of a since-deleted skill has none: the route resolves the skill. */
const hasDocument = (run: SkillRun): boolean =>
  run.status === "completed" &&
  !!run.skill_id &&
  (Object.keys(run.outputs ?? {}).length > 0 || !!run.output?.trim());
 
const RunPdfButton: React.FC<{ skillId: string; run: SkillRun }> = ({
  skillId,
  run,
}) => {
  const { getApiHandler } = useApiHandler();
  return (
    <DownloadPdfButton
      download={() =>
        getApiHandler().skill_router.downloadRunDocument(
          skillId,
          run.id,
          0,
          `${run.skill_name}.pdf`,
        )
      }
    />
  );
};
 
const SkillRunViewer: React.FC = () => {
  const skillId = useResourceId("skillId");
  const runId = useResourceId("runId");
  const { getApiHandler } = useApiHandler();
  const navigate = useNavigate();
 
  const { data, isLoading, error } = useQuery<SkillRun | null>({
    queryKey: [QUERY_KEYS.GET.SKILL_RUN, skillId, runId],
    queryFn: () =>
      skillId && runId
        ? getApiHandler().skill_router.getRun(skillId, runId)
        : Promise.resolve(null),
    enabled: !!skillId && !!runId,
    refetchInterval: (query) =>
      (query.state.data as SkillRun | null | undefined)?.status === "running"
        ? POLL_MS
        : false,
  });
  const run: SkillRun | null = data ?? null;
  const now = useTicker(run?.status === "running");
 
  const actions =
    run && skillId
      ? [
          <button
            key="again"
            type="button"
            disabled={!run.skill_id}
            title={
              run.skill_id
                ? "Open the skill with this run's inputs filled in"
                : "The skill has been deleted"
            }
            onClick={() =>
              navigate(skillHref(skillId), {
                state: { rerun: { prompt: run.prompt, inputs: run.inputs } },
              })
            }
            className="flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 transition-colors"
          >
            <RotateCcw className="size-3" />
            Run again
          </button>,
          ...(hasDocument(run)
            ? [<RunPdfButton key="pdf" skillId={skillId} run={run} />]
            : []),
          // The run's decision record: its rules, checks, people, calls
          // and cost in one place, and what a reviewer of it would see.
          ...(decisionHref(run.invocation_id)
            ? [
                <Link
                  key="decision"
                  to={decisionHref(run.invocation_id)!}
                  className="flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                  <ScanSearch className="size-3" />
                  Why did it do this?
                </Link>,
              ]
            : []),
        ]
      : [];
 
  return (
    <DetailPage<SkillRun>
      resource={run}
      loading={isLoading}
      error={error}
      label="skill run"
      title={run ? run.skill_name : undefined}
      description={
        run
          ? `Run of ${parseServerDate(run.started_at).toLocaleString(undefined, {
              dateStyle: "medium",
              timeStyle: "short",
            })}${run.latency_ms !== null ? ` · ${formatElapsed(run.latency_ms)}` : ""}`
          : undefined
      }
      icon={<Zap className="size-12 text-violet-400 dark:text-violet-500" />}
      back={skillId ? skillHref(skillId) : undefined}
      actions={actions}
      // A run is a record of something that happened, not a resource anyone
      // edits — the revision it ran under is the skill's, linked in the body.
      history={false}
    >
      {(r) => <RunBody run={r} now={now} skillId={skillId ?? ""} />}
    </DetailPage>
  );
};
 
export default SkillRunViewer;