@tangle-network/agent-app 0.46.35 → 0.46.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +6 -6
  2. package/dist/assets/index.js +18 -0
  3. package/dist/assets/index.js.map +1 -1
  4. package/dist/assets/schema.d.ts +657 -0
  5. package/dist/assistant/index.js +6 -6
  6. package/dist/chat-react/index.js +3 -3
  7. package/dist/chat-routes/index.js +1 -1
  8. package/dist/chat-store/index.js +1 -1
  9. package/dist/{chunk-MWEX2M6M.js → chunk-7ZPEJWDI.js} +27 -12
  10. package/dist/{chunk-MWEX2M6M.js.map → chunk-7ZPEJWDI.js.map} +1 -1
  11. package/dist/{chunk-YDOQE47G.js → chunk-PYDMEYWA.js} +20 -6
  12. package/dist/chunk-PYDMEYWA.js.map +1 -0
  13. package/dist/{chunk-EDTWGSQT.js → chunk-SJWIZT7B.js} +6 -2
  14. package/dist/{chunk-EDTWGSQT.js.map → chunk-SJWIZT7B.js.map} +1 -1
  15. package/dist/{chunk-JAYKCWW4.js → chunk-U2UAQTFY.js} +3 -3
  16. package/dist/chunk-U2UAQTFY.js.map +1 -0
  17. package/dist/{chunk-KKBTPZIE.js → chunk-Z4TPWP6A.js} +14 -4
  18. package/dist/chunk-Z4TPWP6A.js.map +1 -0
  19. package/dist/{chunk-4SGGSXI7.js → chunk-ZMMIQOFI.js} +6 -5
  20. package/dist/chunk-ZMMIQOFI.js.map +1 -0
  21. package/dist/{mention-editor-NDJAEMRP.js → mention-editor-CBLT6LE3.js} +2 -2
  22. package/dist/session-shell/index.js +1 -1
  23. package/dist/stream/index.js +1 -1
  24. package/dist/studio-react/index.js +3 -3
  25. package/dist/web-react/agent-session-controls.d.ts +11 -1
  26. package/dist/web-react/controls.d.ts +36 -2
  27. package/dist/web-react/index.d.ts +1 -1
  28. package/dist/web-react/index.js +6 -6
  29. package/dist/workspace-react/index.js +1 -1
  30. package/package.json +13 -13
  31. package/dist/chunk-4SGGSXI7.js.map +0 -1
  32. package/dist/chunk-JAYKCWW4.js.map +0 -1
  33. package/dist/chunk-KKBTPZIE.js.map +0 -1
  34. package/dist/chunk-YDOQE47G.js.map +0 -1
  35. /package/dist/{mention-editor-NDJAEMRP.js.map → mention-editor-CBLT6LE3.js.map} +0 -0
@@ -207,6 +207,11 @@ var OVERLAY_SHADOW = "shadow-[var(--shadow-overlay)]";
207
207
  function pickerRootClass(fullWidth) {
208
208
  return `relative ${fullWidth ? "flex w-full" : "inline-flex"}`;
209
209
  }
210
+ var QUIET_PICKER_TRIGGER_BASE = "inline-flex h-7 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md bg-transparent px-2 text-sm font-normal text-muted-foreground transition focus:outline-none focus-visible:ring-2 focus-visible:ring-ring";
211
+ var QUIET_PICKER_TRIGGER_INTERACTIVE = "hover:bg-accent hover:text-foreground data-[state=open]:bg-accent data-[state=open]:text-foreground";
212
+ function quietPickerTriggerClass({ interactive = true } = {}) {
213
+ return interactive ? `${QUIET_PICKER_TRIGGER_BASE} ${QUIET_PICKER_TRIGGER_INTERACTIVE}` : `${QUIET_PICKER_TRIGGER_BASE} cursor-default`;
214
+ }
210
215
  function usePending() {
211
216
  const [pending, setPending] = useState(false);
212
217
  const inFlight = useRef(false);
@@ -277,7 +282,7 @@ function ModelRow({
277
282
  }
278
283
  );
279
284
  }
280
- function ModelPicker({ value, onChange, models, loading, renderProviderBadge, recommendedLabel = "Recommended", priorityGroup }) {
285
+ function ModelPicker({ value, onChange, models, loading, renderProviderBadge, recommendedLabel = "Recommended", priorityGroup, variant = "chip" }) {
281
286
  const [open, setOpen] = useState(false);
282
287
  const [query, setQuery] = useState("");
283
288
  const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen);
@@ -320,7 +325,8 @@ function ModelPicker({ value, onChange, models, loading, renderProviderBadge, re
320
325
  ...triggerProps,
321
326
  "aria-controls": open ? panelId : void 0,
322
327
  onClick: () => setOpen(!open),
323
- className: "inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent",
328
+ "data-state": open ? "open" : "closed",
329
+ className: variant === "quiet" ? quietPickerTriggerClass() : "inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent",
324
330
  children: [
325
331
  selected ? renderProviderBadge ? renderProviderBadge(selected.provider) : /* @__PURE__ */ jsx2(ProviderLogo, { provider: selected.provider, size: 16 }) : /* @__PURE__ */ jsx2(SparkleGlyph, { className: "h-3.5 w-3.5 text-muted-foreground" }),
326
332
  /* @__PURE__ */ jsx2("span", { className: "max-w-[160px] truncate", children: selected?.name ?? value }),
@@ -427,7 +433,7 @@ function EffortMeter({ fill, className }) {
427
433
  i
428
434
  )) });
429
435
  }
430
- function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label = "Thinking", fullWidth = false }) {
436
+ function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label = "Thinking", fullWidth = false, variant = "chip" }) {
431
437
  const [open, setOpen] = useState(false);
432
438
  const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen);
433
439
  const panelId = useId();
@@ -443,7 +449,8 @@ function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label =
443
449
  "aria-controls": open ? panelId : void 0,
444
450
  onClick: () => setOpen(!open),
445
451
  title: label ? `${label} \u2014 how hard the agent reasons before answering` : "Reasoning effort",
446
- className: `inline-flex min-h-[36px] shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent ${fullWidth ? "w-full" : ""}`,
452
+ "data-state": open ? "open" : "closed",
453
+ className: `${variant === "quiet" ? quietPickerTriggerClass() : "inline-flex min-h-[36px] shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent"} ${fullWidth ? "w-full" : ""}`,
447
454
  children: [
448
455
  /* @__PURE__ */ jsx2(BrainGlyph, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
449
456
  /* @__PURE__ */ jsxs2("span", { className: fullWidth ? "flex-1 truncate text-left" : void 0, children: [
@@ -453,7 +460,13 @@ function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label =
453
460
  ] }) : null,
454
461
  selected ? selected.label : "\u2014"
455
462
  ] }),
456
- selected && isDeclared(selected.id) && /* @__PURE__ */ jsx2(EffortMeter, { fill: effortMeterFill(selected.id, levels), className: "shrink-0 text-foreground" }),
463
+ selected && isDeclared(selected.id) && /* @__PURE__ */ jsx2(
464
+ EffortMeter,
465
+ {
466
+ fill: effortMeterFill(selected.id, levels),
467
+ className: variant === "quiet" ? "shrink-0" : "shrink-0 text-foreground"
468
+ }
469
+ ),
457
470
  /* @__PURE__ */ jsx2(ChevronDown, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" })
458
471
  ]
459
472
  }
@@ -504,6 +517,7 @@ export {
504
517
  POPOVER_OPTION_FOCUS,
505
518
  OVERLAY_SHADOW,
506
519
  pickerRootClass,
520
+ quietPickerTriggerClass,
507
521
  usePending,
508
522
  ModelPicker,
509
523
  DEFAULT_EFFORT_LEVELS,
@@ -515,4 +529,4 @@ export {
515
529
  EffortMeter,
516
530
  EffortPicker
517
531
  };
518
- //# sourceMappingURL=chunk-YDOQE47G.js.map
532
+ //# sourceMappingURL=chunk-PYDMEYWA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-react/provider-logo.tsx","../src/web-react/controls.tsx"],"sourcesContent":["/**\n * Provider brand marks — real logo path data (simple-icons / SVG Logos, both\n * CC0) inlined so the picker shows actual provider identity instead of\n * colored-initial monograms. Providers without a usable mark fall back to a\n * tinted monogram chip. Aliases (z-ai/zai, moonshot/moonshotai, deepseek_ai)\n * normalize to one entry.\n */\n\nimport type { ReactNode } from 'react'\n\ninterface LogoDef {\n viewBox: string\n fill: string\n paths: string[]\n}\n\nconst LOGOS: Record<string, LogoDef> = {\n anthropic: { viewBox: '0 0 24 24', fill: '#D97757', paths: [\"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z\"] },\n google: { viewBox: '0 0 24 24', fill: '#8E75B2', paths: [\"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81\"] },\n deepseek: { viewBox: '0 0 24 24', fill: '#4D6BFE', paths: [\"M23.748 4.651c-.254-.124-.364.113-.512.233-.051.04-.094.09-.137.137-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.155-.708-.311-.955-.65-.172-.24-.219-.509-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.094.172.187.129.323-.082.28-.18.553-.266.833-.055.179-.137.218-.328.14a5.5 5.5 0 0 1-1.737-1.179c-.857-.828-1.631-1.743-2.597-2.46a12 12 0 0 0-.689-.47c-.985-.957.13-1.743.387-1.836.27-.098.094-.433-.778-.428-.872.003-1.67.295-2.687.685a3 3 0 0 1-.465.136 9.6 9.6 0 0 0-2.883-.101c-1.885.21-3.39 1.1-4.497 2.622C.082 8.776-.231 10.854.152 13.02c.403 2.284 1.568 4.175 3.36 5.653 1.857 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.132-.284 4.994-1.86.47.234.962.328 1.78.398.629.058 1.235-.031 1.705-.129.735-.155.684-.836.418-.961-2.155-1.004-1.682-.595-2.112-.926 1.095-1.295 2.768-3.598 3.284-6.733.05-.346.115-.834.108-1.114-.004-.171.035-.238.23-.257a4.2 4.2 0 0 0 1.545-.475c1.397-.763 1.96-2.016 2.093-3.517.02-.23-.004-.467-.247-.588M11.58 18.168c-2.088-1.642-3.101-2.183-3.52-2.16-.39.024-.32.472-.234.763.09.288.207.487.371.74.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.168-1.361-.801-2.5-1.86-3.301-3.306-.775-1.393-1.225-2.888-1.299-4.482-.02-.385.094-.522.477-.592a4.7 4.7 0 0 1 1.53-.038c2.131.311 3.946 1.264 5.467 2.774.868.86 1.525 1.887 2.202 2.89.72 1.066 1.494 2.082 2.48 2.915.348.291.626.513.892.677-.802.09-2.14.109-3.055-.615zm1.001-6.44a.306.306 0 0 1 .415-.287.3.3 0 0 1 .113.074.3.3 0 0 1 .086.214c0 .17-.136.307-.308.307a.303.303 0 0 1-.306-.307m3.11 1.596c-.2.081-.4.151-.591.16a1.25 1.25 0 0 1-.798-.254c-.274-.23-.47-.358-.551-.758a1.7 1.7 0 0 1 .015-.588c.07-.327-.007-.537-.238-.727-.188-.156-.426-.199-.689-.199a.6.6 0 0 1-.254-.078.253.253 0 0 1-.114-.358 1 1 0 0 1 .192-.21c.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.392.451.462.576.685.915.176.264.336.536.446.848.066.194-.02.353-.25.45\"] },\n mistral: { viewBox: '0 0 24 24', fill: '#FA520F', paths: [\"M17.143 3.429v3.428h-3.429v3.429h-3.428V6.857H6.857V3.43H3.43v13.714H0v3.428h10.286v-3.428H6.857v-3.429h3.429v3.429h3.429v-3.429h3.428v3.429h-3.428v3.428H24v-3.428h-3.43V3.429z\"] },\n xai: { viewBox: '0 0 24 24', fill: '#000000', paths: [\"M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z\"] },\n nvidia: { viewBox: '0 0 24 24', fill: '#76B900', paths: [\"M8.948 8.798v-1.43a6.7 6.7 0 0 1 .424-.018c3.922-.124 6.493 3.374 6.493 3.374s-2.774 3.851-5.75 3.851c-.398 0-.787-.062-1.158-.185v-4.346c1.528.185 1.837.857 2.747 2.385l2.04-1.714s-1.492-1.952-4-1.952a6.016 6.016 0 0 0-.796.035m0-4.735v2.138l.424-.027c5.45-.185 9.01 4.47 9.01 4.47s-4.08 4.964-8.33 4.964c-.37 0-.733-.035-1.095-.097v1.325c.3.035.61.062.91.062 3.957 0 6.82-2.023 9.593-4.408.459.371 2.34 1.263 2.73 1.652-2.633 2.208-8.772 3.984-12.253 3.984-.335 0-.653-.018-.971-.053v1.864H24V4.063zm0 10.326v1.131c-3.657-.654-4.673-4.46-4.673-4.46s1.758-1.944 4.673-2.262v1.237H8.94c-1.528-.186-2.73 1.245-2.73 1.245s.68 2.412 2.739 3.11M2.456 10.9s2.164-3.197 6.5-3.533V6.201C4.153 6.59 0 10.653 0 10.653s2.35 6.802 8.948 7.42v-1.237c-4.84-.6-6.492-5.936-6.492-5.936z\"] },\n meta: { viewBox: '0 0 24 24', fill: '#0467DF', paths: [\"M6.915 4.03c-1.968 0-3.683 1.28-4.871 3.113C.704 9.208 0 11.883 0 14.449c0 .706.07 1.369.21 1.973a6.624 6.624 0 0 0 .265.86 5.297 5.297 0 0 0 .371.761c.696 1.159 1.818 1.927 3.593 1.927 1.497 0 2.633-.671 3.965-2.444.76-1.012 1.144-1.626 2.663-4.32l.756-1.339.186-.325c.061.1.121.196.183.3l2.152 3.595c.724 1.21 1.665 2.556 2.47 3.314 1.046.987 1.992 1.22 3.06 1.22 1.075 0 1.876-.355 2.455-.843a3.743 3.743 0 0 0 .81-.973c.542-.939.861-2.127.861-3.745 0-2.72-.681-5.357-2.084-7.45-1.282-1.912-2.957-2.93-4.716-2.93-1.047 0-2.088.467-3.053 1.308-.652.57-1.257 1.29-1.82 2.05-.69-.875-1.335-1.547-1.958-2.056-1.182-.966-2.315-1.303-3.454-1.303zm10.16 2.053c1.147 0 2.188.758 2.992 1.999 1.132 1.748 1.647 4.195 1.647 6.4 0 1.548-.368 2.9-1.839 2.9-.58 0-1.027-.23-1.664-1.004-.496-.601-1.343-1.878-2.832-4.358l-.617-1.028a44.908 44.908 0 0 0-1.255-1.98c.07-.109.141-.224.211-.327 1.12-1.667 2.118-2.602 3.358-2.602zm-10.201.553c1.265 0 2.058.791 2.675 1.446.307.327.737.871 1.234 1.579l-1.02 1.566c-.757 1.163-1.882 3.017-2.837 4.338-1.191 1.649-1.81 1.817-2.486 1.817-.524 0-1.038-.237-1.383-.794-.263-.426-.464-1.13-.464-2.046 0-2.221.63-4.535 1.66-6.088.454-.687.964-1.226 1.533-1.533a2.264 2.264 0 0 1 1.088-.285z\"] },\n moonshotai: { viewBox: '0 0 24 24', fill: '#16191E', paths: [\"m1.053 16.91 9.538 2.55a21 20.981 0 0 0 .06 2.031l5.956 1.592a12 11.99 0 0 1-15.554-6.172m-1.02-5.79 11.352 3.035a21 20.981 0 0 0-.469 2.01l10.817 2.89a12 11.99 0 0 1-1.845 2.004L.658 15.918a12 11.99 0 0 1-.625-4.796m1.593-5.146L13.573 9.17a21 20.981 0 0 0-1.01 1.874l11.297 3.02a21 20.981 0 0 1-.67 2.362l-11.55-3.087L.125 10.26a12 11.99 0 0 1 1.499-4.285ZM6.067 1.58l11.285 3.016a21 20.981 0 0 0-1.688 1.719l7.824 2.091a21 20.981 0 0 1 .513 2.664L2.107 5.218a12 11.99 0 0 1 3.96-3.638M21.68 4.866 7.222 1.003A12 11.99 0 0 1 21.68 4.866\"] },\n openai: { viewBox: '0 0 256 260', fill: '#10A37F', paths: [\"M239.184 106.203a64.72 64.72 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.72 64.72 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.67 64.67 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.77 64.77 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483m-97.56 136.338a48.4 48.4 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.6 8.6 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601M37.158 197.93a48.35 48.35 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.34 8.34 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803M23.549 85.38a48.5 48.5 0 0 1 25.58-21.333v61.39a8.29 8.29 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.82.82 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405zm179.466 41.695l-63.08-36.63L161.73 77.86a.82.82 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.54 8.54 0 0 0-4.4-7.213m21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.72.72 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391zM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.6 8.6 0 0 0-4.246 7.367zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218z\"] },\n}\n\nconst ALIASES: Record<string, string> = {\n moonshot: 'moonshotai',\n deepseek_ai: 'deepseek',\n 'x-ai': 'xai',\n 'meta-llama': 'meta',\n}\n\nconst MONOGRAM: Record<string, { bg: string; fg: string }> = {\n cohere: { bg: '#fae8ff', fg: '#c026d3' },\n groq: { bg: '#fce7f3', fg: '#db2777' },\n cerebras: { bg: '#ccfbf1', fg: '#0d9488' },\n zai: { bg: '#ede9fe', fg: '#7c3aed' },\n 'z-ai': { bg: '#ede9fe', fg: '#7c3aed' },\n tuner: { bg: '#dbeafe', fg: '#2563eb' },\n}\n\nexport interface ProviderLogoProps {\n provider?: string\n size?: number\n}\n\n/** Real brand mark when we have one; tinted monogram otherwise. */\nexport function ProviderLogo({ provider, size = 16 }: ProviderLogoProps): ReactNode {\n const key = ALIASES[provider ?? ''] ?? provider ?? ''\n const logo = LOGOS[key]\n if (logo) {\n return (\n <svg width={size} height={size} viewBox={logo.viewBox} role=\"img\" aria-label={key}>\n {logo.paths.map((d, i) => (\n <path key={i} d={d} fill={logo.fill} />\n ))}\n </svg>\n )\n }\n // Unknown providers fall back to a neutral monogram drawn from theme tokens\n // (secondary tile, muted glyph) — the previous hardcoded grays (#f3f4f6 /\n // #6b7280) were tuned for light mode and read as a washed-out hole on dark.\n // `style` rather than the `fill` attribute so the var() references resolve.\n const mono = MONOGRAM[key]\n return (\n <svg width={size} height={size} viewBox=\"0 0 16 16\" role=\"img\" aria-label={key || 'model'}>\n <rect width=\"16\" height=\"16\" rx=\"4\" style={{ fill: mono ? mono.bg : 'hsl(var(--secondary))' }} />\n <text x=\"8\" y=\"11.6\" textAnchor=\"middle\" style={{ fill: mono ? mono.fg : 'hsl(var(--muted-foreground))' }} fontSize=\"9\" fontWeight=\"700\" fontFamily=\"system-ui, sans-serif\">\n {(key || '?').charAt(0).toUpperCase()}\n </text>\n </svg>\n )\n}\n","/**\n * Shared chat-shell control primitives — the LEAF that both the web-react barrel\n * (`./index`) and the composer children (`./agent-session-controls`,\n * `./seat-paywall`) import directly, so neither child has to reach back through\n * the barrel (which would re-create an import cycle). The barrel re-exports the\n * public names (`usePopover`, `usePending`, `ModelPicker`, `EffortPicker`, …)\n * unchanged, so the published export surface is identical.\n *\n * Styling contract matches the rest of `web-react`: Tailwind classes against the\n * shared design tokens; the glyphs are inline SVGs, no icon-library dependency.\n */\n\nimport {\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n type RefObject,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { ProviderLogo } from './provider-logo'\nimport type { CatalogModel } from '../runtime/model-catalog'\n\n// ── shared glyphs (no icon-library dependency) ────────────────────────────\n\nexport function ChevronDown({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n )\n}\n\nfunction SearchGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </svg>\n )\n}\n\nfunction SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\n/** lucide `brain` (v1.27) inlined — `/web-react` ships no icon-library\n * dependency, so the thinking glyph follows the same pattern as the rest of\n * this set. */\nexport function BrainGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 18V5\" />\n <path d=\"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4\" />\n <path d=\"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5\" />\n <path d=\"M17.997 5.125a4 4 0 0 1 2.526 5.77\" />\n <path d=\"M18 18a4 4 0 0 0 2-7.464\" />\n <path d=\"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517\" />\n <path d=\"M6 18a4 4 0 0 1-2-7.464\" />\n <path d=\"M6.003 5.125a4 4 0 0 0-2.526 5.77\" />\n </svg>\n )\n}\n\n/** lucide `check` — the selected-row mark in the picker menus. */\nexport function CheckGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n )\n}\n\n/**\n * Keyboard + pointer model for a trigger-and-popover pair, dependency-free.\n * Outside-mousedown and Escape both close; Escape also returns focus to the\n * trigger so keyboard users aren't dropped at the top of the document. The\n * returned `triggerProps` carry the ARIA contract (`aria-haspopup`/\n * `aria-expanded`); spread them onto the trigger button.\n *\n * `panelRef` belongs to the popover panel and MUST be wired when the panel is\n * rendered through {@link PopoverSurface}: a portaled panel is not inside\n * `containerRef`, so a container-only outside test reads every click on the\n * menu's own rows as an outside click and closes before the row's handler runs.\n */\nexport function usePopover(open: boolean, setOpen: (open: boolean) => void) {\n const containerRef = useRef<HTMLDivElement>(null)\n const triggerRef = useRef<HTMLButtonElement>(null)\n const panelRef = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n if (!open) return\n function onMouseDown(e: MouseEvent) {\n const target = e.target as Node\n if (containerRef.current?.contains(target)) return\n const panel = panelRef.current\n if (panel?.contains(target)) return\n // A popover opened FROM this one portals as a SIBLING at body level, so\n // `contains` cannot see it and a click on its rows would read as outside.\n // Surfaces stamp their ancestor chain, so descendancy survives the portal.\n const ownPath = panel?.getAttribute(POPOVER_SURFACE_ATTR)\n const hitPath =\n target instanceof Element\n ? target.closest(`[${POPOVER_SURFACE_ATTR}]`)?.getAttribute(POPOVER_SURFACE_ATTR)\n : null\n if (ownPath && hitPath && (hitPath === ownPath || hitPath.startsWith(`${ownPath}${POPOVER_PATH_SEPARATOR}`))) return\n setOpen(false)\n }\n function onKeyDown(e: KeyboardEvent) {\n if (e.key === 'Escape') {\n setOpen(false)\n triggerRef.current?.focus()\n }\n }\n document.addEventListener('mousedown', onMouseDown)\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('mousedown', onMouseDown)\n document.removeEventListener('keydown', onKeyDown)\n }\n }, [open, setOpen])\n\n return {\n containerRef,\n triggerRef,\n panelRef,\n triggerProps: {\n ref: triggerRef,\n 'aria-haspopup': true as const,\n 'aria-expanded': open,\n },\n }\n}\n\n// ── PopoverSurface ────────────────────────────────────────────────────────\n\n/** Distance between the trigger and the panel it opens. */\nconst POPOVER_GAP = 8\n/** Minimum distance the panel keeps from every viewport edge. */\nconst POPOVER_VIEWPORT_MARGIN = 16\n/** Floor for the computed max-height, so a cramped side still shows rows\n * rather than collapsing to a sliver the user cannot read. */\nconst POPOVER_MIN_HEIGHT = 120\n\n/**\n * Marks the portaled panel in the DOM. Products and audits (see\n * `playground/scripts/popover-hit-test.mjs`) select on this rather than on a\n * Tailwind class, which is presentation and free to change.\n *\n * Its VALUE is the surface's ancestor path (`outer/inner`), which is what\n * restores \"is this click inside my popover\" after the portal flattens two\n * nested panels into two siblings of `<body>`.\n */\nexport const POPOVER_SURFACE_ATTR = 'data-agent-app-popover'\nconst POPOVER_PATH_SEPARATOR = '/'\n\n/**\n * `PopoverSurface` is now mounted (closed) inside every server-rendered\n * composer, so its hooks run on the server once per composer per request.\n * React 18 logs \"useLayoutEffect does nothing on the server\" for that; React 19\n * does not (measured silent on react-dom 19.2.8). The peer floor is `react >=18`,\n * so bind the synchronous hook only where there is a DOM and the effect hook\n * elsewhere — placement never runs on the server either way.\n */\nconst useBrowserLayoutEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect\n\nexport interface PopoverSurfaceProps {\n open: boolean\n /** The trigger the panel anchors to — `usePopover`'s `triggerRef`. */\n triggerRef: RefObject<HTMLElement | null>\n /** `usePopover`'s `panelRef`; also what the outside-click test consults. */\n panelRef: RefObject<HTMLDivElement | null>\n /** Presentation classes. Placement and elevation are owned here — a caller\n * must not pass `absolute`/`fixed`/`top-*`/`bottom-*`/`z-*`. */\n className?: string\n role?: string\n id?: string\n /** Make the panel at least as wide as its trigger. A portaled panel has no\n * `w-full` to inherit — the trigger is no longer its offset parent — so a\n * menu that used to stretch to a full-width trigger declares it here. */\n matchTriggerWidth?: boolean\n children: ReactNode\n}\n\n/**\n * The floating panel every canonical picker opens.\n *\n * It renders through a PORTAL to `document.body` and anchors itself to the\n * trigger in viewport coordinates, because an in-place `absolute` panel's\n * visibility is decided by markup this package does not own. Measured in\n * production: the shipped chat composer docks these controls inside a\n * horizontally scrolling rail (`overflow-x-auto`), and a scroll container\n * clips every positioned descendant whose containing block sits inside it —\n * so a correct 420x457 menu with correct coordinates painted zero pixels and\n * could not be clicked. An ancestor `transform`/`filter`/`contain` would trap\n * it the same way through the stacking context instead of the clip. Leaving\n * the DOM subtree is the only placement a host cannot re-break.\n *\n * Placement prefers ABOVE the trigger (these controls dock at the bottom of a\n * composer), flips below when there is more room there, clamps horizontally\n * into the viewport, and caps its own height to the space on the chosen side.\n * The panel is `visibility: hidden` for the measure pass so it never paints at\n * the pre-placement origin.\n */\nexport function PopoverSurface({\n open,\n triggerRef,\n panelRef,\n className,\n role,\n id,\n matchTriggerWidth,\n children,\n}: PopoverSurfaceProps) {\n const surfaceId = useId()\n const [style, setStyle] = useState<CSSProperties>(() => ({\n position: 'fixed',\n top: 0,\n left: 0,\n visibility: 'hidden',\n }))\n\n const place = useCallback(() => {\n const trigger = triggerRef.current\n const panel = panelRef.current\n if (!trigger || !panel) return\n const anchor = trigger.getBoundingClientRect()\n const viewportWidth = window.innerWidth\n const viewportHeight = window.innerHeight\n\n // `scrollHeight` is the panel's CONTENT height, so it does not feed back\n // on the `maxHeight` this function just applied — reading `offsetHeight`\n // here would measure the previous pass's clamp and ratchet the panel\n // smaller on every scroll event.\n const contentHeight = panel.scrollHeight\n const panelWidth = panel.offsetWidth\n\n const roomAbove = anchor.top - POPOVER_GAP - POPOVER_VIEWPORT_MARGIN\n const roomBelow = viewportHeight - anchor.bottom - POPOVER_GAP - POPOVER_VIEWPORT_MARGIN\n const above = contentHeight <= roomAbove || roomAbove >= roomBelow\n const maxHeight = Math.max(POPOVER_MIN_HEIGHT, above ? roomAbove : roomBelow)\n const height = Math.min(contentHeight, maxHeight)\n\n const top = above ? Math.max(POPOVER_VIEWPORT_MARGIN, anchor.top - POPOVER_GAP - height) : anchor.bottom + POPOVER_GAP\n const rightBound = Math.max(POPOVER_VIEWPORT_MARGIN, viewportWidth - panelWidth - POPOVER_VIEWPORT_MARGIN)\n const left = Math.min(Math.max(POPOVER_VIEWPORT_MARGIN, anchor.left), rightBound)\n\n setStyle({\n position: 'fixed',\n top,\n left,\n maxHeight,\n visibility: 'visible',\n ...(matchTriggerWidth ? { minWidth: anchor.width } : {}),\n })\n }, [matchTriggerWidth, panelRef, triggerRef])\n\n // Layout effect: placement is resolved before the browser paints, so the\n // panel is never seen at the origin it mounts at.\n useBrowserLayoutEffect(() => {\n if (!open) {\n setStyle({ position: 'fixed', top: 0, left: 0, visibility: 'hidden' })\n return\n }\n place()\n }, [open, place])\n\n useEffect(() => {\n if (!open) return\n const onViewportChange = () => place()\n // `capture` so the rail's OWN scroll re-anchors the panel — a scroll inside\n // an ancestor does not bubble to window.\n window.addEventListener('scroll', onViewportChange, true)\n window.addEventListener('resize', onViewportChange)\n return () => {\n window.removeEventListener('scroll', onViewportChange, true)\n window.removeEventListener('resize', onViewportChange)\n }\n }, [open, place])\n\n if (!open || typeof document === 'undefined') return null\n\n const ownerPath = triggerRef.current?.closest?.(`[${POPOVER_SURFACE_ATTR}]`)?.getAttribute(POPOVER_SURFACE_ATTR)\n const path = ownerPath ? `${ownerPath}${POPOVER_PATH_SEPARATOR}${surfaceId}` : surfaceId\n\n return createPortal(\n <div\n ref={panelRef}\n id={id}\n role={role}\n style={style}\n {...{ [POPOVER_SURFACE_ATTR]: path }}\n className={`z-[1000] ${className ?? ''}`}\n >\n {children}\n </div>,\n document.body,\n )\n}\n\n/**\n * Focus treatment for a row inside a popover panel.\n *\n * The ring itself now comes from the `:focus-visible` floor in tokens.css, so\n * this no longer restates a width or a colour. What it still has to say is\n * WHERE the ring is drawn: a popover option is a full-width row inside a panel\n * that clips its own corners (`overflow-hidden rounded-xl`), and an outward\n * ring on the first or last row is clipped away by that panel. Pulling the\n * offset negative draws the same ring just inside the row instead.\n */\nexport const POPOVER_OPTION_FOCUS = 'focus-visible:[outline-offset:-2px]'\n\n/**\n * The one overlay elevation for floating surfaces — picker menus, popovers,\n * drawers, modals. Reads the theme's `--shadow-overlay` token, so every overlay\n * lifts with the same shadow and re-themes from one source. The floating\n * composer uses the quieter `shadow-raised` rung instead.\n *\n * Written as an arbitrary value rather than the preset's `shadow-overlay`\n * utility, because that utility only exists where the preset is part of the\n * Tailwind build. A host that gets its tokens through a precompiled bundle —\n * `@tangle-network/sandbox-ui` ships brand's tokens inlined, with no `@theme`\n * block surviving the compile — receives `--shadow-overlay` as a plain custom\n * property, from which no `shadow-overlay` utility can be generated, and these\n * surfaces render flat. The arbitrary form emits from the class alone and works\n * either way.\n */\nexport const OVERLAY_SHADOW = 'shadow-[var(--shadow-overlay)]'\n\n/**\n * Root geometry for a picker — the box that holds the trigger — in one place\n * because every picker in this family has to agree on it.\n *\n * Shrink-wrapping (`inline-flex`) is the default: these controls dock on a\n * composer row where an expanding pill shoves its neighbours around. A STACKED\n * panel wants the opposite — the compact `AgentSessionControls` gear popover\n * lays its controls out in a column, and a shrink-wrapped root there makes a\n * trigger's own `w-full` a no-op, since it fills a box the trigger itself\n * sized. That is what left Agent backend short of the panel edge and Thinking\n * narrower still.\n *\n * The panel is portaled ({@link PopoverSurface}), so widening the root widens\n * the TRIGGER only. A menu that should follow it declares `matchTriggerWidth`.\n */\nexport function pickerRootClass(fullWidth: boolean): string {\n return `relative ${fullWidth ? 'flex w-full' : 'inline-flex'}`\n}\n\n/**\n * How a picker's TRIGGER is drawn. The menu it opens is the same either way.\n *\n * - `chip` (default): the 36px bordered pill — `rounded-full border\n * border-border bg-card font-medium`. A consumer that names no variant\n * renders exactly what it rendered before this prop existed.\n * - `quiet`: a 28px borderless text button — muted label, small glyph, a\n * surface fill on hover and while the menu is open, nothing else. For a\n * composer whose card already draws the border: three pills docked under\n * the input there read as three more cards, not as the input's controls.\n */\nexport type PickerVariant = 'chip' | 'quiet'\n\n/** The quiet trigger at rest: geometry, type, and keyboard focus. */\nconst QUIET_PICKER_TRIGGER_BASE =\n 'inline-flex h-7 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md bg-transparent px-2 text-sm font-normal text-muted-foreground transition focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'\n\n/** The fills a quiet trigger shows on hover and while its menu is open — the\n * only two states it draws. Reads `data-state`, which every picker trigger\n * in this family stamps. */\nconst QUIET_PICKER_TRIGGER_INTERACTIVE =\n 'hover:bg-accent hover:text-foreground data-[state=open]:bg-accent data-[state=open]:text-foreground'\n\n/**\n * Trigger classes for a `quiet` picker. Height, padding, radius, and type are\n * fixed here so the triggers on one composer row agree; a caller adds only\n * width (`w-full`) and alignment (`justify-between`).\n *\n * The focus ring is drawn on the element rather than left to the tokens.css\n * `:focus-visible` floor: a quiet trigger sits beside the composer's own action\n * buttons (attach, dictate, send), which draw `focus-visible:ring-2\n * focus-visible:ring-ring`, and a row whose controls answer keyboard focus two\n * different ways reads as two families.\n *\n * `interactive: false` is for a PINNED control (see `HarnessPicker`'s\n * `lockReason`): it keeps the resting treatment and draws no hover or open\n * fill, because a fill promises a menu the control will not open.\n */\nexport function quietPickerTriggerClass({ interactive = true }: { interactive?: boolean } = {}): string {\n return interactive\n ? `${QUIET_PICKER_TRIGGER_BASE} ${QUIET_PICKER_TRIGGER_INTERACTIVE}`\n : `${QUIET_PICKER_TRIGGER_BASE} cursor-default`\n}\n\n/**\n * Guard an async action against double-submit. `run` ignores re-entrant calls\n * while a promise is in flight and flips `pending` so the caller can disable\n * the control — the fix for double-charge / double-approve on a slow network.\n * Settles (success or throw) before clearing, and no-ops state updates after\n * unmount.\n */\nexport function usePending(): { pending: boolean; run: (action: () => void | Promise<void>) => void } {\n const [pending, setPending] = useState(false)\n const inFlight = useRef(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const run = (action: () => void | Promise<void>) => {\n if (inFlight.current) return\n let result: void | Promise<void>\n try {\n result = action()\n } catch {\n return\n }\n if (!(result instanceof Promise)) return\n inFlight.current = true\n setPending(true)\n void result.finally(() => {\n inFlight.current = false\n if (mounted.current) setPending(false)\n })\n }\n return { pending, run }\n}\n\n// ── ModelPicker ───────────────────────────────────────────────────────────\n\nexport interface ModelPickerProps {\n value: string\n onChange: (id: string) => void\n /** Catalogue models — from `GET`ing the app's catalogue route (see\n * `runtime/model-catalog`), plus any product-specific entries appended. */\n models: CatalogModel[]\n loading?: boolean\n /** Render a provider logo/badge; default is a generic sparkle. */\n renderProviderBadge?: (provider: string) => ReactNode\n /** Section label for `featured` models. */\n recommendedLabel?: string\n /** Pin a labeled section to the TOP of the list (above Recommended) for the\n * models a product wants surfaced first — e.g. a tuner app's own fine-tuned\n * models (`{ label: 'Your Fine-Tuned Models', match: (m) => m.provider === 'tuner' }`).\n * Matching models are shown only in this section, not duplicated below. */\n priorityGroup?: {\n label: string\n match: (model: CatalogModel) => boolean\n }\n /** Trigger treatment — see {@link PickerVariant}. Default `chip`. */\n variant?: PickerVariant\n}\n\nfunction formatPrice(p?: string): string | undefined {\n if (!p) return undefined\n const n = Number(p)\n if (isNaN(n) || n === 0) return undefined\n const perM = n * 1_000_000\n return perM >= 1 ? `$${perM.toFixed(0)}/M` : `$${perM.toFixed(2)}/M`\n}\n\nfunction formatContext(len?: number): string | undefined {\n if (!len) return undefined\n if (len >= 1_000_000) return `${(len / 1_000_000).toFixed(1)}M ctx`\n if (len >= 1_000) return `${Math.round(len / 1_000)}K ctx`\n return `${len} ctx`\n}\n\nfunction SectionHeader({ children }: { children: ReactNode }) {\n return (\n <div className=\"px-3 pb-1 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground\">\n {children}\n </div>\n )\n}\n\nfunction ModelRow({\n model,\n selected,\n onSelect,\n renderProviderBadge,\n}: {\n model: CatalogModel\n selected: boolean\n onSelect: () => void\n renderProviderBadge?: (provider: string) => ReactNode\n}) {\n const price = formatPrice(model.pricing?.prompt)\n const ctx = formatContext(model.contextLength)\n return (\n <button\n type=\"button\"\n onClick={onSelect}\n className={`flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n selected ? 'bg-primary/10 font-medium' : 'hover:bg-accent'\n }`}\n >\n {renderProviderBadge ? renderProviderBadge(model.provider) : <ProviderLogo provider={model.provider} size={16} />}\n <span className=\"truncate\">{model.name}</span>\n {!model.supportsTools && (\n <span className=\"shrink-0 rounded bg-secondary px-1.5 py-0.5 text-xs font-medium text-muted-foreground\">\n no tools\n </span>\n )}\n <span className=\"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground\">\n {ctx && <span>{ctx}</span>}\n {price && <span>{price}</span>}\n </span>\n </button>\n )\n}\n\n/**\n * Searchable model picker pill + popover: a featured/recommended section\n * first, then per-provider groups in catalogue order (the server already\n * sorts providers by tier).\n *\n * This is the CANONICAL ecosystem model picker (see \"UI chrome ownership\n * (picker canon)\" in AGENTS.md). sandbox-ui's `dashboard/ModelPicker` is\n * legacy — deprecated, frozen, removed at sandbox-ui's next major; new code\n * belongs here.\n */\nexport function ModelPicker({ value, onChange, models, loading, renderProviderBadge, recommendedLabel = 'Recommended', priorityGroup, variant = 'chip' }: ModelPickerProps) {\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen)\n const inputRef = useRef<HTMLInputElement>(null)\n const panelId = useId()\n\n useEffect(() => {\n if (open) inputRef.current?.focus()\n }, [open])\n\n const selected = models.find((m) => m.id === value)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n if (!q) return null\n return models.filter(\n (m) =>\n m.id.toLowerCase().includes(q) ||\n m.name.toLowerCase().includes(q) ||\n (m.description?.toLowerCase() ?? '').includes(q) ||\n m.provider.toLowerCase().includes(q),\n )\n }, [models, query])\n\n const sections = useMemo(() => {\n const isPriority = priorityGroup ? (m: CatalogModel) => priorityGroup.match(m) : () => false\n const priority = priorityGroup ? models.filter(isPriority) : []\n const recommended = models.filter((m) => m.featured && !isPriority(m))\n const byProvider: Array<{ provider: string; items: CatalogModel[] }> = []\n for (const m of models) {\n if (m.featured || isPriority(m)) continue\n const last = byProvider[byProvider.length - 1]\n if (last && last.provider === m.provider) last.items.push(m)\n else byProvider.push({ provider: m.provider, items: [m] })\n }\n return { priority, recommended, byProvider }\n }, [models, priorityGroup])\n\n const select = (id: string) => {\n onChange(id)\n setOpen(false)\n setQuery('')\n }\n\n return (\n <div ref={containerRef} className=\"relative inline-flex\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen(!open)}\n data-state={open ? 'open' : 'closed'}\n className={\n variant === 'quiet'\n ? quietPickerTriggerClass()\n : 'inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent'\n }\n >\n {selected ? (renderProviderBadge ? renderProviderBadge(selected.provider) : <ProviderLogo provider={selected.provider} size={16} />) : <SparkleGlyph className=\"h-3.5 w-3.5 text-muted-foreground\" />}\n <span className=\"max-w-[160px] truncate\">{selected?.name ?? value}</span>\n <ChevronDown className=\"h-3.5 w-3.5 text-muted-foreground\" />\n </button>\n\n <PopoverSurface\n open={open}\n id={panelId}\n triggerRef={triggerRef}\n panelRef={panelRef}\n className={`flex w-[420px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-xl border border-card-edge bg-popover ${OVERLAY_SHADOW}`}\n >\n <div className=\"shrink-0 border-b border-border px-3 py-2\">\n <div className=\"flex items-center gap-2 rounded-lg border border-strong bg-background px-3 py-2\">\n <SearchGlyph className=\"h-3.5 w-3.5 text-muted-foreground\" />\n <input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder=\"Search models...\"\n className=\"flex-1 bg-transparent text-sm placeholder:text-muted-foreground\"\n />\n </div>\n </div>\n {/* `min-h-0` is what lets the list absorb the surface's computed\n max-height on a short viewport instead of overflowing the panel. */}\n <div className=\"max-h-[400px] min-h-0 overflow-y-auto p-1 pb-2\">\n {loading && <div className=\"px-3 py-4 text-center text-sm text-muted-foreground\">Loading models...</div>}\n {!loading && filtered && (\n <>\n {filtered.length === 0 && (\n <div className=\"px-3 py-4 text-center text-sm text-muted-foreground\">No models match your search</div>\n )}\n {filtered.map((m) => (\n <ModelRow key={m.id} model={m} selected={m.id === value} onSelect={() => select(m.id)} renderProviderBadge={renderProviderBadge} />\n ))}\n </>\n )}\n {!loading && !filtered && models.length === 0 && (\n <div className=\"px-3 py-4 text-center text-sm text-muted-foreground\">No models available</div>\n )}\n {!loading && !filtered && models.length > 0 && (\n <>\n {priorityGroup && sections.priority.length > 0 && (\n <>\n <SectionHeader>{priorityGroup.label}</SectionHeader>\n {sections.priority.map((m) => (\n <ModelRow key={m.id} model={m} selected={m.id === value} onSelect={() => select(m.id)} renderProviderBadge={renderProviderBadge} />\n ))}\n </>\n )}\n {sections.recommended.length > 0 && (\n <>\n <SectionHeader>{recommendedLabel}</SectionHeader>\n {sections.recommended.map((m) => (\n <ModelRow key={m.id} model={m} selected={m.id === value} onSelect={() => select(m.id)} renderProviderBadge={renderProviderBadge} />\n ))}\n </>\n )}\n {sections.byProvider.map((g) => (\n <div key={g.provider}>\n <SectionHeader>{g.provider}</SectionHeader>\n {g.items.map((m) => (\n <ModelRow key={m.id} model={m} selected={m.id === value} onSelect={() => select(m.id)} renderProviderBadge={renderProviderBadge} />\n ))}\n </div>\n ))}\n </>\n )}\n </div>\n </PopoverSurface>\n </div>\n )\n}\n\n// ── EffortPicker ──────────────────────────────────────────────────────────\n\n/** One reasoning-budget level: the engine `id` is unchanged (the value the\n * product sends to the loop); only the user-facing `label` is renamed to the\n * plainer \"how hard should it think\" vocabulary from docs/product-surfaces.md.\n * `low`→Quick, `medium`→Standard, `high`→Extended. The mapping is overridable\n * via `EffortPickerProps.levels`, so a product can relabel without losing the\n * ids the runtime expects. */\nexport interface EffortLevel {\n id: string\n label: string\n}\n\n/**\n * The engine ids this package NAMES, and the word each one reads as.\n *\n * Deliberately WIDER than {@link DEFAULT_EFFORT_LEVELS}: the default list is\n * what a picker OFFERS when a product declares nothing, while this is the\n * vocabulary — the labels a named id keeps wherever it appears. The two are\n * different questions, and folding them together is what made a real engine\n * rung read as its own id: `xhigh` and `ultracode` are rungs claude-code\n * applies above `high`, so a product declaring them got \"Xhigh\" while every\n * neighbouring rung had a plain English word. Naming them here is what stops\n * each product inventing its own — the drift `effortLevelsFromIds` exists to\n * prevent. They stay OUT of the offered default because most backends do not\n * apply them, and offering a rung the backend ignores is the defect\n * `effortLevels` was added to close.\n */\nconst KNOWN_EFFORT_LABELS = {\n off: 'Off',\n low: 'Quick',\n medium: 'Standard',\n high: 'Extended',\n xhigh: 'Extra',\n ultracode: 'Ultra',\n} as const\n\nexport const DEFAULT_EFFORT_LEVELS: readonly EffortLevel[] = [\n { id: 'off', label: KNOWN_EFFORT_LABELS.off },\n { id: 'low', label: KNOWN_EFFORT_LABELS.low },\n { id: 'medium', label: KNOWN_EFFORT_LABELS.medium },\n { id: 'high', label: KNOWN_EFFORT_LABELS.high },\n]\n\n/**\n * The user-facing label for an engine level id: the canonical vocabulary when\n * the id is one this package names, otherwise the id itself made readable\n * (`auto` -> \"Auto\", `ultra-code` -> \"Ultra code\"). Never invents a depth word,\n * so an id nobody declared a label for still reads as ITSELF and never as some\n * other level.\n */\nexport function effortLevelLabel(id: string): string {\n const known = (KNOWN_EFFORT_LABELS as Record<string, string | undefined>)[id]\n if (known) return known\n const words = id.replace(/[-_]+/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/**\n * Build a levels list from the engine ids a backend applies — the shape the\n * removed `ComposerAgentControls` took as `reasoning.available`, so a product\n * migrating that list has one call to make instead of a hand-written label map\n * per product (which is how \"Quick\" and \"Low\" drift apart across surfaces).\n */\nexport function effortLevelsFromIds(ids: readonly string[]): readonly EffortLevel[] {\n return ids.map((id) => ({ id, label: effortLevelLabel(id) }))\n}\n\n/**\n * The list {@link EffortPicker} RENDERS for `value` — the declared levels, plus\n * `value` itself when the declaration omits it.\n *\n * A picker cannot honestly resolve a selected value it was not given, and the\n * failure it used to take instead — fall back to the middle entry — renders the\n * session's real depth as a DIFFERENT level's name. That is exactly the defect\n * `levels` was added to prevent: the legacy adapter's `available` list excluded\n * the `auto` sentinel because the old picker injected it, so a product mapping\n * that list straight across ships a session running on `auto` labelled\n * \"Extended\". Admitting the value is not offering a new choice — it is\n * reporting the state the session is already in, and it disappears from the\n * list as soon as the user picks a declared level.\n *\n * A blank value is not admitted (there is no honest label for it); the picker\n * renders no selection instead.\n */\nexport function reconcileEffortLevels(\n value: string,\n levels: readonly EffortLevel[] = DEFAULT_EFFORT_LEVELS,\n): readonly EffortLevel[] {\n if (!value || levels.some((l) => l.id === value)) return levels\n return [{ id: value, label: effortLevelLabel(value) }, ...levels]\n}\n\n// ── effort strength meter ─────────────────────────────────────────────────\n\n/** Segments the meter draws — fixed geometry so the ladder stays tabular\n * across levels (and across the trigger and its menu rows). */\nexport const EFFORT_METER_SEGMENTS = 4\n\n/** Filled-segment opacity ladder: translucent on the left, heavy on the\n * right — the ramp carries strength even at a glance, the count carries it\n * exactly. Unfilled segments sit at a fixed ghost opacity. */\nconst EFFORT_METER_FILL_OPACITY = [0.25, 0.5, 0.75, 1] as const\nconst EFFORT_METER_GHOST_OPACITY = 0.15\n\n/** Level ids that mean \"no reasoning\" — the meter renders all-ghost. */\nconst OFF_LEVEL_IDS: ReadonlySet<string> = new Set(['off', 'none'])\n\n/**\n * Ids that name a POLICY rather than a depth: `auto` means \"let the harness and\n * model decide\", so it has no position on a strength ladder.\n *\n * Without this it lands wherever the declaration puts it and draws a filled\n * meter — measured on a product that offers `auto` first: every harness read\n * `Auto` at a FULL four bars, including `cli-base`, which has no agent to think\n * at all. A meter is a claim about how hard the run will think, and a sentinel\n * cannot make that claim.\n */\nconst UNPLACEABLE_LEVEL_IDS: ReadonlySet<string> = new Set(['auto'])\n\n/**\n * Filled-segment count for a level: 0 for off/none (or an id the levels list\n * does not carry); otherwise the level's position among the non-off choices\n * scaled onto the meter, so the ladder reads low < medium < high and the top\n * level fills the whole scale. The canonical four levels land 0 / 1 / 2 / 4.\n */\nexport function effortMeterFill(\n levelId: string,\n levels: readonly EffortLevel[] = DEFAULT_EFFORT_LEVELS,\n): number {\n if (OFF_LEVEL_IDS.has(levelId) || UNPLACEABLE_LEVEL_IDS.has(levelId)) return 0\n const active = levels.filter((l) => !OFF_LEVEL_IDS.has(l.id) && !UNPLACEABLE_LEVEL_IDS.has(l.id))\n const index = active.findIndex((l) => l.id === levelId)\n if (index < 0 || active.length === 0) return 0\n return Math.max(1, Math.floor(((index + 1) * EFFORT_METER_SEGMENTS) / active.length))\n}\n\n/**\n * The thinking-strength meter: four 12px bars, filled count = level, filled\n * opacity ramping 25→100% left to right (unfilled at a faint ghost). Purely\n * decorative — the level name is always rendered as text beside it, so the\n * meter is `aria-hidden` and adds no second accessible name.\n */\nexport function EffortMeter({ fill, className }: { fill: number; className?: string }) {\n return (\n <span aria-hidden className={`inline-flex items-center gap-[2px] ${className ?? ''}`}>\n {Array.from({ length: EFFORT_METER_SEGMENTS }, (_, i) => (\n <span\n key={i}\n className=\"h-3 w-[3px] rounded-full bg-current\"\n style={{ opacity: i < fill ? EFFORT_METER_FILL_OPACITY[i] : EFFORT_METER_GHOST_OPACITY }}\n />\n ))}\n </span>\n )\n}\n\nexport interface EffortPickerProps {\n value: string\n onChange: (id: string) => void\n /** Selectable levels (engine id + user-facing label). Defaults to the plain\n * \"Thinking\" vocabulary; override to relabel without changing the ids the\n * runtime receives.\n *\n * A list that omits the current `value` is not a rendering error the picker\n * papers over: `value` is reconciled INTO the rendered list under its own\n * name (see {@link reconcileEffortLevels}), because a control must report\n * the depth the session is running at and never some other list entry. */\n levels?: readonly EffortLevel[]\n /** Prefix shown before the active level on the pill — the \"what is this\"\n * context the bare value lacked. Default \"Thinking\". Pass '' to hide it. */\n label?: string\n /** Fill the container instead of shrink-wrapping — opt-in, default `false`;\n * see {@link pickerRootClass} for when and why. */\n fullWidth?: boolean\n /** Trigger treatment — see {@link PickerVariant}. Default `chip`. */\n variant?: PickerVariant\n}\n\n/** Thinking-budget selector pill, styled to match {@link ModelPicker}. Show\n * it only when the selected model `supportsReasoning`. \"Thinking\" is the\n * plain-English name for what was internally called \"effort\".\n *\n * The CANONICAL ecosystem effort picker — sandbox-ui's reasoning menu (inside\n * its `chat/AgentSessionControls`) is legacy and frozen. */\nexport function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label = 'Thinking', fullWidth = false, variant = 'chip' }: EffortPickerProps) {\n const [open, setOpen] = useState(false)\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen)\n const panelId = useId()\n const rendered = reconcileEffortLevels(value, levels)\n // The strength ladder is computed over the DECLARED levels only, so admitting\n // the selected value cannot shift where the declared ones sit on the meter.\n // A level the declaration does not carry has no position on that ladder, so\n // it renders with NO meter — an all-ghost meter is what `off` looks like, and\n // \"we cannot place this\" is not \"no thinking\".\n const isDeclared = (id: string) => levels.some((l) => l.id === id) && !UNPLACEABLE_LEVEL_IDS.has(id)\n const selected = rendered.find((l) => l.id === value)\n\n return (\n <div ref={containerRef} className={pickerRootClass(fullWidth)}>\n <button\n type=\"button\"\n {...triggerProps}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen(!open)}\n title={label ? `${label} — how hard the agent reasons before answering` : 'Reasoning effort'}\n data-state={open ? 'open' : 'closed'}\n className={`${\n variant === 'quiet'\n ? quietPickerTriggerClass()\n : 'inline-flex min-h-[36px] shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent'\n } ${fullWidth ? 'w-full' : ''}`}\n >\n <BrainGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n {/* Full width gives the label the slack, so the meter and chevron park\n on the trailing edge and the glyph stays against the text. */}\n <span className={fullWidth ? 'flex-1 truncate text-left' : undefined}>\n {label ? <span className=\"text-muted-foreground\">{label}: </span> : null}\n {selected ? selected.label : '—'}\n </span>\n {/* Quiet inherits the trigger's tone, so the meter is muted at rest\n and lifts with the label on hover. */}\n {selected && isDeclared(selected.id) && (\n <EffortMeter\n fill={effortMeterFill(selected.id, levels)}\n className={variant === 'quiet' ? 'shrink-0' : 'shrink-0 text-foreground'}\n />\n )}\n <ChevronDown className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"menu\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n // A portaled panel has no `w-full` to inherit, so a full-width trigger\n // hands its measured width to the panel instead.\n matchTriggerWidth={fullWidth}\n className={`w-44 overflow-y-auto rounded-xl border border-card-edge bg-popover p-1 ${OVERLAY_SHADOW}`}\n >\n {rendered.map((l) => (\n <button\n key={l.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={l.id === value}\n onClick={() => {\n onChange(l.id)\n setOpen(false)\n }}\n className={`flex min-h-[40px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n l.id === value ? 'bg-primary/10 font-medium' : 'hover:bg-accent'\n }`}\n >\n <BrainGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate\">{l.label}</span>\n {isDeclared(l.id) && (\n <EffortMeter fill={effortMeterFill(l.id, levels)} className=\"ml-auto text-foreground\" />\n )}\n {l.id === value && (\n <CheckGlyph className={`${isDeclared(l.id) ? '' : 'ml-auto '}h-3.5 w-3.5 shrink-0 text-primary`} />\n )}\n </button>\n ))}\n </PopoverSurface>\n </div>\n )\n}\n"],"mappings":";AAyDU,cAWN,YAXM;AAzCV,IAAM,QAAiC;AAAA,EACrC,WAAW,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,0KAA0K,EAAE;AAAA,EACxO,QAAQ,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,8RAA8R,EAAE;AAAA,EACzV,UAAU,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,w7DAAw7D,EAAE;AAAA,EACr/D,SAAS,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,kLAAkL,EAAE;AAAA,EAC9O,KAAK,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,oMAAoM,EAAE;AAAA,EAC5P,QAAQ,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,qwBAAqwB,EAAE;AAAA,EACh0B,MAAM,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,ksCAAksC,EAAE;AAAA,EAC3vC,YAAY,EAAE,SAAS,aAAa,MAAM,WAAW,OAAO,CAAC,2hBAA2hB,EAAE;AAAA,EAC1lB,QAAQ,EAAE,SAAS,eAAe,MAAM,WAAW,OAAO,CAAC,28CAA28C,EAAE;AAC1gD;AAE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AA,8BAAAD,KAAC,cAAW,WAAU,8CAA6C;AAAA,cACnE,gBAAAA,KAAC,UAAK,WAAU,YAAY,YAAE,OAAM;AAAA,cACnC,WAAW,EAAE,EAAE,KACd,gBAAAA,KAAC,eAAY,MAAM,gBAAgB,EAAE,IAAI,MAAM,GAAG,WAAU,2BAA0B;AAAA,cAEvF,EAAE,OAAO,SACR,gBAAAA,KAAC,cAAW,WAAW,GAAG,WAAW,EAAE,EAAE,IAAI,KAAK,UAAU,qCAAqC;AAAA;AAAA;AAAA,UAlB9F,EAAE;AAAA,QAoBT,CACD;AAAA;AAAA,IACL;AAAA,KACF;AAEJ;","names":["jsx","jsxs"]}
@@ -406,7 +406,11 @@ function activeSessionIdFromPath({
406
406
  const id = path.slice(prefix.length + 1).split("/")[0] ?? "";
407
407
  if (!id || id === newSegment) return null;
408
408
  if (reserved?.some((name) => stripSlashes(name) === id)) return null;
409
- return decodeURIComponent(id);
409
+ try {
410
+ return decodeURIComponent(id);
411
+ } catch {
412
+ return null;
413
+ }
410
414
  }
411
415
  function resolveActiveNavId({
412
416
  pathname,
@@ -519,4 +523,4 @@ export {
519
523
  railCollapsedCookie,
520
524
  writeRailCollapsedCookie
521
525
  };
522
- //# sourceMappingURL=chunk-EDTWGSQT.js.map
526
+ //# sourceMappingURL=chunk-SJWIZT7B.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/session-shell/path.ts","../src/session-shell/nav-guard.ts","../src/session-shell/command-palette.ts","../src/session-shell/index.ts"],"sourcesContent":["/**\n * Path normalisation shared by the shell's routing helpers. Segment-aligned\n * comparison is the invariant: `/vault` must never claim `/vault-archive`, so\n * every prefix test here works on whole segments rather than string prefixes.\n */\n\nexport function stripTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\n/** Bare segment name, so a caller may pass `'/settings'` or `'settings'`. */\nexport function stripSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\n/** Path with query + fragment removed and trailing slashes trimmed. A caller\n * passing a full href instead of a pathname would otherwise match nothing. */\nexport function normalizePath(pathname: string): string {\n const withoutHash = pathname.split('#')[0] ?? ''\n const withoutQuery = withoutHash.split('?')[0] ?? ''\n return stripTrailingSlashes(withoutQuery)\n}\n\n/** True when `path` is `prefix` or a segment-aligned descendant of it, so\n * `/vault` never claims `/vault-archive`. */\nexport function isUnderPrefix(path: string, prefix: string): boolean {\n const p = stripTrailingSlashes(prefix)\n if (p === '') return true\n return path === p || path.startsWith(`${p}/`)\n}\n\n/** Non-empty segments of a path or route pattern. Leading/trailing/duplicate\n * slashes collapse, so `/app//x/` and `app/x` compare equal. */\nexport function toSegments(value: string): string[] {\n return value.split('/').filter((segment) => segment.length > 0)\n}\n\n/** Canonical display form: rooted, no trailing slash, no empty segments. */\nexport function toRootedPath(value: string): string {\n return `/${toSegments(value).join('/')}`\n}\n","/**\n * Nav destinations, and the guard that proves every href the rail renders\n * resolves to a route the product's router actually registered.\n *\n * A rail row's href is assembled from a base plus a relative path, and nothing\n * downstream re-checks it: the sidebar renders a link, the click navigates, and\n * the router answers 404. A unit test written against the nav builder alone\n * cannot catch that — it asserts the href the builder produced, which is the\n * same wrong string the user clicks.\n *\n * Two mechanisms, meant to be used together:\n *\n * 1. `NavDestination` makes the base a REQUIRED discriminant (`scope`). An\n * optional `absolute?: boolean`-style flag has the opposite property:\n * omitting it type-checks, and the destination silently resolves under the\n * workspace prefix instead of the app-level one. A required literal union\n * turns that omission into a compile error, and widening `TScope` demands a\n * base for the new scope rather than defaulting to a wrong one.\n * 2. `assertNavHrefsRegistered` matches every resolved href against the route\n * table, so a destination the router never registered fails a test instead\n * of a user's click. It reads the product's real route table, so it cannot\n * agree with the builder's mistake the way a hand-maintained expected-href\n * list does.\n */\n\nimport { isUnderPrefix, normalizePath, stripTrailingSlashes, toRootedPath, toSegments } from './path'\n\n// ---------------------------------------------------------------------------\n// Destinations — the base is a required discriminant, never an optional flag\n// ---------------------------------------------------------------------------\n\n/** The bases a product routes rail rows under. `workspace` is the per-workspace\n * prefix (`/app/ws_123`); `app` is the account-level one (`/app`), where\n * singleton surfaces such as a shared terminal or billing live. */\nexport type NavScope = 'workspace' | 'app'\n\n/** A base path per scope. Widening `TScope` widens this record, so a product\n * that adds a scope cannot compile until it supplies that scope's base. */\nexport type NavScopeBases<TScope extends string = NavScope> = Readonly<Record<TScope, string>>\n\n/** One rail destination as the product declares it, before a base is applied. */\nexport interface NavDestination<TScope extends string = NavScope> {\n id: string\n /** Path relative to the base named by `scope`. `''` is the base itself.\n * Must be empty or start with `/` — a bare `'vault'` would concatenate into\n * `/app/ws_123vault`, so it is rejected rather than silently repaired. */\n path: string\n /** Which base `path` resolves against. Required on purpose. */\n scope: TScope\n}\n\n/** A destination with its base applied. */\nexport interface ResolvedNavDestination<TScope extends string = NavScope> {\n id: string\n href: string\n scope: TScope\n}\n\n/** Apply a destination's scope base to its path.\n *\n * Throws when the scope has no base configured — a product that assembles\n * `bases` dynamically can defeat the type-level guarantee, and a missing base\n * would otherwise produce `undefined/vault`. */\nexport function resolveNavHref<TScope extends string>(\n destination: NavDestination<TScope>,\n bases: NavScopeBases<TScope>,\n): string {\n const base = bases[destination.scope]\n if (typeof base !== 'string') {\n throw new Error(\n `Nav destination '${destination.id}' uses scope '${destination.scope}', which has no configured base`,\n )\n }\n if (destination.path !== '' && !destination.path.startsWith('/')) {\n throw new Error(\n `Nav destination '${destination.id}' path must be empty or start with '/' (got '${destination.path}')`,\n )\n }\n const rooted = `${stripTrailingSlashes(base)}${destination.path}`\n return rooted === '' ? '/' : stripTrailingSlashes(rooted)\n}\n\n/** Apply the bases to every destination, preserving declaration order. */\nexport function resolveNavDestinations<TScope extends string>(\n destinations: readonly NavDestination<TScope>[],\n bases: NavScopeBases<TScope>,\n): ResolvedNavDestination<TScope>[] {\n return destinations.map((destination) => ({\n id: destination.id,\n href: resolveNavHref(destination, bases),\n scope: destination.scope,\n }))\n}\n\nexport interface ResolveScopedActiveNavIdOptions<TScope extends string = NavScope> {\n pathname: string\n destinations: readonly NavDestination<TScope>[]\n bases: NavScopeBases<TScope>\n /** Extra ABSOLUTE prefixes that light an existing row, e.g.\n * `{ '/app/ws_1/agents': 'integrations' }`. Same longest-prefix contest. */\n aliases?: Readonly<Record<string, string>>\n /** ABSOLUTE prefixes that deliberately highlight nothing, beating any shorter\n * match. */\n claimsNothing?: readonly string[]\n}\n\n/**\n * The rail row to highlight, across scopes.\n *\n * `resolveActiveNavId` resolves rows against ONE base, so an app-level row can\n * only be highlighted by a second, hand-rolled scan — the same split that lets\n * an app-level destination render under the workspace base. This resolves the\n * hrefs first and runs a single longest-prefix contest over absolute paths, so\n * declaration order cannot change the answer and no scope needs its own pass.\n *\n * Prefixes in `aliases` / `claimsNothing` are absolute here, unlike\n * `resolveActiveNavId`'s base-relative ones, because the contest itself is\n * absolute.\n */\nexport function resolveScopedActiveNavId<TScope extends string>({\n pathname,\n destinations,\n bases,\n aliases,\n claimsNothing,\n}: ResolveScopedActiveNavIdOptions<TScope>): string | undefined {\n const path = normalizePath(pathname)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (candidate: string, id: string | undefined, winsTies = false): void => {\n const full = stripTrailingSlashes(candidate)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const resolved of resolveNavDestinations(destinations, bases)) consider(resolved.href, resolved.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix here is a\n // deliberate override of the row that owns it.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Route table — structurally the product's own router config\n// ---------------------------------------------------------------------------\n\n/**\n * One entry of a registered route table. Structurally compatible with\n * react-router's `RouteConfigEntry`, so a product passes its real `routes.ts`\n * default export straight in — the point of the guard is that it reads the\n * router's own truth rather than a second list that can agree with the bug.\n */\nexport interface RegisteredRoute {\n /** Absent on a pathless layout route: its children inherit the parent path. */\n path?: string\n index?: boolean\n children?: readonly RegisteredRoute[]\n}\n\n/** A route table entry is either a bare pattern string or a router config node. */\nexport type NavRouteTable = readonly (string | RegisteredRoute)[]\n\nfunction joinPattern(parent: string, child: string): string {\n if (child.startsWith('/')) return child\n if (child === '') return parent\n return `${parent}/${child}`\n}\n\n/**\n * Every path pattern the table registers, rooted and de-duplicated.\n *\n * Parent nodes contribute their own cumulative path as well as their children's:\n * a router matches a parent route with an index child at the parent path, and a\n * parent without one still matches with an empty outlet, so treating parents as\n * unregistered would flag working hrefs.\n */\nexport function flattenRouteTable(table: NavRouteTable): string[] {\n const patterns: string[] = []\n const walk = (entries: NavRouteTable, parent: string): void => {\n for (const entry of entries) {\n if (typeof entry === 'string') {\n patterns.push(toRootedPath(joinPattern(parent, entry)))\n continue\n }\n const own = entry.path === undefined ? parent : joinPattern(parent, entry.path)\n patterns.push(toRootedPath(own))\n if (entry.children) walk(entry.children, own)\n }\n }\n walk(table, '')\n return [...new Set(patterns)]\n}\n\n/**\n * Whole-path segment match of a concrete path against one route pattern.\n *\n * Supports the three pattern forms a router uses: literal segments, `:param`\n * (exactly one non-empty segment), optional `:param?` / `segment?` (zero or\n * one), and a trailing `*` splat (zero or more). Matching is recursive because\n * an optional segment forks the walk — a linear scan silently mismatches\n * `/a/b` against `a/:x?/b`.\n */\nfunction matchesPattern(pathSegments: readonly string[], patternSegments: readonly string[], caseSensitive: boolean): boolean {\n if (patternSegments.length === 0) return pathSegments.length === 0\n const head = patternSegments[0] ?? ''\n if (head === '*') return true\n const rest = patternSegments.slice(1)\n const optional = head.endsWith('?')\n const core = optional ? head.slice(0, -1) : head\n const first = pathSegments[0]\n if (first !== undefined) {\n const hit = core.startsWith(':')\n ? first.length > 0\n : caseSensitive\n ? core === first\n : core.toLowerCase() === first.toLowerCase()\n if (hit && matchesPattern(pathSegments.slice(1), rest, caseSensitive)) return true\n }\n return optional ? matchesPattern(pathSegments, rest, caseSensitive) : false\n}\n\n// ---------------------------------------------------------------------------\n// The guard\n// ---------------------------------------------------------------------------\n\n/**\n * A nav row as the guard needs to see it. Structurally satisfied by\n * `SessionRailNavItem` / `SessionRailSubItem` and by sandbox-ui's\n * `SidebarLayoutNavItem`, so the guard runs over the builder's real output\n * rather than a re-declaration of it.\n */\nexport interface NavHrefItem {\n id: string\n href: string\n subItems?: readonly NavHrefItem[]\n}\n\nexport type NavHrefProblemReason =\n /** No registered pattern matches the resolved href. */\n | 'unregistered'\n /** Empty, fragment-only, or not rooted at `/` — the row navigates nowhere\n * predictable regardless of the route table. */\n | 'not-a-path'\n /** Leaves the router (scheme or protocol-relative) while `allowExternal` is\n * off. */\n | 'external'\n\nexport interface NavHrefProblem {\n id: string\n href: string\n reason: NavHrefProblemReason\n /** Registered patterns ending in the same segment. A destination resolved\n * under the wrong base lands here as its correctly-based twin, which is what\n * names the missing scope in the failure message. */\n nearest: string[]\n message: string\n}\n\nexport interface NavHrefReport {\n /** Hrefs examined, including nested sub-items. */\n checked: number\n problems: NavHrefProblem[]\n /** Off-router destinations accepted because `allowExternal` is on. */\n external: string[]\n /** The flattened route table the check ran against. */\n patterns: string[]\n}\n\nexport interface NavHrefCheckOptions {\n /** Hrefs to skip, compared after query/fragment removal. For a destination\n * served outside this route table (a static asset, another worker). */\n ignore?: readonly string[]\n /** Absolute URLs / `mailto:` / `tel:` are reported under `external` instead\n * of failing. Default true. */\n allowExternal?: boolean\n /** Compare literal segments case-sensitively. Default true — a router that\n * matches case-insensitively still renders a link the deploy's CDN or a\n * case-sensitive origin may not. */\n caseSensitive?: boolean\n}\n\n/** `scheme:` or `//host` — anything the router will not resolve as a path. */\nconst OFF_ROUTER_HREF = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i\n\nfunction flattenItems(items: readonly NavHrefItem[], out: NavHrefItem[] = []): NavHrefItem[] {\n for (const item of items) {\n out.push(item)\n if (item.subItems) flattenItems(item.subItems, out)\n }\n return out\n}\n\n/**\n * Check every nav href against the product's route table.\n *\n * Pure — returns the full report so a caller can assert on parts of it. Use\n * {@link assertNavHrefsRegistered} in tests; it turns the report into a failure\n * that names the offending row, its resolved href, and the near-miss pattern.\n */\nexport function checkNavHrefs(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): NavHrefReport {\n const { ignore, allowExternal = true, caseSensitive = true } = options\n const patterns = flattenRouteTable(routes)\n const patternSegments = patterns.map((pattern) => ({ pattern, segments: toSegments(pattern) }))\n const ignored = new Set((ignore ?? []).map((href) => normalizePath(href)))\n const problems: NavHrefProblem[] = []\n const external: string[] = []\n const flat = flattenItems(items)\n let checked = 0\n\n for (const item of flat) {\n const raw = item.href\n const path = normalizePath(raw)\n if (ignored.has(path)) continue\n if (OFF_ROUTER_HREF.test(raw)) {\n if (allowExternal) {\n external.push(raw)\n continue\n }\n // Counted as checked: it was examined and rejected, so the vacuous-pass\n // guard must not read this run as \"nothing was looked at\".\n checked += 1\n problems.push({\n id: item.id,\n href: raw,\n reason: 'external',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' leaves the router, and external destinations are rejected`,\n })\n continue\n }\n checked += 1\n if (raw === '' || raw.startsWith('#') || !raw.startsWith('/')) {\n problems.push({\n id: item.id,\n href: raw,\n reason: 'not-a-path',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' is not a rooted path — it cannot resolve to a registered route`,\n })\n continue\n }\n const segments = toSegments(path)\n if (patternSegments.some((candidate) => matchesPattern(segments, candidate.segments, caseSensitive))) continue\n const nearest = nearestPatterns(segments, patternSegments.map((candidate) => candidate.pattern), caseSensitive)\n problems.push({\n id: item.id,\n href: raw,\n reason: 'unregistered',\n nearest,\n message:\n `Nav item '${item.id}' href '${raw}' matches no registered route` +\n (nearest.length ? ` — nearest registered: ${nearest.join(', ')}` : ''),\n })\n }\n\n return { checked, problems, external, patterns }\n}\n\n/** Registered patterns whose last segment equals the href's last segment: the\n * same destination under a different base is the near-miss worth printing. */\nfunction nearestPatterns(segments: readonly string[], patterns: readonly string[], caseSensitive: boolean): string[] {\n const tail = segments[segments.length - 1]\n if (tail === undefined) return []\n const same = (a: string, b: string): boolean => (caseSensitive ? a === b : a.toLowerCase() === b.toLowerCase())\n return patterns\n .filter((pattern) => {\n const patternTail = toSegments(pattern).at(-1)\n return patternTail !== undefined && same(patternTail, tail)\n })\n .slice(0, 5)\n}\n\n/**\n * Fail unless every nav href resolves to a registered route.\n *\n * Throws on an empty item list or an empty route table as well: a guard that\n * examined nothing reports safety it does not provide, and both are what a\n * mis-wired import looks like.\n */\nexport function assertNavHrefsRegistered(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): void {\n if (items.length === 0) {\n throw new Error('assertNavHrefsRegistered received no nav items — the check would pass without examining anything')\n }\n const report = checkNavHrefs(items, routes, options)\n if (report.patterns.length === 0) {\n throw new Error('assertNavHrefsRegistered received an empty route table — every href would fail or nothing would be proven')\n }\n // Real problems are reported before the vacuous-pass guard: rejected external\n // hrefs are problems that were never \"checked\", and the guard's message would\n // otherwise hide them.\n if (report.problems.length > 0) {\n const detail = report.problems.map((problem) => ` - ${problem.message}`).join('\\n')\n throw new Error(\n `${report.problems.length} of ${report.checked} nav hrefs do not resolve to a registered route:\\n${detail}\\n` +\n `Registered patterns (${report.patterns.length}): ${report.patterns.join(', ')}`,\n )\n }\n if (report.checked === 0) {\n throw new Error(\n `assertNavHrefsRegistered examined 0 hrefs (${report.external.length} external, ${ignoredCount(items, options)} ignored) — the check would pass without examining anything`,\n )\n }\n}\n\nfunction ignoredCount(items: readonly NavHrefItem[], options: NavHrefCheckOptions): number {\n const ignored = new Set((options.ignore ?? []).map((href) => normalizePath(href)))\n return flattenItems(items).filter((item) => ignored.has(normalizePath(item.href))).length\n}\n","/**\n * Command palette — the React-free selection half of the Cmd/Ctrl+K surface\n * (`/web-react` holds the rendered half, `CommandPalette`).\n *\n * Pure and import-free beyond this module's own types: no React, no DOM, no\n * fuse.js. A route loader or a worker can build and rank the same items the\n * browser renders.\n *\n * Domain stays a parameter. The palette knows two kinds of row — a SESSION the\n * user can jump to and an ACTION the product offers (new chat, toggle theme,\n * open settings) — and both arrive as data. What a selection DOES is the\n * product's business; the shell only builds, ranks, and groups.\n *\n * Ranking is the documented ladder, not a fuzzy library: exact > prefix >\n * word-prefix > substring (earlier index wins) > token-order, with keyword\n * hits ranked a fixed step below the same hit on the label. Deterministic —\n * no index-building, no async, same input always sorts the same way.\n */\n\nimport { sessionLabel, UNTITLED_SESSION_LABEL, type SessionSummary } from './index'\n\n/** A product-supplied palette action. `hint` is the right-aligned affordance\n * copy (a kbd chord, a route name) — rendered verbatim, never interpreted. */\nexport interface CommandPaletteAction {\n id: string\n label: string\n description?: string\n hint?: string\n /** Extra match vocabulary that never renders (`settings` matching\n * \"preferences\"). A keyword hit ranks below the same hit on the label. */\n keywords?: string[]\n}\n\n/** One selectable row. `group` is the section header it renders under. */\nexport interface CommandPaletteItem {\n id: string\n group: string\n label: string\n description?: string\n hint?: string\n keywords?: string[]\n /** Recency key (ISO-8601). Breaks score ties and orders the unfiltered\n * list recent-first. Rows without one sort below rows with one. */\n recentAt?: string | null\n}\n\n/** One rendered section: a header plus its rows, in first-seen group order. */\nexport interface CommandPaletteGroup {\n group: string\n items: CommandPaletteItem[]\n}\n\nexport const COMMAND_PALETTE_SESSIONS_GROUP = 'Sessions'\nexport const COMMAND_PALETTE_ACTIONS_GROUP = 'Actions'\n\nexport interface BuildCommandPaletteItemsOptions {\n sessions?: readonly SessionSummary[]\n actions?: readonly CommandPaletteAction[]\n /** Section label for sessions. Default \"Sessions\". */\n sessionsLabel?: string\n /** Section label for actions. Default \"Actions\". */\n actionsLabel?: string\n /** Placeholder title for an untitled session. */\n untitledLabel?: string\n}\n\n/**\n * Flatten sessions + actions into palette items, sessions group first (the\n * jump-back-in list), actions after. Sessions order recent-first by\n * `updatedAt` — a palette with an empty query IS the recency list, so the\n * build order is the render order and the filter never has to re-derive it.\n * Pinned sessions lead the recency sort, matching the rail.\n */\nexport function buildCommandPaletteItems({\n sessions = [],\n actions = [],\n sessionsLabel = COMMAND_PALETTE_SESSIONS_GROUP,\n actionsLabel = COMMAND_PALETTE_ACTIONS_GROUP,\n untitledLabel = UNTITLED_SESSION_LABEL,\n}: BuildCommandPaletteItemsOptions): CommandPaletteItem[] {\n const ordered = [...sessions].sort((a, b) => {\n if (!!a.isPinned !== !!b.isPinned) return a.isPinned ? -1 : 1\n return compareRecent(a.updatedAt, b.updatedAt)\n })\n const sessionItems: CommandPaletteItem[] = ordered.map((session) => ({\n id: session.id,\n group: sessionsLabel,\n label: sessionLabel(session, untitledLabel),\n keywords: session.category ? [session.category] : undefined,\n recentAt: session.updatedAt,\n }))\n const actionItems: CommandPaletteItem[] = actions.map((action) => ({\n id: action.id,\n group: actionsLabel,\n label: action.label,\n description: action.description,\n hint: action.hint,\n keywords: action.keywords,\n }))\n return [...sessionItems, ...actionItems]\n}\n\n/** Newer first; an undated row sorts below every dated one. ISO strings\n * compare lexicographically. */\nfunction compareRecent(a: string | null | undefined, b: string | null | undefined): number {\n if (a && b) return a < b ? 1 : a > b ? -1 : 0\n if (a) return -1\n if (b) return 1\n return 0\n}\n\n/** Collapse whitespace, lowercase once — every comparison runs on this form. */\nfunction normalize(text: string): string {\n return text.trim().toLowerCase().replace(/\\s+/g, ' ')\n}\n\n/** Words of a normalized string: runs of letters/numbers, so \"new-chat\" and\n * \"new chat\" word-prefix identically. */\nconst WORD_SPLIT = /[^\\p{L}\\p{N}]+/u\n\nfunction wordsOf(text: string): string[] {\n return text.split(WORD_SPLIT).filter(Boolean)\n}\n\n/** How far below a label hit the same keyword hit ranks: any label match, even\n * a token-order one (40), outranks a keyword exact match (100 − 65 = 35). */\nconst KEYWORD_PENALTY = 65\n\n/**\n * Score one text against the query on the prefix > substring > token-order\n * ladder. Returns `null` for no match. Higher is better; tiers are spaced so\n * no within-tier adjustment can cross a tier boundary:\n *\n * - 100 exact\n * - 90 prefix (`text` starts with the query)\n * - 80 word-prefix (a WORD starts with the query — \"chat\" hits \"New chat\")\n * - 60–79 substring, minus the match index clamped to 19 (earlier wins)\n * - 40 token-order (every query token matches a later word, in order)\n */\nfunction scoreText(text: string, query: string): number | null {\n if (!query) return 0\n if (text === query) return 100\n if (text.startsWith(query)) return 90\n const words = wordsOf(text)\n if (words.some((word) => word.startsWith(query))) return 80\n const at = text.indexOf(query)\n if (at >= 0) return 60 + Math.max(0, 19 - at)\n const tokens = wordsOf(query)\n if (tokens.length > 1) {\n let atWord = 0\n const inOrder = tokens.every((token) => {\n while (atWord < words.length) {\n const word = words[atWord]\n atWord += 1\n // Guarded by the while condition; noUncheckedIndexedAccess can't see it.\n if (word !== undefined && (word.startsWith(token) || word.includes(token))) return true\n }\n return false\n })\n if (inOrder) return 40\n }\n return null\n}\n\n/**\n * Score an item: the best label score, or the best keyword score a fixed step\n * below. `null` when neither matches — the item is filtered out. An empty\n * query scores every item 0 (the caller keeps build order: recent-first).\n */\nexport function scoreCommandPaletteItem(item: CommandPaletteItem, query: string): number | null {\n const q = normalize(query)\n const label = scoreText(normalize(item.label), q)\n let best = label\n for (const keyword of item.keywords ?? []) {\n const score = scoreText(normalize(keyword), q)\n if (score !== null) {\n const penalized = score - KEYWORD_PENALTY\n if (best === null || penalized > best) best = penalized\n }\n }\n return best\n}\n\n/**\n * Filter + rank: an empty query returns the items untouched (build order is\n * the recency order); a real query drops non-matches and sorts by score, then\n * recency, then original position — stable and deterministic.\n */\nexport function filterCommandPaletteItems(\n items: readonly CommandPaletteItem[],\n query: string,\n): CommandPaletteItem[] {\n if (!normalize(query)) return [...items]\n const scored: Array<{ item: CommandPaletteItem; score: number; index: number }> = []\n items.forEach((item, index) => {\n const score = scoreCommandPaletteItem(item, query)\n if (score !== null) scored.push({ item, score, index })\n })\n scored.sort((a, b) => {\n if (a.score !== b.score) return b.score - a.score\n const recent = compareRecent(a.item.recentAt, b.item.recentAt)\n if (recent !== 0) return recent\n return a.index - b.index\n })\n return scored.map(({ item }) => item)\n}\n\n/**\n * Fold a flat (already ordered) item list into renderable sections. Groups\n * appear in first-seen order and each group appears ONCE — a filtered ranking\n * interleaves sessions and actions by score, and folding only consecutive runs\n * would render the same header twice. Within a group, rows keep the flat\n * order. Empty groups vanish, so a filter that leaves only actions renders no\n * \"Sessions\" header over nothing.\n */\nexport function groupCommandPaletteItems(items: readonly CommandPaletteItem[]): CommandPaletteGroup[] {\n const groups: CommandPaletteGroup[] = []\n const byGroup = new Map<string, CommandPaletteGroup>()\n for (const item of items) {\n let group = byGroup.get(item.group)\n if (!group) {\n group = { group: item.group, items: [] }\n byGroup.set(item.group, group)\n groups.push(group)\n }\n group.items.push(item)\n }\n return groups\n}\n","/**\n * Session shell — the app-shell mechanism every agent product needs around the\n * chat surface: a list of past sessions in the rail, an entry point for a new\n * one, and a paged history view behind it.\n *\n * `/web-react` already owns the chat SURFACE (composer, transcript, cards); it\n * owned no session SHELL, so all four products hand-rolled one and drifted.\n * This module is the shell's pure half: no React, no DOM, no peer imports, so a\n * server loader can call `readRailCollapsedCookie` without dragging React into\n * a worker bundle (`/web-react` holds the rendered half).\n *\n * Domain stays a parameter. A \"session\" here is only an id, a title and a\n * timestamp — a gtm thread, a tax session and a legal matter are all the same\n * shape to the shell, and the product supplies routing through `hrefForSession`\n * rather than the shell knowing any URL.\n */\n\nimport { isUnderPrefix, normalizePath, stripSlashes, stripTrailingSlashes } from './path'\n\nexport * from './nav-guard'\nexport * from './command-palette'\n\n/** One session as the shell needs to see it. Products map their own row\n * (thread / session / matter) onto this before handing it over. */\nexport interface SessionSummary {\n id: string\n /** `null`/empty renders as the untitled placeholder rather than a blank row. */\n title: string | null\n /** ISO-8601. `null` when the product has no timestamp to show. */\n updatedAt: string | null\n isPinned?: boolean\n /** Unread for the viewer. Use `resolveSessionUnread` to fold live overlays in. */\n unread?: boolean\n /** Free-form product label (gtm categories, legal matter types). Passed\n * through untouched — the shell never interprets it. */\n category?: string | null\n}\n\n/** One fetched page of sessions with an optional continuation cursor. */\nexport interface SessionPage {\n items: SessionSummary[]\n /** Opaque continuation token; absent/null ⇒ no further pages. */\n nextCursor?: string | null\n}\n\n/** Sort order for the history view. The product's fetcher decides what these\n * mean against its own storage; the shell only round-trips the value. */\nexport type SessionSort = 'newest' | 'oldest'\n\n// ---------------------------------------------------------------------------\n// Rail items — structurally assignable to sandbox-ui's SidebarLayout types\n// ---------------------------------------------------------------------------\n\n/**\n * These mirror `@tangle-network/sandbox-ui/dashboard`'s `SidebarLayoutNavItem`\n * / `RailExpandableSubItem` STRUCTURALLY rather than importing them, so this\n * module stays free of the optional peer (invariant 3 — structural over\n * hard-dep when the surface is small). `tests/session-shell/rail-contract.test.ts`\n * assigns the builder output to the real sandbox-ui types, so a drift in either\n * direction fails CI instead of silently dropping a field at runtime.\n *\n * `TIcon` is the product's icon component type (lucide, custom, anything) —\n * generic so this file needs no React types.\n */\nexport interface SessionRailAction<TIcon = unknown> {\n id: string\n label: string\n icon?: TIcon\n destructive?: boolean\n onSelect: () => void\n}\n\nexport type RailPrefetch = 'none' | 'intent' | 'render' | 'viewport'\n\nexport interface SessionRailSubItem<TIcon = unknown> {\n id: string\n label: string\n href: string\n prefetch?: RailPrefetch\n /** Live working indicator — the session is mid-turn. */\n isLoading?: boolean\n /** Bold + leading dot. sandbox-ui suppresses it while `isLoading`. */\n unread?: boolean\n /** Emphasised row, used for the trailing \"view all\" overflow link. */\n emphasis?: boolean\n actions?: SessionRailAction<TIcon>[]\n}\n\nexport interface SessionRailNavItem<TIcon = unknown> {\n id: string\n /** REQUIRED, mirroring sandbox-ui — the rail renders `<Icon />` unguarded, so\n * an omitted icon is a blank/crashing row rather than a styling nit. */\n icon: TIcon\n label: string\n href: string\n badge?: number\n expandable?: boolean\n defaultOpen?: boolean\n subItems?: SessionRailSubItem<TIcon>[]\n subActiveIds?: string[]\n emptyLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Per-row rename/delete wiring. Supplied by the layout that owns the dialogs;\n * omitted (or `canEdit: false`) leaves rows read-only. */\nexport interface SessionRowActions<TIcon = unknown> {\n canEdit: boolean\n renameIcon?: TIcon\n deleteIcon?: TIcon\n renameLabel?: string\n deleteLabel?: string\n /**\n * Omit when the product cannot rename a session — the row then offers delete\n * only, instead of a menu item that does nothing.\n *\n * Independently optional, matching `SessionHistoryPanel`, which has always\n * rendered whichever of the two it was given. The rail builder used to demand\n * both, so a product with archive-but-no-rename (tax) could either fake a\n * rename or ship no row actions at all.\n */\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /**\n * Row actions this shell has no opinion about — pin, categorise, duplicate,\n * share. Evaluated per session so a label can read that row's state\n * (\"Pin\" vs \"Unpin\"), and ordered between rename and delete so the\n * destructive action stays last.\n *\n * `id` must not be `rename` or `delete`; those are the shell's own.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction<TIcon>[]\n}\n\nexport const UNTITLED_SESSION_LABEL = 'Untitled chat'\n\n/** Display title for a session row — trims, and falls back rather than\n * rendering an empty row the user cannot aim at. */\nexport function sessionLabel(session: SessionSummary, untitled = UNTITLED_SESSION_LABEL): string {\n return session.title?.trim() || untitled\n}\n\nexport interface BuildSessionSubItemsOptions<TIcon = unknown> {\n sessions: SessionSummary[]\n /** The product's route for one session. The shell never builds a URL itself. */\n hrefForSession: (sessionId: string) => string\n /** Ids currently mid-turn — renders the working indicator. */\n respondingSessionIds?: ReadonlySet<string>\n actions?: SessionRowActions<TIcon>\n untitledLabel?: string\n prefetch?: RailPrefetch\n /** Trailing \"view all\" row, appended when the capped list hides sessions. */\n overflow?: { href: string; label?: string }\n}\n\n/** Session rows for the rail's expandable history item. */\nexport function buildSessionSubItems<TIcon = unknown>({\n sessions,\n hrefForSession,\n respondingSessionIds,\n actions,\n untitledLabel = UNTITLED_SESSION_LABEL,\n prefetch = 'intent',\n overflow,\n}: BuildSessionSubItemsOptions<TIcon>): SessionRailSubItem<TIcon>[] {\n /**\n * Only the handlers the product actually supplied. An empty result becomes\n * `undefined` rather than `[]`, because sandbox-ui renders the kebab trigger\n * whenever `actions` is an array — an empty one is a button that opens an\n * empty menu.\n */\n const rowActions = (session: SessionSummary): SessionRailAction<TIcon>[] | undefined => {\n if (!actions?.canEdit) return undefined\n const built: SessionRailAction<TIcon>[] = []\n const { onRename, onDelete, extraActions } = actions\n if (onRename) {\n built.push({\n id: 'rename',\n label: actions.renameLabel ?? 'Rename',\n icon: actions.renameIcon,\n onSelect: () => onRename(session),\n })\n }\n if (extraActions) built.push(...extraActions(session))\n if (onDelete) {\n built.push({\n id: 'delete',\n label: actions.deleteLabel ?? 'Delete',\n icon: actions.deleteIcon,\n destructive: true,\n onSelect: () => onDelete(session),\n })\n }\n return built.length ? built : undefined\n }\n\n const rows: SessionRailSubItem<TIcon>[] = sessions.map((session) => ({\n id: session.id,\n label: sessionLabel(session, untitledLabel),\n href: hrefForSession(session.id),\n prefetch,\n isLoading: respondingSessionIds?.has(session.id) ?? false,\n unread: Boolean(session.unread),\n actions: rowActions(session),\n }))\n if (!overflow) return rows\n return [\n ...rows,\n {\n id: 'view-all',\n label: overflow.label ?? 'View all chats',\n href: overflow.href,\n prefetch,\n emphasis: true,\n },\n ]\n}\n\nexport interface BuildSessionNavItemOptions<TIcon = unknown>\n extends BuildSessionSubItemsOptions<TIcon> {\n /** Nav id the product highlights against (`activeNavId === id`). */\n id?: string\n label?: string\n /** The product's icon component. Required — see `SessionRailNavItem.icon`. */\n icon: TIcon\n /** The expandable row's own destination — the full history page. */\n href: string\n /** Session currently open, highlighted inside the expandable. */\n activeSessionId?: string | null\n emptyLabel?: string\n defaultOpen?: boolean\n}\n\n/**\n * The rail's session entry: one expandable nav row whose sub-items are the\n * recent sessions. This is the structure the owner asked for — history lives IN\n * the rail, not in a second sidebar panel beside it.\n */\nexport function buildSessionNavItem<TIcon = unknown>({\n id = 'history',\n label = 'History',\n icon,\n href,\n activeSessionId,\n emptyLabel = 'No chats yet',\n defaultOpen = true,\n ...subItemOptions\n}: BuildSessionNavItemOptions<TIcon>): SessionRailNavItem<TIcon> {\n return {\n id,\n icon,\n label,\n href,\n expandable: true,\n defaultOpen,\n subItems: buildSessionSubItems<TIcon>(subItemOptions),\n subActiveIds: activeSessionId ? [activeSessionId] : undefined,\n emptyLabel,\n prefetch: subItemOptions.prefetch ?? 'intent',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Routing / selection\n// ---------------------------------------------------------------------------\n\nexport interface ActiveSessionIdOptions {\n pathname: string\n /** Workspace-scoped route base, e.g. `/app/ws_123`. */\n base: string\n /** Route segment sessions live under. Default `chat` ⇒ `${base}/chat/:id`.\n * Pass `''` when sessions sit DIRECTLY under the base (`/app/:sessionId`),\n * which is how one product routes them — then `reserved` is mandatory. */\n segment?: string\n /** Segment that means \"composing a new session\", not an id. Default `new`. */\n newSegment?: string\n /**\n * First segments that are OTHER routes, not session ids. Only meaningful\n * with `segment: ''`, where `/app/settings` is otherwise indistinguishable\n * from a session called `settings` — and resolving it as one would highlight\n * and prefetch a session that does not exist. Pass the product's own nav\n * paths; unknown-but-reserved is a routing bug, so this fails closed.\n */\n reserved?: readonly string[]\n}\n\n/**\n * The session id the current route has open, or `null` on the new-session\n * composer / anywhere else.\n *\n * Anchored at `base` on purpose. A bare `/\\/chat\\/([^/]+)/` scan — the shape\n * three products shipped — matches the FIRST `/chat/` anywhere in the path, so\n * a workspace or vault folder named `chat` resolves a neighbouring segment as a\n * session id and the rail highlights (and prefetches) a session the user is not\n * in. Same class as attaching to a stale box: it looks right and points at the\n * wrong row.\n */\nexport function activeSessionIdFromPath({\n pathname,\n base,\n segment = 'chat',\n newSegment = 'new',\n reserved,\n}: ActiveSessionIdOptions): string | null {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n const prefix = segment ? `${root}/${segment}` : root\n if (!isUnderPrefix(path, prefix) || path === prefix) return null\n const id = path.slice(prefix.length + 1).split('/')[0] ?? ''\n if (!id || id === newSegment) return null\n // `/app/settings` under a segment-less route is a sibling page, not a\n // session named \"settings\".\n if (reserved?.some((name) => stripSlashes(name) === id)) return null\n return decodeURIComponent(id)\n}\n\n/** One rail destination. `path` is relative to the workspace base. */\nexport interface NavRouteDef {\n id: string\n path: string\n}\n\nexport interface ResolveActiveNavIdOptions {\n pathname: string\n base: string\n /** The product's rail rows, in any order — resolution is longest-prefix. */\n routes: NavRouteDef[]\n /** Extra prefixes that light an existing row: `{ '/agents': 'integrations' }`.\n * Participates in the same longest-prefix contest. */\n aliases?: Record<string, string>\n /** Prefixes that deliberately highlight NOTHING, beating any shorter match.\n * gtm uses this so an open chat lights no rail row while `/chat/new` still\n * lights \"New\". */\n claimsNothing?: string[]\n}\n\n/**\n * The rail row to highlight for the current route.\n *\n * Longest-prefix wins, so declaration order cannot change the answer. The\n * per-product versions this replaces were first-match over an array, which made\n * `/chat/new` vs `/chat` an ordering accident rather than a rule.\n */\nexport function resolveActiveNavId({\n pathname,\n base,\n routes,\n aliases,\n claimsNothing,\n}: ResolveActiveNavIdOptions): string | undefined {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (relative: string, id: string | undefined, winsTies = false) => {\n const full = stripTrailingSlashes(`${root}${relative}`)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const route of routes) consider(route.path, route.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix in\n // `claimsNothing` is a deliberate override of the row that owns it, so\n // `claimsNothing: ['/chat']` beats a `{ id: 'chat', path: '/chat' }` row while\n // a longer `/chat/new` still wins on specificity.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Sidebar list composition\n// ---------------------------------------------------------------------------\n\nexport interface ResolveSessionUnreadOptions {\n sessionId: string\n /** Server-computed unread from the route loader. */\n loaderUnread: boolean\n /** Live \"went unread\" ids from the workspace channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has already opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** The open session is never unread to its own viewer. */\n currentSessionId?: string | null\n}\n\n/**\n * Effective unread for one row. The loader's value can be stale — a layout\n * loader that survives same-workspace navigation keeps reporting a session as\n * unread after the user opened it — so live and local overlays win over it, and\n * the currently-open session always reads as read.\n */\nexport function resolveSessionUnread({\n sessionId,\n loaderUnread,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ResolveSessionUnreadOptions): boolean {\n if (sessionId === currentSessionId) return false\n if (liveUnreadIds?.has(sessionId)) return true\n if (locallyReadIds?.has(sessionId)) return false\n return loaderUnread\n}\n\nexport interface ComposeSidebarSessionsOptions {\n /** Server-rendered rows, already ordered by the product's query. */\n loaderSessions: SessionSummary[]\n /** Optimistic rows from the live channel (a chat created in another tab). */\n optimisticSessions?: SessionSummary[]\n /** Rail cap. The full list lives on the history page. */\n limit: number\n /** Total sessions the product holds, used to decide the overflow row. */\n totalCount?: number\n liveUnreadIds?: ReadonlySet<string>\n locallyReadIds?: ReadonlySet<string>\n currentSessionId?: string | null\n}\n\nexport interface ComposedSidebarSessions {\n sessions: SessionSummary[]\n /** More sessions exist than the rail shows ⇒ render the \"view all\" row. */\n hasMore: boolean\n}\n\n/**\n * The rail's session list: optimistic rows first, then the loader's, capped,\n * with unread resolved per row.\n *\n * Optimistic rows are deduped against the loader by id — once a revalidation\n * brings a live-created session back from the server it must not appear twice\n * (duplicate React keys, and the row's actions would target the same session\n * from two places).\n */\nexport function composeSidebarSessions({\n loaderSessions,\n optimisticSessions = [],\n limit,\n totalCount,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ComposeSidebarSessionsOptions): ComposedSidebarSessions {\n const loaderIds = new Set(loaderSessions.map((session) => session.id))\n const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id))\n const merged = [...pendingNew, ...loaderSessions]\n const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({\n ...session,\n unread: resolveSessionUnread({\n sessionId: session.id,\n loaderUnread: Boolean(session.unread),\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n }),\n }))\n const known = (totalCount ?? loaderSessions.length) + pendingNew.length\n return { sessions, hasMore: known > sessions.length }\n}\n\n/**\n * Append a fetched page to held rows, dropping ids already shown. A session\n * bumped to the top between two page fetches otherwise arrives twice — once in\n * the page it moved out of and once in the page it moved into.\n */\nexport function mergeSessionPages(\n existing: SessionSummary[],\n incoming: SessionSummary[],\n): SessionSummary[] {\n const seen = new Set(existing.map((session) => session.id))\n return [...existing, ...incoming.filter((session) => !seen.has(session.id))]\n}\n\n// ---------------------------------------------------------------------------\n// Rail collapse cookie (SSR-seeded so the first paint matches the client)\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_RAIL_COOKIE_NAME = 'agent-sidebar-rail-collapsed'\n\n/**\n * Read the persisted rail-collapse state from a request's `Cookie` header, so\n * the server renders the rail in the state the user left it and the first\n * client render does not re-flow.\n *\n * Parses the header rather than building a `RegExp` from the cookie name (the\n * shape the products shipped): a name containing a regex metacharacter would\n * silently match the wrong cookie or none at all.\n */\nexport function readRailCollapsedCookie(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_RAIL_COOKIE_NAME,\n): boolean {\n for (const pair of (cookieHeader ?? '').split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n return pair.slice(eq + 1).trim() === '1'\n }\n return false\n}\n\nexport interface RailCookieOptions {\n name?: string\n /** Seconds. Default one year. */\n maxAge?: number\n path?: string\n /** Omit to auto-detect: `secure` on https, off on http://localhost — a Secure\n * cookie is dropped there and the rail state would not persist in dev. */\n secure?: boolean\n}\n\n/** The cookie string for a collapse state. Usable as `document.cookie` or as a\n * `Set-Cookie` value. Exported separately so it is testable without a DOM. */\nexport function railCollapsedCookie(\n collapsed: boolean,\n { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31_536_000, path = '/', secure }: RailCookieOptions = {},\n): string {\n const isSecure =\n secure ?? (typeof location !== 'undefined' && location.protocol === 'https:')\n return `${name}=${collapsed ? '1' : '0'}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? '; secure' : ''}`\n}\n\n/** Persist the rail-collapse state from the browser. No-op without a document\n * so a shared toggle handler is safe to call during SSR. */\nexport function writeRailCollapsedCookie(collapsed: boolean, options: RailCookieOptions = {}): void {\n if (typeof document === 'undefined') return\n document.cookie = railCollapsedCookie(collapsed, options)\n}\n"],"mappings":";AAMO,SAAS,qBAAqB,OAAuB;AAC1D,SAAO,MAAM,QAAQ,QAAQ,EAAE;AACjC;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAIO,SAAS,cAAc,UAA0B;AACtD,QAAM,cAAc,SAAS,MAAM,GAAG,EAAE,CAAC,KAAK;AAC9C,QAAM,eAAe,YAAY,MAAM,GAAG,EAAE,CAAC,KAAK;AAClD,SAAO,qBAAqB,YAAY;AAC1C;AAIO,SAAS,cAAc,MAAc,QAAyB;AACnE,QAAM,IAAI,qBAAqB,MAAM;AACrC,MAAI,MAAM,GAAI,QAAO;AACrB,SAAO,SAAS,KAAK,KAAK,WAAW,GAAG,CAAC,GAAG;AAC9C;AAIO,SAAS,WAAW,OAAyB;AAClD,SAAO,MAAM,MAAM,GAAG,EAAE,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AAChE;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,IAAI,WAAW,KAAK,EAAE,KAAK,GAAG,CAAC;AACxC;;;ACuBO,SAAS,eACd,aACA,OACQ;AACR,QAAM,OAAO,MAAM,YAAY,KAAK;AACpC,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI;AAAA,MACR,oBAAoB,YAAY,EAAE,iBAAiB,YAAY,KAAK;AAAA,IACtE;AAAA,EACF;AACA,MAAI,YAAY,SAAS,MAAM,CAAC,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;AACF,QAAM,SAAS,cAAc,eAAe,UAAU,WAAW;AACjE,SAAO,EAAE,UAAU,SAAS,QAAQ,SAAS,OAAO;AACtD;AAOO,SAAS,kBACd,UACA,UACkB;AAClB,QAAM,OAAO,IAAI,IAAI,SAAS,IAAI,CAAC,YAAY,QAAQ,EAAE,CAAC;AAC1D,SAAO,CAAC,GAAG,UAAU,GAAG,SAAS,OAAO,CAAC,YAAY,CAAC,KAAK,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC7E;AAMO,IAAM,2BAA2B;AAWjC,SAAS,wBACd,cACA,OAAe,0BACN;AACT,aAAW,SAAS,gBAAgB,IAAI,MAAM,GAAG,GAAG;AAClD,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,GAAI;AACf,QAAI,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,KAAM;AACvC,WAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK,MAAM;AAAA,EACvC;AACA,SAAO;AACT;AAcO,SAAS,oBACd,WACA,EAAE,OAAO,0BAA0B,SAAS,SAAY,OAAO,KAAK,OAAO,IAAuB,CAAC,GAC3F;AACR,QAAM,WACJ,WAAW,OAAO,aAAa,eAAe,SAAS,aAAa;AACtE,SAAO,GAAG,IAAI,IAAI,YAAY,MAAM,GAAG,UAAU,IAAI,aAAa,MAAM,iBAAiB,WAAW,aAAa,EAAE;AACrH;AAIO,SAAS,yBAAyB,WAAoB,UAA6B,CAAC,GAAS;AAClG,MAAI,OAAO,aAAa,YAAa;AACrC,WAAS,SAAS,oBAAoB,WAAW,OAAO;AAC1D;","names":[]}
1
+ {"version":3,"sources":["../src/session-shell/path.ts","../src/session-shell/nav-guard.ts","../src/session-shell/command-palette.ts","../src/session-shell/index.ts"],"sourcesContent":["/**\n * Path normalisation shared by the shell's routing helpers. Segment-aligned\n * comparison is the invariant: `/vault` must never claim `/vault-archive`, so\n * every prefix test here works on whole segments rather than string prefixes.\n */\n\nexport function stripTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\n/** Bare segment name, so a caller may pass `'/settings'` or `'settings'`. */\nexport function stripSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\n/** Path with query + fragment removed and trailing slashes trimmed. A caller\n * passing a full href instead of a pathname would otherwise match nothing. */\nexport function normalizePath(pathname: string): string {\n const withoutHash = pathname.split('#')[0] ?? ''\n const withoutQuery = withoutHash.split('?')[0] ?? ''\n return stripTrailingSlashes(withoutQuery)\n}\n\n/** True when `path` is `prefix` or a segment-aligned descendant of it, so\n * `/vault` never claims `/vault-archive`. */\nexport function isUnderPrefix(path: string, prefix: string): boolean {\n const p = stripTrailingSlashes(prefix)\n if (p === '') return true\n return path === p || path.startsWith(`${p}/`)\n}\n\n/** Non-empty segments of a path or route pattern. Leading/trailing/duplicate\n * slashes collapse, so `/app//x/` and `app/x` compare equal. */\nexport function toSegments(value: string): string[] {\n return value.split('/').filter((segment) => segment.length > 0)\n}\n\n/** Canonical display form: rooted, no trailing slash, no empty segments. */\nexport function toRootedPath(value: string): string {\n return `/${toSegments(value).join('/')}`\n}\n","/**\n * Nav destinations, and the guard that proves every href the rail renders\n * resolves to a route the product's router actually registered.\n *\n * A rail row's href is assembled from a base plus a relative path, and nothing\n * downstream re-checks it: the sidebar renders a link, the click navigates, and\n * the router answers 404. A unit test written against the nav builder alone\n * cannot catch that — it asserts the href the builder produced, which is the\n * same wrong string the user clicks.\n *\n * Two mechanisms, meant to be used together:\n *\n * 1. `NavDestination` makes the base a REQUIRED discriminant (`scope`). An\n * optional `absolute?: boolean`-style flag has the opposite property:\n * omitting it type-checks, and the destination silently resolves under the\n * workspace prefix instead of the app-level one. A required literal union\n * turns that omission into a compile error, and widening `TScope` demands a\n * base for the new scope rather than defaulting to a wrong one.\n * 2. `assertNavHrefsRegistered` matches every resolved href against the route\n * table, so a destination the router never registered fails a test instead\n * of a user's click. It reads the product's real route table, so it cannot\n * agree with the builder's mistake the way a hand-maintained expected-href\n * list does.\n */\n\nimport { isUnderPrefix, normalizePath, stripTrailingSlashes, toRootedPath, toSegments } from './path'\n\n// ---------------------------------------------------------------------------\n// Destinations — the base is a required discriminant, never an optional flag\n// ---------------------------------------------------------------------------\n\n/** The bases a product routes rail rows under. `workspace` is the per-workspace\n * prefix (`/app/ws_123`); `app` is the account-level one (`/app`), where\n * singleton surfaces such as a shared terminal or billing live. */\nexport type NavScope = 'workspace' | 'app'\n\n/** A base path per scope. Widening `TScope` widens this record, so a product\n * that adds a scope cannot compile until it supplies that scope's base. */\nexport type NavScopeBases<TScope extends string = NavScope> = Readonly<Record<TScope, string>>\n\n/** One rail destination as the product declares it, before a base is applied. */\nexport interface NavDestination<TScope extends string = NavScope> {\n id: string\n /** Path relative to the base named by `scope`. `''` is the base itself.\n * Must be empty or start with `/` — a bare `'vault'` would concatenate into\n * `/app/ws_123vault`, so it is rejected rather than silently repaired. */\n path: string\n /** Which base `path` resolves against. Required on purpose. */\n scope: TScope\n}\n\n/** A destination with its base applied. */\nexport interface ResolvedNavDestination<TScope extends string = NavScope> {\n id: string\n href: string\n scope: TScope\n}\n\n/** Apply a destination's scope base to its path.\n *\n * Throws when the scope has no base configured — a product that assembles\n * `bases` dynamically can defeat the type-level guarantee, and a missing base\n * would otherwise produce `undefined/vault`. */\nexport function resolveNavHref<TScope extends string>(\n destination: NavDestination<TScope>,\n bases: NavScopeBases<TScope>,\n): string {\n const base = bases[destination.scope]\n if (typeof base !== 'string') {\n throw new Error(\n `Nav destination '${destination.id}' uses scope '${destination.scope}', which has no configured base`,\n )\n }\n if (destination.path !== '' && !destination.path.startsWith('/')) {\n throw new Error(\n `Nav destination '${destination.id}' path must be empty or start with '/' (got '${destination.path}')`,\n )\n }\n const rooted = `${stripTrailingSlashes(base)}${destination.path}`\n return rooted === '' ? '/' : stripTrailingSlashes(rooted)\n}\n\n/** Apply the bases to every destination, preserving declaration order. */\nexport function resolveNavDestinations<TScope extends string>(\n destinations: readonly NavDestination<TScope>[],\n bases: NavScopeBases<TScope>,\n): ResolvedNavDestination<TScope>[] {\n return destinations.map((destination) => ({\n id: destination.id,\n href: resolveNavHref(destination, bases),\n scope: destination.scope,\n }))\n}\n\nexport interface ResolveScopedActiveNavIdOptions<TScope extends string = NavScope> {\n pathname: string\n destinations: readonly NavDestination<TScope>[]\n bases: NavScopeBases<TScope>\n /** Extra ABSOLUTE prefixes that light an existing row, e.g.\n * `{ '/app/ws_1/agents': 'integrations' }`. Same longest-prefix contest. */\n aliases?: Readonly<Record<string, string>>\n /** ABSOLUTE prefixes that deliberately highlight nothing, beating any shorter\n * match. */\n claimsNothing?: readonly string[]\n}\n\n/**\n * The rail row to highlight, across scopes.\n *\n * `resolveActiveNavId` resolves rows against ONE base, so an app-level row can\n * only be highlighted by a second, hand-rolled scan — the same split that lets\n * an app-level destination render under the workspace base. This resolves the\n * hrefs first and runs a single longest-prefix contest over absolute paths, so\n * declaration order cannot change the answer and no scope needs its own pass.\n *\n * Prefixes in `aliases` / `claimsNothing` are absolute here, unlike\n * `resolveActiveNavId`'s base-relative ones, because the contest itself is\n * absolute.\n */\nexport function resolveScopedActiveNavId<TScope extends string>({\n pathname,\n destinations,\n bases,\n aliases,\n claimsNothing,\n}: ResolveScopedActiveNavIdOptions<TScope>): string | undefined {\n const path = normalizePath(pathname)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (candidate: string, id: string | undefined, winsTies = false): void => {\n const full = stripTrailingSlashes(candidate)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const resolved of resolveNavDestinations(destinations, bases)) consider(resolved.href, resolved.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix here is a\n // deliberate override of the row that owns it.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Route table — structurally the product's own router config\n// ---------------------------------------------------------------------------\n\n/**\n * One entry of a registered route table. Structurally compatible with\n * react-router's `RouteConfigEntry`, so a product passes its real `routes.ts`\n * default export straight in — the point of the guard is that it reads the\n * router's own truth rather than a second list that can agree with the bug.\n */\nexport interface RegisteredRoute {\n /** Absent on a pathless layout route: its children inherit the parent path. */\n path?: string\n index?: boolean\n children?: readonly RegisteredRoute[]\n}\n\n/** A route table entry is either a bare pattern string or a router config node. */\nexport type NavRouteTable = readonly (string | RegisteredRoute)[]\n\nfunction joinPattern(parent: string, child: string): string {\n if (child.startsWith('/')) return child\n if (child === '') return parent\n return `${parent}/${child}`\n}\n\n/**\n * Every path pattern the table registers, rooted and de-duplicated.\n *\n * Parent nodes contribute their own cumulative path as well as their children's:\n * a router matches a parent route with an index child at the parent path, and a\n * parent without one still matches with an empty outlet, so treating parents as\n * unregistered would flag working hrefs.\n */\nexport function flattenRouteTable(table: NavRouteTable): string[] {\n const patterns: string[] = []\n const walk = (entries: NavRouteTable, parent: string): void => {\n for (const entry of entries) {\n if (typeof entry === 'string') {\n patterns.push(toRootedPath(joinPattern(parent, entry)))\n continue\n }\n const own = entry.path === undefined ? parent : joinPattern(parent, entry.path)\n patterns.push(toRootedPath(own))\n if (entry.children) walk(entry.children, own)\n }\n }\n walk(table, '')\n return [...new Set(patterns)]\n}\n\n/**\n * Whole-path segment match of a concrete path against one route pattern.\n *\n * Supports the three pattern forms a router uses: literal segments, `:param`\n * (exactly one non-empty segment), optional `:param?` / `segment?` (zero or\n * one), and a trailing `*` splat (zero or more). Matching is recursive because\n * an optional segment forks the walk — a linear scan silently mismatches\n * `/a/b` against `a/:x?/b`.\n */\nfunction matchesPattern(pathSegments: readonly string[], patternSegments: readonly string[], caseSensitive: boolean): boolean {\n if (patternSegments.length === 0) return pathSegments.length === 0\n const head = patternSegments[0] ?? ''\n if (head === '*') return true\n const rest = patternSegments.slice(1)\n const optional = head.endsWith('?')\n const core = optional ? head.slice(0, -1) : head\n const first = pathSegments[0]\n if (first !== undefined) {\n const hit = core.startsWith(':')\n ? first.length > 0\n : caseSensitive\n ? core === first\n : core.toLowerCase() === first.toLowerCase()\n if (hit && matchesPattern(pathSegments.slice(1), rest, caseSensitive)) return true\n }\n return optional ? matchesPattern(pathSegments, rest, caseSensitive) : false\n}\n\n// ---------------------------------------------------------------------------\n// The guard\n// ---------------------------------------------------------------------------\n\n/**\n * A nav row as the guard needs to see it. Structurally satisfied by\n * `SessionRailNavItem` / `SessionRailSubItem` and by sandbox-ui's\n * `SidebarLayoutNavItem`, so the guard runs over the builder's real output\n * rather than a re-declaration of it.\n */\nexport interface NavHrefItem {\n id: string\n href: string\n subItems?: readonly NavHrefItem[]\n}\n\nexport type NavHrefProblemReason =\n /** No registered pattern matches the resolved href. */\n | 'unregistered'\n /** Empty, fragment-only, or not rooted at `/` — the row navigates nowhere\n * predictable regardless of the route table. */\n | 'not-a-path'\n /** Leaves the router (scheme or protocol-relative) while `allowExternal` is\n * off. */\n | 'external'\n\nexport interface NavHrefProblem {\n id: string\n href: string\n reason: NavHrefProblemReason\n /** Registered patterns ending in the same segment. A destination resolved\n * under the wrong base lands here as its correctly-based twin, which is what\n * names the missing scope in the failure message. */\n nearest: string[]\n message: string\n}\n\nexport interface NavHrefReport {\n /** Hrefs examined, including nested sub-items. */\n checked: number\n problems: NavHrefProblem[]\n /** Off-router destinations accepted because `allowExternal` is on. */\n external: string[]\n /** The flattened route table the check ran against. */\n patterns: string[]\n}\n\nexport interface NavHrefCheckOptions {\n /** Hrefs to skip, compared after query/fragment removal. For a destination\n * served outside this route table (a static asset, another worker). */\n ignore?: readonly string[]\n /** Absolute URLs / `mailto:` / `tel:` are reported under `external` instead\n * of failing. Default true. */\n allowExternal?: boolean\n /** Compare literal segments case-sensitively. Default true — a router that\n * matches case-insensitively still renders a link the deploy's CDN or a\n * case-sensitive origin may not. */\n caseSensitive?: boolean\n}\n\n/** `scheme:` or `//host` — anything the router will not resolve as a path. */\nconst OFF_ROUTER_HREF = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i\n\nfunction flattenItems(items: readonly NavHrefItem[], out: NavHrefItem[] = []): NavHrefItem[] {\n for (const item of items) {\n out.push(item)\n if (item.subItems) flattenItems(item.subItems, out)\n }\n return out\n}\n\n/**\n * Check every nav href against the product's route table.\n *\n * Pure — returns the full report so a caller can assert on parts of it. Use\n * {@link assertNavHrefsRegistered} in tests; it turns the report into a failure\n * that names the offending row, its resolved href, and the near-miss pattern.\n */\nexport function checkNavHrefs(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): NavHrefReport {\n const { ignore, allowExternal = true, caseSensitive = true } = options\n const patterns = flattenRouteTable(routes)\n const patternSegments = patterns.map((pattern) => ({ pattern, segments: toSegments(pattern) }))\n const ignored = new Set((ignore ?? []).map((href) => normalizePath(href)))\n const problems: NavHrefProblem[] = []\n const external: string[] = []\n const flat = flattenItems(items)\n let checked = 0\n\n for (const item of flat) {\n const raw = item.href\n const path = normalizePath(raw)\n if (ignored.has(path)) continue\n if (OFF_ROUTER_HREF.test(raw)) {\n if (allowExternal) {\n external.push(raw)\n continue\n }\n // Counted as checked: it was examined and rejected, so the vacuous-pass\n // guard must not read this run as \"nothing was looked at\".\n checked += 1\n problems.push({\n id: item.id,\n href: raw,\n reason: 'external',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' leaves the router, and external destinations are rejected`,\n })\n continue\n }\n checked += 1\n if (raw === '' || raw.startsWith('#') || !raw.startsWith('/')) {\n problems.push({\n id: item.id,\n href: raw,\n reason: 'not-a-path',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' is not a rooted path — it cannot resolve to a registered route`,\n })\n continue\n }\n const segments = toSegments(path)\n if (patternSegments.some((candidate) => matchesPattern(segments, candidate.segments, caseSensitive))) continue\n const nearest = nearestPatterns(segments, patternSegments.map((candidate) => candidate.pattern), caseSensitive)\n problems.push({\n id: item.id,\n href: raw,\n reason: 'unregistered',\n nearest,\n message:\n `Nav item '${item.id}' href '${raw}' matches no registered route` +\n (nearest.length ? ` — nearest registered: ${nearest.join(', ')}` : ''),\n })\n }\n\n return { checked, problems, external, patterns }\n}\n\n/** Registered patterns whose last segment equals the href's last segment: the\n * same destination under a different base is the near-miss worth printing. */\nfunction nearestPatterns(segments: readonly string[], patterns: readonly string[], caseSensitive: boolean): string[] {\n const tail = segments[segments.length - 1]\n if (tail === undefined) return []\n const same = (a: string, b: string): boolean => (caseSensitive ? a === b : a.toLowerCase() === b.toLowerCase())\n return patterns\n .filter((pattern) => {\n const patternTail = toSegments(pattern).at(-1)\n return patternTail !== undefined && same(patternTail, tail)\n })\n .slice(0, 5)\n}\n\n/**\n * Fail unless every nav href resolves to a registered route.\n *\n * Throws on an empty item list or an empty route table as well: a guard that\n * examined nothing reports safety it does not provide, and both are what a\n * mis-wired import looks like.\n */\nexport function assertNavHrefsRegistered(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): void {\n if (items.length === 0) {\n throw new Error('assertNavHrefsRegistered received no nav items — the check would pass without examining anything')\n }\n const report = checkNavHrefs(items, routes, options)\n if (report.patterns.length === 0) {\n throw new Error('assertNavHrefsRegistered received an empty route table — every href would fail or nothing would be proven')\n }\n // Real problems are reported before the vacuous-pass guard: rejected external\n // hrefs are problems that were never \"checked\", and the guard's message would\n // otherwise hide them.\n if (report.problems.length > 0) {\n const detail = report.problems.map((problem) => ` - ${problem.message}`).join('\\n')\n throw new Error(\n `${report.problems.length} of ${report.checked} nav hrefs do not resolve to a registered route:\\n${detail}\\n` +\n `Registered patterns (${report.patterns.length}): ${report.patterns.join(', ')}`,\n )\n }\n if (report.checked === 0) {\n throw new Error(\n `assertNavHrefsRegistered examined 0 hrefs (${report.external.length} external, ${ignoredCount(items, options)} ignored) — the check would pass without examining anything`,\n )\n }\n}\n\nfunction ignoredCount(items: readonly NavHrefItem[], options: NavHrefCheckOptions): number {\n const ignored = new Set((options.ignore ?? []).map((href) => normalizePath(href)))\n return flattenItems(items).filter((item) => ignored.has(normalizePath(item.href))).length\n}\n","/**\n * Command palette — the React-free selection half of the Cmd/Ctrl+K surface\n * (`/web-react` holds the rendered half, `CommandPalette`).\n *\n * Pure and import-free beyond this module's own types: no React, no DOM, no\n * fuse.js. A route loader or a worker can build and rank the same items the\n * browser renders.\n *\n * Domain stays a parameter. The palette knows two kinds of row — a SESSION the\n * user can jump to and an ACTION the product offers (new chat, toggle theme,\n * open settings) — and both arrive as data. What a selection DOES is the\n * product's business; the shell only builds, ranks, and groups.\n *\n * Ranking is the documented ladder, not a fuzzy library: exact > prefix >\n * word-prefix > substring (earlier index wins) > token-order, with keyword\n * hits ranked a fixed step below the same hit on the label. Deterministic —\n * no index-building, no async, same input always sorts the same way.\n */\n\nimport { sessionLabel, UNTITLED_SESSION_LABEL, type SessionSummary } from './index'\n\n/** A product-supplied palette action. `hint` is the right-aligned affordance\n * copy (a kbd chord, a route name) — rendered verbatim, never interpreted. */\nexport interface CommandPaletteAction {\n id: string\n label: string\n description?: string\n hint?: string\n /** Extra match vocabulary that never renders (`settings` matching\n * \"preferences\"). A keyword hit ranks below the same hit on the label. */\n keywords?: string[]\n}\n\n/** One selectable row. `group` is the section header it renders under. */\nexport interface CommandPaletteItem {\n id: string\n group: string\n label: string\n description?: string\n hint?: string\n keywords?: string[]\n /** Recency key (ISO-8601). Breaks score ties and orders the unfiltered\n * list recent-first. Rows without one sort below rows with one. */\n recentAt?: string | null\n}\n\n/** One rendered section: a header plus its rows, in first-seen group order. */\nexport interface CommandPaletteGroup {\n group: string\n items: CommandPaletteItem[]\n}\n\nexport const COMMAND_PALETTE_SESSIONS_GROUP = 'Sessions'\nexport const COMMAND_PALETTE_ACTIONS_GROUP = 'Actions'\n\nexport interface BuildCommandPaletteItemsOptions {\n sessions?: readonly SessionSummary[]\n actions?: readonly CommandPaletteAction[]\n /** Section label for sessions. Default \"Sessions\". */\n sessionsLabel?: string\n /** Section label for actions. Default \"Actions\". */\n actionsLabel?: string\n /** Placeholder title for an untitled session. */\n untitledLabel?: string\n}\n\n/**\n * Flatten sessions + actions into palette items, sessions group first (the\n * jump-back-in list), actions after. Sessions order recent-first by\n * `updatedAt` — a palette with an empty query IS the recency list, so the\n * build order is the render order and the filter never has to re-derive it.\n * Pinned sessions lead the recency sort, matching the rail.\n */\nexport function buildCommandPaletteItems({\n sessions = [],\n actions = [],\n sessionsLabel = COMMAND_PALETTE_SESSIONS_GROUP,\n actionsLabel = COMMAND_PALETTE_ACTIONS_GROUP,\n untitledLabel = UNTITLED_SESSION_LABEL,\n}: BuildCommandPaletteItemsOptions): CommandPaletteItem[] {\n const ordered = [...sessions].sort((a, b) => {\n if (!!a.isPinned !== !!b.isPinned) return a.isPinned ? -1 : 1\n return compareRecent(a.updatedAt, b.updatedAt)\n })\n const sessionItems: CommandPaletteItem[] = ordered.map((session) => ({\n id: session.id,\n group: sessionsLabel,\n label: sessionLabel(session, untitledLabel),\n keywords: session.category ? [session.category] : undefined,\n recentAt: session.updatedAt,\n }))\n const actionItems: CommandPaletteItem[] = actions.map((action) => ({\n id: action.id,\n group: actionsLabel,\n label: action.label,\n description: action.description,\n hint: action.hint,\n keywords: action.keywords,\n }))\n return [...sessionItems, ...actionItems]\n}\n\n/** Newer first; an undated row sorts below every dated one. ISO strings\n * compare lexicographically. */\nfunction compareRecent(a: string | null | undefined, b: string | null | undefined): number {\n if (a && b) return a < b ? 1 : a > b ? -1 : 0\n if (a) return -1\n if (b) return 1\n return 0\n}\n\n/** Collapse whitespace, lowercase once — every comparison runs on this form. */\nfunction normalize(text: string): string {\n return text.trim().toLowerCase().replace(/\\s+/g, ' ')\n}\n\n/** Words of a normalized string: runs of letters/numbers, so \"new-chat\" and\n * \"new chat\" word-prefix identically. */\nconst WORD_SPLIT = /[^\\p{L}\\p{N}]+/u\n\nfunction wordsOf(text: string): string[] {\n return text.split(WORD_SPLIT).filter(Boolean)\n}\n\n/** How far below a label hit the same keyword hit ranks: any label match, even\n * a token-order one (40), outranks a keyword exact match (100 − 65 = 35). */\nconst KEYWORD_PENALTY = 65\n\n/**\n * Score one text against the query on the prefix > substring > token-order\n * ladder. Returns `null` for no match. Higher is better; tiers are spaced so\n * no within-tier adjustment can cross a tier boundary:\n *\n * - 100 exact\n * - 90 prefix (`text` starts with the query)\n * - 80 word-prefix (a WORD starts with the query — \"chat\" hits \"New chat\")\n * - 60–79 substring, minus the match index clamped to 19 (earlier wins)\n * - 40 token-order (every query token matches a later word, in order)\n */\nfunction scoreText(text: string, query: string): number | null {\n if (!query) return 0\n if (text === query) return 100\n if (text.startsWith(query)) return 90\n const words = wordsOf(text)\n if (words.some((word) => word.startsWith(query))) return 80\n const at = text.indexOf(query)\n if (at >= 0) return 60 + Math.max(0, 19 - at)\n const tokens = wordsOf(query)\n if (tokens.length > 1) {\n let atWord = 0\n const inOrder = tokens.every((token) => {\n while (atWord < words.length) {\n const word = words[atWord]\n atWord += 1\n // Guarded by the while condition; noUncheckedIndexedAccess can't see it.\n if (word !== undefined && (word.startsWith(token) || word.includes(token))) return true\n }\n return false\n })\n if (inOrder) return 40\n }\n return null\n}\n\n/**\n * Score an item: the best label score, or the best keyword score a fixed step\n * below. `null` when neither matches — the item is filtered out. An empty\n * query scores every item 0 (the caller keeps build order: recent-first).\n */\nexport function scoreCommandPaletteItem(item: CommandPaletteItem, query: string): number | null {\n const q = normalize(query)\n const label = scoreText(normalize(item.label), q)\n let best = label\n for (const keyword of item.keywords ?? []) {\n const score = scoreText(normalize(keyword), q)\n if (score !== null) {\n const penalized = score - KEYWORD_PENALTY\n if (best === null || penalized > best) best = penalized\n }\n }\n return best\n}\n\n/**\n * Filter + rank: an empty query returns the items untouched (build order is\n * the recency order); a real query drops non-matches and sorts by score, then\n * recency, then original position — stable and deterministic.\n */\nexport function filterCommandPaletteItems(\n items: readonly CommandPaletteItem[],\n query: string,\n): CommandPaletteItem[] {\n if (!normalize(query)) return [...items]\n const scored: Array<{ item: CommandPaletteItem; score: number; index: number }> = []\n items.forEach((item, index) => {\n const score = scoreCommandPaletteItem(item, query)\n if (score !== null) scored.push({ item, score, index })\n })\n scored.sort((a, b) => {\n if (a.score !== b.score) return b.score - a.score\n const recent = compareRecent(a.item.recentAt, b.item.recentAt)\n if (recent !== 0) return recent\n return a.index - b.index\n })\n return scored.map(({ item }) => item)\n}\n\n/**\n * Fold a flat (already ordered) item list into renderable sections. Groups\n * appear in first-seen order and each group appears ONCE — a filtered ranking\n * interleaves sessions and actions by score, and folding only consecutive runs\n * would render the same header twice. Within a group, rows keep the flat\n * order. Empty groups vanish, so a filter that leaves only actions renders no\n * \"Sessions\" header over nothing.\n */\nexport function groupCommandPaletteItems(items: readonly CommandPaletteItem[]): CommandPaletteGroup[] {\n const groups: CommandPaletteGroup[] = []\n const byGroup = new Map<string, CommandPaletteGroup>()\n for (const item of items) {\n let group = byGroup.get(item.group)\n if (!group) {\n group = { group: item.group, items: [] }\n byGroup.set(item.group, group)\n groups.push(group)\n }\n group.items.push(item)\n }\n return groups\n}\n","/**\n * Session shell — the app-shell mechanism every agent product needs around the\n * chat surface: a list of past sessions in the rail, an entry point for a new\n * one, and a paged history view behind it.\n *\n * `/web-react` already owns the chat SURFACE (composer, transcript, cards); it\n * owned no session SHELL, so all four products hand-rolled one and drifted.\n * This module is the shell's pure half: no React, no DOM, no peer imports, so a\n * server loader can call `readRailCollapsedCookie` without dragging React into\n * a worker bundle (`/web-react` holds the rendered half).\n *\n * Domain stays a parameter. A \"session\" here is only an id, a title and a\n * timestamp — a gtm thread, a tax session and a legal matter are all the same\n * shape to the shell, and the product supplies routing through `hrefForSession`\n * rather than the shell knowing any URL.\n */\n\nimport { isUnderPrefix, normalizePath, stripSlashes, stripTrailingSlashes } from './path'\n\nexport * from './nav-guard'\nexport * from './command-palette'\n\n/** One session as the shell needs to see it. Products map their own row\n * (thread / session / matter) onto this before handing it over. */\nexport interface SessionSummary {\n id: string\n /** `null`/empty renders as the untitled placeholder rather than a blank row. */\n title: string | null\n /** ISO-8601. `null` when the product has no timestamp to show. */\n updatedAt: string | null\n isPinned?: boolean\n /** Unread for the viewer. Use `resolveSessionUnread` to fold live overlays in. */\n unread?: boolean\n /** Free-form product label (gtm categories, legal matter types). Passed\n * through untouched — the shell never interprets it. */\n category?: string | null\n}\n\n/** One fetched page of sessions with an optional continuation cursor. */\nexport interface SessionPage {\n items: SessionSummary[]\n /** Opaque continuation token; absent/null ⇒ no further pages. */\n nextCursor?: string | null\n}\n\n/** Sort order for the history view. The product's fetcher decides what these\n * mean against its own storage; the shell only round-trips the value. */\nexport type SessionSort = 'newest' | 'oldest'\n\n// ---------------------------------------------------------------------------\n// Rail items — structurally assignable to sandbox-ui's SidebarLayout types\n// ---------------------------------------------------------------------------\n\n/**\n * These mirror `@tangle-network/sandbox-ui/dashboard`'s `SidebarLayoutNavItem`\n * / `RailExpandableSubItem` STRUCTURALLY rather than importing them, so this\n * module stays free of the optional peer (invariant 3 — structural over\n * hard-dep when the surface is small). `tests/session-shell/rail-contract.test.ts`\n * assigns the builder output to the real sandbox-ui types, so a drift in either\n * direction fails CI instead of silently dropping a field at runtime.\n *\n * `TIcon` is the product's icon component type (lucide, custom, anything) —\n * generic so this file needs no React types.\n */\nexport interface SessionRailAction<TIcon = unknown> {\n id: string\n label: string\n icon?: TIcon\n destructive?: boolean\n onSelect: () => void\n}\n\nexport type RailPrefetch = 'none' | 'intent' | 'render' | 'viewport'\n\nexport interface SessionRailSubItem<TIcon = unknown> {\n id: string\n label: string\n href: string\n prefetch?: RailPrefetch\n /** Live working indicator — the session is mid-turn. */\n isLoading?: boolean\n /** Bold + leading dot. sandbox-ui suppresses it while `isLoading`. */\n unread?: boolean\n /** Emphasised row, used for the trailing \"view all\" overflow link. */\n emphasis?: boolean\n actions?: SessionRailAction<TIcon>[]\n}\n\nexport interface SessionRailNavItem<TIcon = unknown> {\n id: string\n /** REQUIRED, mirroring sandbox-ui — the rail renders `<Icon />` unguarded, so\n * an omitted icon is a blank/crashing row rather than a styling nit. */\n icon: TIcon\n label: string\n href: string\n badge?: number\n expandable?: boolean\n defaultOpen?: boolean\n subItems?: SessionRailSubItem<TIcon>[]\n subActiveIds?: string[]\n emptyLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Per-row rename/delete wiring. Supplied by the layout that owns the dialogs;\n * omitted (or `canEdit: false`) leaves rows read-only. */\nexport interface SessionRowActions<TIcon = unknown> {\n canEdit: boolean\n renameIcon?: TIcon\n deleteIcon?: TIcon\n renameLabel?: string\n deleteLabel?: string\n /**\n * Omit when the product cannot rename a session — the row then offers delete\n * only, instead of a menu item that does nothing.\n *\n * Independently optional, matching `SessionHistoryPanel`, which has always\n * rendered whichever of the two it was given. The rail builder used to demand\n * both, so a product with archive-but-no-rename (tax) could either fake a\n * rename or ship no row actions at all.\n */\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /**\n * Row actions this shell has no opinion about — pin, categorise, duplicate,\n * share. Evaluated per session so a label can read that row's state\n * (\"Pin\" vs \"Unpin\"), and ordered between rename and delete so the\n * destructive action stays last.\n *\n * `id` must not be `rename` or `delete`; those are the shell's own.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction<TIcon>[]\n}\n\nexport const UNTITLED_SESSION_LABEL = 'Untitled chat'\n\n/** Display title for a session row — trims, and falls back rather than\n * rendering an empty row the user cannot aim at. */\nexport function sessionLabel(session: SessionSummary, untitled = UNTITLED_SESSION_LABEL): string {\n return session.title?.trim() || untitled\n}\n\nexport interface BuildSessionSubItemsOptions<TIcon = unknown> {\n sessions: SessionSummary[]\n /** The product's route for one session. The shell never builds a URL itself. */\n hrefForSession: (sessionId: string) => string\n /** Ids currently mid-turn — renders the working indicator. */\n respondingSessionIds?: ReadonlySet<string>\n actions?: SessionRowActions<TIcon>\n untitledLabel?: string\n prefetch?: RailPrefetch\n /** Trailing \"view all\" row, appended when the capped list hides sessions. */\n overflow?: { href: string; label?: string }\n}\n\n/** Session rows for the rail's expandable history item. */\nexport function buildSessionSubItems<TIcon = unknown>({\n sessions,\n hrefForSession,\n respondingSessionIds,\n actions,\n untitledLabel = UNTITLED_SESSION_LABEL,\n prefetch = 'intent',\n overflow,\n}: BuildSessionSubItemsOptions<TIcon>): SessionRailSubItem<TIcon>[] {\n /**\n * Only the handlers the product actually supplied. An empty result becomes\n * `undefined` rather than `[]`, because sandbox-ui renders the kebab trigger\n * whenever `actions` is an array — an empty one is a button that opens an\n * empty menu.\n */\n const rowActions = (session: SessionSummary): SessionRailAction<TIcon>[] | undefined => {\n if (!actions?.canEdit) return undefined\n const built: SessionRailAction<TIcon>[] = []\n const { onRename, onDelete, extraActions } = actions\n if (onRename) {\n built.push({\n id: 'rename',\n label: actions.renameLabel ?? 'Rename',\n icon: actions.renameIcon,\n onSelect: () => onRename(session),\n })\n }\n if (extraActions) built.push(...extraActions(session))\n if (onDelete) {\n built.push({\n id: 'delete',\n label: actions.deleteLabel ?? 'Delete',\n icon: actions.deleteIcon,\n destructive: true,\n onSelect: () => onDelete(session),\n })\n }\n return built.length ? built : undefined\n }\n\n const rows: SessionRailSubItem<TIcon>[] = sessions.map((session) => ({\n id: session.id,\n label: sessionLabel(session, untitledLabel),\n href: hrefForSession(session.id),\n prefetch,\n isLoading: respondingSessionIds?.has(session.id) ?? false,\n unread: Boolean(session.unread),\n actions: rowActions(session),\n }))\n if (!overflow) return rows\n return [\n ...rows,\n {\n id: 'view-all',\n label: overflow.label ?? 'View all chats',\n href: overflow.href,\n prefetch,\n emphasis: true,\n },\n ]\n}\n\nexport interface BuildSessionNavItemOptions<TIcon = unknown>\n extends BuildSessionSubItemsOptions<TIcon> {\n /** Nav id the product highlights against (`activeNavId === id`). */\n id?: string\n label?: string\n /** The product's icon component. Required — see `SessionRailNavItem.icon`. */\n icon: TIcon\n /** The expandable row's own destination — the full history page. */\n href: string\n /** Session currently open, highlighted inside the expandable. */\n activeSessionId?: string | null\n emptyLabel?: string\n defaultOpen?: boolean\n}\n\n/**\n * The rail's session entry: one expandable nav row whose sub-items are the\n * recent sessions. This is the structure the owner asked for — history lives IN\n * the rail, not in a second sidebar panel beside it.\n */\nexport function buildSessionNavItem<TIcon = unknown>({\n id = 'history',\n label = 'History',\n icon,\n href,\n activeSessionId,\n emptyLabel = 'No chats yet',\n defaultOpen = true,\n ...subItemOptions\n}: BuildSessionNavItemOptions<TIcon>): SessionRailNavItem<TIcon> {\n return {\n id,\n icon,\n label,\n href,\n expandable: true,\n defaultOpen,\n subItems: buildSessionSubItems<TIcon>(subItemOptions),\n subActiveIds: activeSessionId ? [activeSessionId] : undefined,\n emptyLabel,\n prefetch: subItemOptions.prefetch ?? 'intent',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Routing / selection\n// ---------------------------------------------------------------------------\n\nexport interface ActiveSessionIdOptions {\n pathname: string\n /** Workspace-scoped route base, e.g. `/app/ws_123`. */\n base: string\n /** Route segment sessions live under. Default `chat` ⇒ `${base}/chat/:id`.\n * Pass `''` when sessions sit DIRECTLY under the base (`/app/:sessionId`),\n * which is how one product routes them — then `reserved` is mandatory. */\n segment?: string\n /** Segment that means \"composing a new session\", not an id. Default `new`. */\n newSegment?: string\n /**\n * First segments that are OTHER routes, not session ids. Only meaningful\n * with `segment: ''`, where `/app/settings` is otherwise indistinguishable\n * from a session called `settings` — and resolving it as one would highlight\n * and prefetch a session that does not exist. Pass the product's own nav\n * paths; unknown-but-reserved is a routing bug, so this fails closed.\n */\n reserved?: readonly string[]\n}\n\n/**\n * The session id the current route has open, or `null` on the new-session\n * composer / anywhere else.\n *\n * Anchored at `base` on purpose. A bare `/\\/chat\\/([^/]+)/` scan — the shape\n * three products shipped — matches the FIRST `/chat/` anywhere in the path, so\n * a workspace or vault folder named `chat` resolves a neighbouring segment as a\n * session id and the rail highlights (and prefetches) a session the user is not\n * in. Same class as attaching to a stale box: it looks right and points at the\n * wrong row.\n */\nexport function activeSessionIdFromPath({\n pathname,\n base,\n segment = 'chat',\n newSegment = 'new',\n reserved,\n}: ActiveSessionIdOptions): string | null {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n const prefix = segment ? `${root}/${segment}` : root\n if (!isUnderPrefix(path, prefix) || path === prefix) return null\n const id = path.slice(prefix.length + 1).split('/')[0] ?? ''\n if (!id || id === newSegment) return null\n // `/app/settings` under a segment-less route is a sibling page, not a\n // session named \"settings\".\n if (reserved?.some((name) => stripSlashes(name) === id)) return null\n try {\n return decodeURIComponent(id)\n } catch {\n // A malformed route is not a session id. Fail closed so a bad URL cannot\n // take down the shell while it resolves the active row.\n return null\n }\n}\n\n/** One rail destination. `path` is relative to the workspace base. */\nexport interface NavRouteDef {\n id: string\n path: string\n}\n\nexport interface ResolveActiveNavIdOptions {\n pathname: string\n base: string\n /** The product's rail rows, in any order — resolution is longest-prefix. */\n routes: NavRouteDef[]\n /** Extra prefixes that light an existing row: `{ '/agents': 'integrations' }`.\n * Participates in the same longest-prefix contest. */\n aliases?: Record<string, string>\n /** Prefixes that deliberately highlight NOTHING, beating any shorter match.\n * gtm uses this so an open chat lights no rail row while `/chat/new` still\n * lights \"New\". */\n claimsNothing?: string[]\n}\n\n/**\n * The rail row to highlight for the current route.\n *\n * Longest-prefix wins, so declaration order cannot change the answer. The\n * per-product versions this replaces were first-match over an array, which made\n * `/chat/new` vs `/chat` an ordering accident rather than a rule.\n */\nexport function resolveActiveNavId({\n pathname,\n base,\n routes,\n aliases,\n claimsNothing,\n}: ResolveActiveNavIdOptions): string | undefined {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (relative: string, id: string | undefined, winsTies = false) => {\n const full = stripTrailingSlashes(`${root}${relative}`)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const route of routes) consider(route.path, route.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix in\n // `claimsNothing` is a deliberate override of the row that owns it, so\n // `claimsNothing: ['/chat']` beats a `{ id: 'chat', path: '/chat' }` row while\n // a longer `/chat/new` still wins on specificity.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Sidebar list composition\n// ---------------------------------------------------------------------------\n\nexport interface ResolveSessionUnreadOptions {\n sessionId: string\n /** Server-computed unread from the route loader. */\n loaderUnread: boolean\n /** Live \"went unread\" ids from the workspace channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has already opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** The open session is never unread to its own viewer. */\n currentSessionId?: string | null\n}\n\n/**\n * Effective unread for one row. The loader's value can be stale — a layout\n * loader that survives same-workspace navigation keeps reporting a session as\n * unread after the user opened it — so live and local overlays win over it, and\n * the currently-open session always reads as read.\n */\nexport function resolveSessionUnread({\n sessionId,\n loaderUnread,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ResolveSessionUnreadOptions): boolean {\n if (sessionId === currentSessionId) return false\n if (liveUnreadIds?.has(sessionId)) return true\n if (locallyReadIds?.has(sessionId)) return false\n return loaderUnread\n}\n\nexport interface ComposeSidebarSessionsOptions {\n /** Server-rendered rows, already ordered by the product's query. */\n loaderSessions: SessionSummary[]\n /** Optimistic rows from the live channel (a chat created in another tab). */\n optimisticSessions?: SessionSummary[]\n /** Rail cap. The full list lives on the history page. */\n limit: number\n /** Total sessions the product holds, used to decide the overflow row. */\n totalCount?: number\n liveUnreadIds?: ReadonlySet<string>\n locallyReadIds?: ReadonlySet<string>\n currentSessionId?: string | null\n}\n\nexport interface ComposedSidebarSessions {\n sessions: SessionSummary[]\n /** More sessions exist than the rail shows ⇒ render the \"view all\" row. */\n hasMore: boolean\n}\n\n/**\n * The rail's session list: optimistic rows first, then the loader's, capped,\n * with unread resolved per row.\n *\n * Optimistic rows are deduped against the loader by id — once a revalidation\n * brings a live-created session back from the server it must not appear twice\n * (duplicate React keys, and the row's actions would target the same session\n * from two places).\n */\nexport function composeSidebarSessions({\n loaderSessions,\n optimisticSessions = [],\n limit,\n totalCount,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ComposeSidebarSessionsOptions): ComposedSidebarSessions {\n const loaderIds = new Set(loaderSessions.map((session) => session.id))\n const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id))\n const merged = [...pendingNew, ...loaderSessions]\n const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({\n ...session,\n unread: resolveSessionUnread({\n sessionId: session.id,\n loaderUnread: Boolean(session.unread),\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n }),\n }))\n const known = (totalCount ?? loaderSessions.length) + pendingNew.length\n return { sessions, hasMore: known > sessions.length }\n}\n\n/**\n * Append a fetched page to held rows, dropping ids already shown. A session\n * bumped to the top between two page fetches otherwise arrives twice — once in\n * the page it moved out of and once in the page it moved into.\n */\nexport function mergeSessionPages(\n existing: SessionSummary[],\n incoming: SessionSummary[],\n): SessionSummary[] {\n const seen = new Set(existing.map((session) => session.id))\n return [...existing, ...incoming.filter((session) => !seen.has(session.id))]\n}\n\n// ---------------------------------------------------------------------------\n// Rail collapse cookie (SSR-seeded so the first paint matches the client)\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_RAIL_COOKIE_NAME = 'agent-sidebar-rail-collapsed'\n\n/**\n * Read the persisted rail-collapse state from a request's `Cookie` header, so\n * the server renders the rail in the state the user left it and the first\n * client render does not re-flow.\n *\n * Parses the header rather than building a `RegExp` from the cookie name (the\n * shape the products shipped): a name containing a regex metacharacter would\n * silently match the wrong cookie or none at all.\n */\nexport function readRailCollapsedCookie(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_RAIL_COOKIE_NAME,\n): boolean {\n for (const pair of (cookieHeader ?? '').split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n return pair.slice(eq + 1).trim() === '1'\n }\n return false\n}\n\nexport interface RailCookieOptions {\n name?: string\n /** Seconds. Default one year. */\n maxAge?: number\n path?: string\n /** Omit to auto-detect: `secure` on https, off on http://localhost — a Secure\n * cookie is dropped there and the rail state would not persist in dev. */\n secure?: boolean\n}\n\n/** The cookie string for a collapse state. Usable as `document.cookie` or as a\n * `Set-Cookie` value. Exported separately so it is testable without a DOM. */\nexport function railCollapsedCookie(\n collapsed: boolean,\n { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31_536_000, path = '/', secure }: RailCookieOptions = {},\n): string {\n const isSecure =\n secure ?? (typeof location !== 'undefined' && location.protocol === 'https:')\n return `${name}=${collapsed ? '1' : '0'}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? '; secure' : ''}`\n}\n\n/** Persist the rail-collapse state from the browser. No-op without a document\n * so a shared toggle handler is safe to call during SSR. */\nexport function writeRailCollapsedCookie(collapsed: boolean, options: RailCookieOptions = {}): void {\n if (typeof document === 'undefined') return\n document.cookie = railCollapsedCookie(collapsed, options)\n}\n"],"mappings":";AAMO,SAAS,qBAAqB,OAAuB;AAC1D,SAAO,MAAM,QAAQ,QAAQ,EAAE;AACjC;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAIO,SAAS,cAAc,UAA0B;AACtD,QAAM,cAAc,SAAS,MAAM,GAAG,EAAE,CAAC,KAAK;AAC9C,QAAM,eAAe,YAAY,MAAM,GAAG,EAAE,CAAC,KAAK;AAClD,SAAO,qBAAqB,YAAY;AAC1C;AAIO,SAAS,cAAc,MAAc,QAAyB;AACnE,QAAM,IAAI,qBAAqB,MAAM;AACrC,MAAI,MAAM,GAAI,QAAO;AACrB,SAAO,SAAS,KAAK,KAAK,WAAW,GAAG,CAAC,GAAG;AAC9C;AAIO,SAAS,WAAW,OAAyB;AAClD,SAAO,MAAM,MAAM,GAAG,EAAE,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AAChE;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,IAAI,WAAW,KAAK,EAAE,KAAK,GA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Aa,YAAa;AACrC,WAAS,SAAS,oBAAoB,WAAW,OAAO;AAC1D;","names":[]}
@@ -23,14 +23,14 @@ import {
23
23
  PopoverSurface,
24
24
  usePending,
25
25
  usePopover
26
- } from "./chunk-YDOQE47G.js";
26
+ } from "./chunk-PYDMEYWA.js";
27
27
  import {
28
28
  AsyncView
29
29
  } from "./chunk-3UBAO3N5.js";
30
30
  import {
31
31
  filterCommandPaletteItems,
32
32
  groupCommandPaletteItems
33
- } from "./chunk-EDTWGSQT.js";
33
+ } from "./chunk-SJWIZT7B.js";
34
34
  import {
35
35
  attachmentPartsFromMessageParts
36
36
  } from "./chunk-5ZTFZBS6.js";
@@ -5959,4 +5959,4 @@ export {
5959
5959
  useThinkingSeconds,
5960
5960
  ChatMessages
5961
5961
  };
5962
- //# sourceMappingURL=chunk-JAYKCWW4.js.map
5962
+ //# sourceMappingURL=chunk-U2UAQTFY.js.map