unsys-canvas 0.1.2 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, lazy, memo, useLayoutEffect, useCallback, useState, useEffect, Suspense, useRef, Component, useContext } from 'react';
1
+ import { createContext, lazy, memo, useLayoutEffect, useCallback, useState, useEffect, Suspense, useRef, Component, useMemo, useContext } from 'react';
2
2
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
3
  import '@excalidraw/excalidraw/index.css';
4
4
  import katex from 'katex';
@@ -204,8 +204,8 @@ var UNSYS_CANVAS_TIMER_RESET_LOADING_MS = 700;
204
204
  var SESSION_FORMAT_WRAPPER = /^(in (one|this|a) (multi-turn |topic-horizon )?guided (conversation|dialogue)[,:.]?\s+|through (a |one )?(multi-turn |topic-horizon )?guided (conversation|dialogue)[,:.]?\s+|in (one|this|a) topic-horizon (conversation|dialogue)[,:.]?\s+|this (chapter|session) is a (topic-horizon |guided |multi-turn )?(conversation|dialogue)[,:.]?\s+|as your (practice )?coach[,:.]?\s+)/i;
205
205
  var COMMAND_META_WRAPPERS = [
206
206
  /^your (question|reply|answer|prompt) sits in the right place(?:\s*\([^)]+\))?[.!]?\s*/i,
207
- /^\(after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|declutter|answer|draw|do\/?run|run|focus)\)[.!]?\s*/i,
208
- /^after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|declutter|answer|draw|do\/?run|run|focus)[,:.]?\s*/i
207
+ /^\(after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|pretty|declutter|answer|draw|do\/?run|run|focus)\)[.!]?\s*/i,
208
+ /^after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|pretty|declutter|answer|draw|do\/?run|run|focus)[,:.]?\s*/i
209
209
  ];
210
210
  function capitalizeIfStripped(original, stripped) {
211
211
  if (!stripped) return "";
@@ -946,6 +946,22 @@ function buildUnsysCanvasSimplifyUserMessage(input) {
946
946
  ].join("\n");
947
947
  return unsysCanvasWithDomainPrefix(body, input.workspace);
948
948
  }
949
+ function buildUnsysCanvasPrettyUserMessage(input) {
950
+ const live = (input.selectedElements ?? []).filter((el) => el && !el.isDeleted);
951
+ const body = [
952
+ "Pretty the selected marks into a tidied, well-made Excalidraw note.",
953
+ "Keep the same meaning. Do not drop claims. The original marks stay; your result is placed beside them.",
954
+ "Give the note a clear title or header. Group related bits, align them, and use even spacing.",
955
+ "Wrap the composition in a container or frame. Use bullets when the content is a list of points.",
956
+ "Use the board palette: stroke #1e1e1e, header fill #ffffff, body fill #f4f4f5. Tasteful, not noisy.",
957
+ 'Prefer JSON "elements" (frame or rectangle, title text, body text or bullets). If a diagram is unnecessary, put the formatted note in "text" with a title on the first line, then a blank line, then the body.',
958
+ "Do not mention commands or placement.",
959
+ "",
960
+ "Selected elements:",
961
+ unsysCanvasCommandSelectionListing(live)
962
+ ].join("\n");
963
+ return unsysCanvasWithDomainPrefix(body, input.workspace);
964
+ }
949
965
  function buildUnsysCanvasClearOverlapsUserMessage(input) {
950
966
  const live = (input.selectedElements ?? []).filter((el) => el && !el.isDeleted);
951
967
  const body = [
@@ -970,6 +986,7 @@ function buildUnsysCanvasCommandUserMessage(input) {
970
986
  if (kind === "declutter" || kind === "clear-overlaps") return buildUnsysCanvasClearOverlapsUserMessage(input);
971
987
  if (kind === "draw") return buildUnsysCanvasDrawUserMessage(input);
972
988
  if (kind === "simplify") return buildUnsysCanvasSimplifyUserMessage(input);
989
+ if (kind === "pretty") return buildUnsysCanvasPrettyUserMessage(input);
973
990
  if (kind === "concepts") return buildUnsysCanvasConceptsUserMessage(input);
974
991
  if (kind === "check") return buildUnsysCanvasCheckUserMessage(input);
975
992
  return buildUnsysCanvasAskUserMessage({
@@ -1540,6 +1557,8 @@ function unsysCanvasNoteLabel(kind) {
1540
1557
  return "Do/run";
1541
1558
  case "simplify":
1542
1559
  return "Simplify";
1560
+ case "pretty":
1561
+ return "Pretty";
1543
1562
  case "concepts":
1544
1563
  return "Concepts";
1545
1564
  case "define":
@@ -2056,12 +2075,36 @@ function unsysCanvasRevealScroll(elements, appState, pad = 40) {
2056
2075
  }
2057
2076
  return { scrollX, scrollY };
2058
2077
  }
2078
+ function unsysCanvasSelectionViewportRect(elements, appState) {
2079
+ const bounds = unsysCanvasContentBounds(elements);
2080
+ if (!bounds) return null;
2081
+ const topLeft = unsysCanvasSceneToViewport({ x: bounds.minX, y: bounds.minY }, appState);
2082
+ const bottomRight = unsysCanvasSceneToViewport({ x: bounds.maxX, y: bounds.maxY }, appState);
2083
+ return {
2084
+ left: Math.min(topLeft.x, bottomRight.x),
2085
+ top: Math.min(topLeft.y, bottomRight.y),
2086
+ right: Math.max(topLeft.x, bottomRight.x),
2087
+ bottom: Math.max(topLeft.y, bottomRight.y)
2088
+ };
2089
+ }
2059
2090
  function unsysCanvasViewportToHost(point, host) {
2060
2091
  return {
2061
2092
  x: point.x - (Number(host?.left) || 0),
2062
2093
  y: point.y - (Number(host?.top) || 0)
2063
2094
  };
2064
2095
  }
2096
+ function unsysCanvasSelectionHostRect(elements, appState, host) {
2097
+ const rect = unsysCanvasSelectionViewportRect(elements, appState);
2098
+ if (!rect) return null;
2099
+ const originLeft = Number(host?.left) || 0;
2100
+ const originTop = Number(host?.top) || 0;
2101
+ return {
2102
+ left: rect.left - originLeft,
2103
+ top: rect.top - originTop,
2104
+ right: rect.right - originLeft,
2105
+ bottom: rect.bottom - originTop
2106
+ };
2107
+ }
2065
2108
  function ileLearnMoreSelectionKey(selectedElementIds) {
2066
2109
  return Object.keys(selectedElementIds ?? {}).filter((id) => Boolean(selectedElementIds?.[id])).sort().join(",");
2067
2110
  }
@@ -2073,7 +2116,8 @@ function unsysCanvasSlashBarOpen(input) {
2073
2116
  }
2074
2117
  function unsysCanvasSlashKeyOpensBar(input) {
2075
2118
  if (input.typingInField) return false;
2076
- return input.key === "/" && Boolean(input.selectionActive);
2119
+ if (!input.selectionActive) return false;
2120
+ return input.key === "/";
2077
2121
  }
2078
2122
 
2079
2123
  // src/lib/work-canvas/work-canvas-xai-parse.ts
@@ -2883,6 +2927,8 @@ var UNSYS_CANVAS_COMMANDS = [
2883
2927
  label: "Simplify",
2884
2928
  tooltip: "Keep the original marks and place a shorter, plainer rewrite next to them. If the selection is a term, make the meaning plain.",
2885
2929
  shortcut: "s",
2930
+ gesture: "question-mark",
2931
+ gestureHint: "Laser: question mark over a mark.",
2886
2932
  needsSelection: true,
2887
2933
  boardOnly: false,
2888
2934
  replacesSelection: false
@@ -2892,6 +2938,8 @@ var UNSYS_CANVAS_COMMANDS = [
2892
2938
  label: "Subdivide",
2893
2939
  tooltip: "Keep the original mark and fan its parts into smaller nodes, linked with arrows.",
2894
2940
  shortcut: "b",
2941
+ gesture: "double-line",
2942
+ gestureHint: "Laser: two quick lines from a mark into empty space.",
2895
2943
  needsSelection: true,
2896
2944
  boardOnly: false,
2897
2945
  replacesSelection: false
@@ -2901,6 +2949,8 @@ var UNSYS_CANVAS_COMMANDS = [
2901
2949
  label: "Concepts",
2902
2950
  tooltip: "Keep the original and fan its named concepts into linked nodes.",
2903
2951
  shortcut: "c",
2952
+ gesture: "line",
2953
+ gestureHint: "Laser: line from a mark into empty space.",
2904
2954
  needsSelection: true,
2905
2955
  boardOnly: false,
2906
2956
  replacesSelection: false
@@ -2911,6 +2961,8 @@ var UNSYS_CANVAS_COMMANDS = [
2911
2961
  slash: "run",
2912
2962
  tooltip: "Work the highlighted problem: carry it out, compute it, or show the result.",
2913
2963
  shortcut: "d",
2964
+ gesture: "loop",
2965
+ gestureHint: "Laser: circle or loop over a mark.",
2914
2966
  needsSelection: true,
2915
2967
  boardOnly: false,
2916
2968
  replacesSelection: false
@@ -2920,12 +2972,28 @@ var UNSYS_CANVAS_COMMANDS = [
2920
2972
  label: "Refactor",
2921
2973
  tooltip: "Delete the selected marks and replace them with a clearer rewrite.",
2922
2974
  shortcut: "r",
2975
+ gesture: "zigzag",
2976
+ gestureHint: "Laser: zigzag over a mark.",
2923
2977
  needsSelection: true,
2924
2978
  boardOnly: false,
2925
2979
  replacesSelection: true
2980
+ },
2981
+ {
2982
+ id: "pretty",
2983
+ label: "Pretty",
2984
+ tooltip: "Keep the original marks and place a tidied, well-formatted Excalidraw note next to them.",
2985
+ shortcut: "p",
2986
+ gesture: "check",
2987
+ gestureHint: "Laser: check mark over a mark.",
2988
+ needsSelection: true,
2989
+ boardOnly: false,
2990
+ replacesSelection: false
2926
2991
  }
2927
2992
  ];
2928
2993
  var UNSYS_CANVAS_CHEATSHEET_LABEL = "Command cheat sheet";
2994
+ var UNSYS_CANVAS_COMMAND_PICKER_LABEL = "Command picker";
2995
+ var UNSYS_CANVAS_COMMAND_PICKER_SHORTCUT = "/";
2996
+ var UNSYS_CANVAS_COMMAND_PICKER_TOOLTIP = "Type to filter commands, then Enter to run one on the current selection. Escape closes. Shortcut / while something is selected. Also right-click or the / control near the selection.";
2929
2997
  function unsysCanvasCommandsFor(_guide, extras = []) {
2930
2998
  const catalog = UNSYS_CANVAS_COMMANDS.map((command) => ({ ...command }));
2931
2999
  const seen = new Set(catalog.map((command) => command.id));
@@ -2942,6 +3010,8 @@ function unsysCanvasCommandsFor(_guide, extras = []) {
2942
3010
  boardOnly: false,
2943
3011
  replacesSelection: false,
2944
3012
  slash: extra.slash,
3013
+ gesture: extra.gesture,
3014
+ gestureHint: extra.gestureHint,
2945
3015
  run: extra.run
2946
3016
  });
2947
3017
  }
@@ -3003,6 +3073,33 @@ function filterUnsysCanvasCommands(query, guide, extras = []) {
3003
3073
  (command) => unsysCanvasCommandMatchNames(command).some((name) => name.startsWith(q))
3004
3074
  );
3005
3075
  }
3076
+ function unsysCanvasFuzzySubsequence(name, query) {
3077
+ let i = 0;
3078
+ for (const ch of name) {
3079
+ if (ch === query[i]) i += 1;
3080
+ if (i >= query.length) return true;
3081
+ }
3082
+ return false;
3083
+ }
3084
+ function unsysCanvasCommandFuzzyScore(command, query) {
3085
+ const q = String(query || "").trim().toLowerCase();
3086
+ if (!q) return 1;
3087
+ if (command.shortcut && command.shortcut.toLowerCase() === q) return 100;
3088
+ let best = 0;
3089
+ for (const name of unsysCanvasCommandMatchNames(command)) {
3090
+ if (name === q) best = Math.max(best, 90);
3091
+ else if (name.startsWith(q)) best = Math.max(best, 80);
3092
+ else if (name.includes(q)) best = Math.max(best, 50);
3093
+ else if (unsysCanvasFuzzySubsequence(name, q)) best = Math.max(best, 20);
3094
+ }
3095
+ return best;
3096
+ }
3097
+ function fuzzyFilterUnsysCanvasCommands(query, guide, extras = []) {
3098
+ const catalog = unsysCanvasCommandsFor(guide, extras);
3099
+ const q = String(query || "").trim().toLowerCase();
3100
+ if (!q) return catalog;
3101
+ return catalog.map((command) => ({ command, score: unsysCanvasCommandFuzzyScore(command, q) })).filter((row) => row.score > 0).sort((a, b) => b.score - a.score || a.command.label.localeCompare(b.command.label)).map((row) => row.command);
3102
+ }
3006
3103
  function unsysCanvasCommandDraft(raw) {
3007
3104
  const trimmed = String(raw ?? "").trim();
3008
3105
  if (!trimmed.startsWith("/")) {
@@ -3115,6 +3212,7 @@ function unsysCanvasBindFanArrow(arrow, start, end, hostBounds) {
3115
3212
  function unsysCanvasFanNoteKind(mark) {
3116
3213
  if (mark === "ileConcepts") return "concepts";
3117
3214
  if (mark === "ileSimplify") return "simplify";
3215
+ if (mark === "ilePretty") return "pretty";
3118
3216
  return "breakdown";
3119
3217
  }
3120
3218
  function unsysCanvasFanStem(host, hostRect, end, toX, toY, mark, hostBounds) {
@@ -3274,6 +3372,80 @@ function fanUnsysCanvasLabeledNodes(scene, selectedElements, chunks, mark) {
3274
3372
  parts
3275
3373
  };
3276
3374
  }
3375
+ function placeUnsysCanvasPrettyReply(scene, selectedElements, payload) {
3376
+ const current = serializeUnsysCanvasScene(scene);
3377
+ const extra = normalizeExtraSkeletons(payload.elements);
3378
+ const text = String(payload.text || "").trim();
3379
+ if (extra.length) {
3380
+ const found = unsysCanvasFanHost(current, selectedElements);
3381
+ if (!found) return { scene: current, placed: false, parts: [] };
3382
+ const { host, expanded } = found;
3383
+ const hostRect = unsysCanvasNormalizedRect(host) ?? {
3384
+ minX: Number(host.x) || 0,
3385
+ minY: Number(host.y) || 0,
3386
+ maxX: (Number(host.x) || 0) + Math.max(1, Number(host.width) || 0),
3387
+ maxY: (Number(host.y) || 0) + Math.max(1, Number(host.height) || 0)
3388
+ };
3389
+ const created = [];
3390
+ for (const item of extra) {
3391
+ const converted = convertToExcalidrawElements([
3392
+ {
3393
+ ...item,
3394
+ customData: { ...item.customData ?? {}, ilePretty: true }
3395
+ }
3396
+ ]);
3397
+ created.push(...converted);
3398
+ }
3399
+ if (!created.length) return { scene: current, placed: false, parts: [] };
3400
+ const box = unsysCanvasContentBounds(created);
3401
+ const gapX = UNSYS_CANVAS_OVERLAP_GAP + 48;
3402
+ const dx = hostRect.maxX + gapX - (box?.minX ?? 0);
3403
+ const dy = hostRect.minY - (box?.minY ?? 0);
3404
+ for (const el of created) {
3405
+ el.x = Number(el.x) + dx;
3406
+ el.y = Number(el.y) + dy;
3407
+ }
3408
+ const settledNodes = settleUnsysCanvasIncoming(
3409
+ created,
3410
+ current.elements.filter((el) => !el.isDeleted)
3411
+ );
3412
+ const bind = settledNodes.find((el) => el.type === "frame" || el.type === "rectangle") ?? settledNodes.find((el) => el.type !== "arrow" && el.type !== "line") ?? settledNodes[0];
3413
+ const nodeHosts = bind ? [bind] : [];
3414
+ const { connectors, hostBounds } = unsysCanvasFanConnectors(
3415
+ host,
3416
+ hostRect,
3417
+ settledNodes,
3418
+ nodeHosts,
3419
+ "ilePretty"
3420
+ );
3421
+ const hostNext = {
3422
+ ...host,
3423
+ boundElements: hostBounds,
3424
+ version: (Number(host.version) || 1) + 1
3425
+ };
3426
+ const parts = [...settledNodes, ...connectors];
3427
+ return {
3428
+ scene: {
3429
+ ...current,
3430
+ elements: [
3431
+ ...current.elements.map((el) => el.id === host.id ? hostNext : el),
3432
+ ...parts
3433
+ ],
3434
+ appState: {
3435
+ ...current.appState,
3436
+ selectedElementIds: Object.fromEntries(
3437
+ expanded.filter((el) => el.id && !el.isDeleted).map((el) => [el.id, true])
3438
+ )
3439
+ }
3440
+ },
3441
+ placed: true,
3442
+ parts
3443
+ };
3444
+ }
3445
+ if (!text) return { scene: current, placed: false, parts: [] };
3446
+ const fanned = fanUnsysCanvasLabeledNodes(current, selectedElements, [text], "ilePretty");
3447
+ return { scene: fanned.scene, placed: fanned.split, parts: fanned.parts };
3448
+ }
3277
3449
  function breakdownUnsysCanvasSelection(scene, selectedElements) {
3278
3450
  const current = serializeUnsysCanvasScene(scene);
3279
3451
  const expanded = expandUnsysCanvasCommandSelection(current, selectedElements);
@@ -3290,6 +3462,7 @@ function unsysCanvasCommandPrompt(action) {
3290
3462
  if (action === "draw") return "Do/run";
3291
3463
  if (action === "breakdown") return "Subdivide";
3292
3464
  if (action === "concepts") return "Concepts";
3465
+ if (action === "pretty") return "Pretty";
3293
3466
  return action;
3294
3467
  }
3295
3468
  function unsysCanvasPlacedHarnessNext(scene) {
@@ -3411,6 +3584,9 @@ function runUnsysCanvasCommand(input) {
3411
3584
  if (input.action === "draw") {
3412
3585
  return idle(null, { kind: "draw", prompt });
3413
3586
  }
3587
+ if (input.action === "pretty") {
3588
+ return idle(null, { kind: "pretty", prompt });
3589
+ }
3414
3590
  return idle(null);
3415
3591
  }
3416
3592
  var CommandContext = createContext(null);
@@ -3529,6 +3705,185 @@ function CanvasPromptBar({
3529
3705
  useEffect(() => () => publishCommands(null), [publishCommands]);
3530
3706
  return null;
3531
3707
  }
3708
+ var UNSYS_CANVAS_COMMAND_RAIL_CLASS = "pointer-events-auto relative flex min-h-9 w-full min-w-0 flex-row items-center justify-start gap-1.5 whitespace-nowrap rounded-none border border-white/45 bg-black px-1.5 py-2 text-left font-mono text-[11px] leading-tight text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.35)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
3709
+ var UNSYS_CANVAS_COMMAND_SIDEBAR_CLASS = "pointer-events-auto relative flex min-h-9 w-full min-w-0 flex-row items-center justify-start gap-1.5 overflow-hidden whitespace-nowrap rounded-none border border-white/35 bg-black px-1.5 py-1.5 text-left font-mono text-[11px] leading-tight text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
3710
+ var UNSYS_CANVAS_COMMAND_SIDEBAR_MARK_CLASS = "h-3.5 w-3.5 shrink-0";
3711
+ var UNSYS_CANVAS_COMMAND_STRIPE_CLASS = "pointer-events-auto relative flex h-10 w-10 shrink-0 items-center justify-center rounded-none border border-white/35 bg-black text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
3712
+ var UNSYS_CANVAS_COMMAND_STRIPE_MARK_CLASS = "h-4 w-4 shrink-0";
3713
+ var ICON_PATHS = {
3714
+ focus: "M8 2v2.5M8 11.5V14M2 8h2.5M11.5 8H14M8 5.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z",
3715
+ next: "M2 8h9M8 4.5l4.5 3.5L8 11.5M13.5 3.5v9",
3716
+ simplify: "M3 4h10M3 8h7M3 12h4",
3717
+ breakdown: "M2 6.5h4v3H2zM10 2.5h4v3h-4zM10 10.5h4v3h-4zM6 8h4M10 8V4M10 8v6.5",
3718
+ concepts: "M2 2.5h4v3H2zM10 2.5h4v3h-4zM6 10.5h4v3H6zM4 5.5v5M12 5.5v5M8 8.5v2",
3719
+ define: "M3 2.5h10v11H3zM5.5 5.5h5M5.5 8h7M5.5 10.5h4",
3720
+ answer: "M3 3h10v7H8l-3 3v-3H3z",
3721
+ draw: "M10.5 2.5l3 3-8 8H2.5v-3zM9 4l3 3",
3722
+ refactor: "M4 3h5v2H6.5A4.5 4.5 0 1 1 3 10M12 13H7v-2h2.5A4.5 4.5 0 1 1 13 6",
3723
+ pretty: "M2.5 2.5h11v11H2.5zM5 6h6M5 8.5h6M5 11h4",
3724
+ picker: "M3 4.5h10M3 8h7M3 11.5h4",
3725
+ dictate: "M8 2.5a2 2 0 0 1 2 2V8a2 2 0 1 1-4 0V4.5a2 2 0 0 1 2-2zM5 8.5a3 3 0 0 0 6 0M8 11.5V14",
3726
+ pointer: "M4.2 8.2a3.6 3.6 0 1 1 3.6-3.6l5.8 5.8a2.2 2.2 0 0 1-3.1 3.1zM9.4 9.4l2.1 2.1M7 7.2l1.3 1.3M4.8 4.8l1.8 1.8",
3727
+ commit: "M3 8h10M10 5l3 3-3 3",
3728
+ "rail-expand": "M6 3l5 5-5 5",
3729
+ "rail-collapse": "M10 3L5 8l5 5",
3730
+ boards: "M2.5 3.5h4.5v4.5H2.5zM9 3.5h4.5v4.5H9zM2.5 10h4.5v3H2.5zM9 10h4.5v3H9z",
3731
+ save: "M3 8.5V13h10V8.5M8 2.5v8M5 8l3 3 3-3"
3732
+ };
3733
+ function CommandMark({
3734
+ id,
3735
+ className = "h-3.5 w-3.5"
3736
+ }) {
3737
+ const d = ICON_PATHS[id] ?? ICON_PATHS.simplify;
3738
+ return /* @__PURE__ */ jsx(
3739
+ "svg",
3740
+ {
3741
+ viewBox: "0 0 16 16",
3742
+ className,
3743
+ fill: "none",
3744
+ stroke: "currentColor",
3745
+ strokeWidth: 1.4,
3746
+ strokeLinecap: "round",
3747
+ strokeLinejoin: "round",
3748
+ "aria-hidden": true,
3749
+ "data-unsys-canvas-command-mark": id,
3750
+ "data-command-icon": id,
3751
+ children: /* @__PURE__ */ jsx("path", { d })
3752
+ }
3753
+ );
3754
+ }
3755
+ function UnsysCanvasCommandPicker({
3756
+ open,
3757
+ left,
3758
+ top,
3759
+ query,
3760
+ extras = [],
3761
+ onQueryChange,
3762
+ onRun,
3763
+ onClose
3764
+ }) {
3765
+ const inputRef = useRef(null);
3766
+ const [active, setActive] = useState(0);
3767
+ const matches = useMemo(
3768
+ () => fuzzyFilterUnsysCanvasCommands(query, null, extras),
3769
+ [extras, query]
3770
+ );
3771
+ useEffect(() => {
3772
+ setActive(0);
3773
+ }, [query, open]);
3774
+ useEffect(() => {
3775
+ if (!open) return;
3776
+ inputRef.current?.focus();
3777
+ inputRef.current?.select();
3778
+ }, [open]);
3779
+ if (!open) return null;
3780
+ const runAt = (index) => {
3781
+ const command = matches[index];
3782
+ if (!command) return;
3783
+ onRun(command.id);
3784
+ };
3785
+ return /* @__PURE__ */ jsxs(
3786
+ "div",
3787
+ {
3788
+ "data-unsys-canvas-command-picker": true,
3789
+ role: "dialog",
3790
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3791
+ className: "pointer-events-auto absolute z-[70] w-[16.5rem] border border-white bg-black text-white shadow-[0_12px_40px_rgba(0,0,0,0.55)]",
3792
+ style: { left, top },
3793
+ onMouseDown: (event) => event.preventDefault(),
3794
+ children: [
3795
+ /* @__PURE__ */ jsx(
3796
+ "input",
3797
+ {
3798
+ ref: inputRef,
3799
+ "data-unsys-canvas-command-picker-input": true,
3800
+ value: query,
3801
+ onChange: (event) => onQueryChange(event.target.value.replace(/^\//, "")),
3802
+ placeholder: "Filter commands",
3803
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3804
+ className: "w-full border-b border-white/30 bg-black px-2 py-1.5 font-mono text-[12px] text-white outline-none placeholder:text-white/35",
3805
+ onKeyDown: (event) => {
3806
+ if (event.key === "Escape") {
3807
+ event.preventDefault();
3808
+ event.stopPropagation();
3809
+ onClose();
3810
+ return;
3811
+ }
3812
+ if (event.key === "ArrowDown") {
3813
+ event.preventDefault();
3814
+ setActive((prev) => Math.min(matches.length - 1, prev + 1));
3815
+ return;
3816
+ }
3817
+ if (event.key === "ArrowUp") {
3818
+ event.preventDefault();
3819
+ setActive((prev) => Math.max(0, prev - 1));
3820
+ return;
3821
+ }
3822
+ if (event.key === "Enter") {
3823
+ event.preventDefault();
3824
+ event.stopPropagation();
3825
+ runAt(active);
3826
+ }
3827
+ }
3828
+ }
3829
+ ),
3830
+ /* @__PURE__ */ jsx("ul", { "data-unsys-canvas-command-picker-list": true, className: "max-h-56 overflow-y-auto py-1", children: matches.length ? matches.map((command, index) => /* @__PURE__ */ jsx(
3831
+ PickerRow,
3832
+ {
3833
+ command,
3834
+ active: index === active,
3835
+ onRun: () => onRun(command.id)
3836
+ },
3837
+ command.id
3838
+ )) : /* @__PURE__ */ jsx("li", { className: "px-2 py-2 font-mono text-[11px] text-white/45", children: "No matching commands" }) })
3839
+ ]
3840
+ }
3841
+ );
3842
+ }
3843
+ function PickerRow({
3844
+ command,
3845
+ active,
3846
+ onRun
3847
+ }) {
3848
+ const shortcut = unsysCanvasCommandShortcutLabel(command.shortcut);
3849
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
3850
+ "button",
3851
+ {
3852
+ type: "button",
3853
+ "data-unsys-canvas-command-picker-row": command.id,
3854
+ "data-active": active ? "true" : "false",
3855
+ onClick: onRun,
3856
+ className: `flex w-full items-center gap-2 px-2 py-1.5 text-left font-mono text-[11px] ${active ? "bg-white text-neutral-950" : "text-white hover:bg-white/10"}`,
3857
+ children: [
3858
+ /* @__PURE__ */ jsx(CommandMark, { id: command.id, label: command.label, className: "h-3.5 w-3.5 shrink-0" }),
3859
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: command.label }),
3860
+ shortcut ? /* @__PURE__ */ jsx("kbd", { className: "shrink-0 text-[10px] opacity-55", children: shortcut }) : null
3861
+ ]
3862
+ }
3863
+ ) });
3864
+ }
3865
+ function UnsysCanvasCommandPickerAffordance({
3866
+ visible,
3867
+ left,
3868
+ top,
3869
+ onOpen
3870
+ }) {
3871
+ if (!visible) return null;
3872
+ return /* @__PURE__ */ jsx(
3873
+ "button",
3874
+ {
3875
+ type: "button",
3876
+ "data-unsys-canvas-command-picker-affordance": true,
3877
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3878
+ title: UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3879
+ className: "pointer-events-auto absolute z-[60] flex h-6 w-6 items-center justify-center border border-white/50 bg-black font-mono text-[11px] text-white hover:border-white",
3880
+ style: { left, top },
3881
+ onMouseDown: (event) => event.preventDefault(),
3882
+ onClick: onOpen,
3883
+ children: "/"
3884
+ }
3885
+ );
3886
+ }
3532
3887
 
3533
3888
  // src/lib/session-branch-model.ts
3534
3889
  function openBranchQuestions(_model) {
@@ -3719,7 +4074,8 @@ function UnsysExcalidrawMount({
3719
4074
  onChange,
3720
4075
  onPointerUpdate,
3721
4076
  initialData,
3722
- viewModeEnabled = false
4077
+ viewModeEnabled = false,
4078
+ isCollaborating = false
3723
4079
  }) {
3724
4080
  const onApiRef = useRef(onApi);
3725
4081
  const onChangeRef = useRef(onChange);
@@ -3736,7 +4092,8 @@ function UnsysExcalidrawMount({
3736
4092
  onPointerUpdateRef,
3737
4093
  initialData: initialDataRef.current,
3738
4094
  viewModeEnabled,
3739
- pointerEnabled: Boolean(onPointerUpdate)
4095
+ pointerEnabled: Boolean(onPointerUpdate),
4096
+ isCollaborating
3740
4097
  }
3741
4098
  );
3742
4099
  }
@@ -3746,7 +4103,8 @@ var UnsysExcalidrawStable = memo(function UnsysExcalidrawStable2({
3746
4103
  onPointerUpdateRef,
3747
4104
  initialData,
3748
4105
  viewModeEnabled,
3749
- pointerEnabled
4106
+ pointerEnabled,
4107
+ isCollaborating
3750
4108
  }) {
3751
4109
  useLayoutEffect(() => {
3752
4110
  return () => {
@@ -3783,6 +4141,7 @@ var UnsysExcalidrawStable = memo(function UnsysExcalidrawStable2({
3783
4141
  initialData,
3784
4142
  theme: "dark",
3785
4143
  viewModeEnabled,
4144
+ isCollaborating,
3786
4145
  UIOptions: UNSYS_EXCALIDRAW_UI_OPTIONS
3787
4146
  }
3788
4147
  ) });
@@ -4044,333 +4403,52 @@ function unsysCanvasWithLiveTransparentFill(scene) {
4044
4403
  };
4045
4404
  }
4046
4405
 
4047
- // src/lib/events.ts
4048
- var UNSYS_CANVAS_EVENT_TYPES = [
4049
- "element:added",
4050
- "element:updated",
4051
- "element:deleted",
4052
- "element:moved",
4053
- "element:resized",
4054
- "text:edited",
4055
- "selection:changed",
4056
- "tool:changed",
4057
- "viewport:changed",
4058
- "command:run",
4059
- "prompt:submit",
4060
- "dictate:start",
4061
- "dictate:stop",
4062
- "dictate:text",
4063
- "laser:gesture",
4064
- "latex:render",
4065
- "undo",
4066
- "redo"
4067
- ];
4068
- var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
4069
- var HIGH_FREQ = /* @__PURE__ */ new Set([
4070
- "viewport:changed",
4071
- "element:moved",
4072
- "element:resized",
4073
- "element:updated",
4074
- "text:edited"
4075
- ]);
4076
- function asRecord2(value) {
4077
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
4078
- return value;
4406
+ // src/lib/work-canvas/work-canvas-xai.ts
4407
+ var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
4408
+ var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
4409
+ function unsysCanvasXaiNeedsBoardContext(kind) {
4410
+ return !kind || kind === "ask" || kind === "draw";
4079
4411
  }
4080
- function elementMap(elements) {
4081
- const map = /* @__PURE__ */ new Map();
4082
- for (const el of elements) {
4083
- if (el && typeof el.id === "string") map.set(el.id, el);
4084
- }
4085
- return map;
4412
+ function unsysCanvasXaiMaxTokens(kind) {
4413
+ if (kind === "concepts") return 220;
4414
+ if (kind === "simplify") return 280;
4415
+ if (kind === "pretty") return 520;
4416
+ if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
4417
+ if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
4418
+ return 800;
4086
4419
  }
4087
- function changedProps(prev, next) {
4088
- const changed = {};
4089
- const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
4090
- for (const key of keys) {
4091
- if (SKIP_KEYS.has(key)) continue;
4092
- const from = prev?.[key];
4093
- const to = next[key];
4094
- if (JSON.stringify(from) !== JSON.stringify(to)) {
4095
- changed[key] = { from, to };
4096
- }
4097
- }
4098
- return changed;
4420
+ function unsysCanvasXaiFetchTimeout(kind) {
4421
+ return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
4099
4422
  }
4100
- function selectedIds(appState) {
4101
- const raw = asRecord2(appState.selectedElementIds);
4102
- return Object.keys(raw).filter((id) => raw[id]);
4423
+ function unsysCanvasContextSkipChrome(el) {
4424
+ const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
4425
+ return part === "header" || part === "label" || part === "body";
4103
4426
  }
4104
- function zoomValue(appState) {
4105
- const zoom = appState.zoom;
4106
- if (zoom && typeof zoom === "object" && "value" in zoom) {
4107
- return Number(zoom.value) || 1;
4108
- }
4109
- return Number(zoom) || 1;
4427
+ function unsysCanvasCompactListing(scene, options) {
4428
+ const live = serializeUnsysCanvasScene(scene).elements.filter(
4429
+ (el) => !el.isDeleted && el.type !== "cursor" && !unsysCanvasContextSkipChrome(el)
4430
+ );
4431
+ if (!live.length) return "(no live elements)";
4432
+ const cap = Math.max(1, UNSYS_CANVAS_CONTEXT_MAX_MARKS);
4433
+ const shown = live.slice(0, cap);
4434
+ const lines = shown.map((el) => {
4435
+ const text = String(el.originalText || el.text || "").replace(/\s+/g, " ").trim().slice(0, UNSYS_CANVAS_CONTEXT_TEXT_MAX);
4436
+ return text ? `[${el.type}] ${JSON.stringify(text)}` : `[${el.type}]`;
4437
+ });
4438
+ if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
4439
+ return lines.join("\n");
4110
4440
  }
4111
- function toolName(appState) {
4112
- const tool = appState.activeTool;
4113
- if (typeof tool === "string") return tool;
4114
- if (tool && typeof tool === "object" && "type" in tool) {
4115
- return String(tool.type || "") || null;
4116
- }
4117
- return null;
4441
+ function unsysCanvasTurnContextMessage(scene, input) {
4442
+ const board = String(input?.boardLabel || "CHAPTER").trim() || "CHAPTER";
4443
+ const listing = unsysCanvasCompactListing(scene);
4444
+ const body = `CURRENT ${board} WORK CANVAS (compact: type and text of live marks; positions omitted). Co-author this board: your reply is placed as a Work note the learner can move and edit. ${unsysCanvasXaiToolsInstruction()}
4445
+ ${listing}`;
4446
+ return unsysCanvasWithDomainPrefix(body, input?.workspace);
4118
4447
  }
4119
- function snapshot(scene) {
4120
- const rec = asRecord2(scene);
4121
- const elements = Array.isArray(rec.elements) ? rec.elements : [];
4122
- return {
4123
- elements,
4124
- appState: asRecord2(rec.appState),
4125
- files: asRecord2(rec.files)
4126
- };
4127
- }
4128
- function eventKey(event) {
4129
- const id = typeof event.payload.id === "string" ? event.payload.id : "";
4130
- return `${event.type}:${id}`;
4131
- }
4132
- function mergePayload(prev, next) {
4133
- const merged = { ...prev, ...next };
4134
- if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
4135
- if ("to" in next) merged.to = next.to;
4136
- if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
4137
- const a = prev.changed;
4138
- const b = next.changed;
4139
- const changed = { ...a };
4140
- for (const [key, value] of Object.entries(b)) {
4141
- const earlier = a[key];
4142
- changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
4143
- }
4144
- merged.changed = changed;
4145
- }
4146
- return merged;
4147
- }
4148
- var UnsysCanvasEventCollector = class {
4149
- constructor(options) {
4150
- this.seq = 0;
4151
- this.prev = null;
4152
- this.buffer = [];
4153
- this.lastFlush = 0;
4154
- this.batchMs = options?.batchMs ?? 0;
4155
- }
4156
- reset(scene) {
4157
- this.prev = snapshot(scene);
4158
- this.seq = 0;
4159
- this.buffer = [];
4160
- this.lastFlush = 0;
4161
- }
4162
- syncWithoutEmit(scene) {
4163
- this.prev = snapshot(scene);
4164
- }
4165
- push(type, payload) {
4166
- this.seq += 1;
4167
- return { seq: this.seq, ts: Date.now(), type, payload };
4168
- }
4169
- observeScene(scene, _opts) {
4170
- const next = snapshot(scene);
4171
- const prev = this.prev ?? { elements: [], appState: {}};
4172
- const events = [];
4173
- const prevEls = elementMap(prev.elements);
4174
- const nextEls = elementMap(next.elements);
4175
- for (const [id, el] of nextEls) {
4176
- const before = prevEls.get(id);
4177
- const deleted = Boolean(el.isDeleted);
4178
- const wasDeleted = Boolean(before?.isDeleted);
4179
- if (!before || wasDeleted && !deleted) {
4180
- if (!deleted) {
4181
- events.push(
4182
- this.push("element:added", {
4183
- id,
4184
- type: el.type,
4185
- element: el
4186
- })
4187
- );
4188
- }
4189
- continue;
4190
- }
4191
- if (!wasDeleted && deleted) {
4192
- events.push(this.push("element:deleted", { id, type: el.type, element: el }));
4193
- continue;
4194
- }
4195
- if (deleted) continue;
4196
- const changed = changedProps(before, el);
4197
- if (!Object.keys(changed).length) continue;
4198
- events.push(
4199
- this.push("element:updated", {
4200
- id,
4201
- type: el.type,
4202
- changed
4203
- })
4204
- );
4205
- if ("x" in changed || "y" in changed) {
4206
- events.push(
4207
- this.push("element:moved", {
4208
- id,
4209
- type: el.type,
4210
- from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
4211
- to: { x: el.x, y: el.y }
4212
- })
4213
- );
4214
- }
4215
- if ("width" in changed || "height" in changed) {
4216
- events.push(
4217
- this.push("element:resized", {
4218
- id,
4219
- type: el.type,
4220
- from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
4221
- to: { width: el.width, height: el.height }
4222
- })
4223
- );
4224
- }
4225
- if ("text" in changed || "originalText" in changed) {
4226
- events.push(
4227
- this.push("text:edited", {
4228
- id,
4229
- type: el.type,
4230
- from: changed.text?.from ?? changed.originalText?.from ?? before.text,
4231
- to: el.text ?? el.originalText
4232
- })
4233
- );
4234
- }
4235
- }
4236
- for (const [id, el] of prevEls) {
4237
- if (nextEls.has(id)) continue;
4238
- if (el.isDeleted) continue;
4239
- events.push(this.push("element:deleted", { id, type: el.type, element: el }));
4240
- }
4241
- const prevSel = selectedIds(prev.appState);
4242
- const nextSel = selectedIds(next.appState);
4243
- if (prevSel.join(",") !== nextSel.join(",")) {
4244
- events.push(this.push("selection:changed", { from: prevSel, to: nextSel }));
4245
- }
4246
- const prevTool = toolName(prev.appState);
4247
- const nextTool = toolName(next.appState);
4248
- if (prevTool !== nextTool) {
4249
- events.push(this.push("tool:changed", { from: prevTool, to: nextTool }));
4250
- }
4251
- const prevView = {
4252
- zoom: zoomValue(prev.appState),
4253
- scrollX: Number(prev.appState.scrollX) || 0,
4254
- scrollY: Number(prev.appState.scrollY) || 0
4255
- };
4256
- const nextView = {
4257
- zoom: zoomValue(next.appState),
4258
- scrollX: Number(next.appState.scrollX) || 0,
4259
- scrollY: Number(next.appState.scrollY) || 0
4260
- };
4261
- if (prevView.zoom !== nextView.zoom || prevView.scrollX !== nextView.scrollX || prevView.scrollY !== nextView.scrollY) {
4262
- events.push(this.push("viewport:changed", { from: prevView, to: nextView }));
4263
- }
4264
- this.prev = next;
4265
- return this.batch(events);
4266
- }
4267
- command(id, meta) {
4268
- return [
4269
- this.push("command:run", {
4270
- id: id ?? null,
4271
- args: meta ?? {}
4272
- })
4273
- ];
4274
- }
4275
- dictate(meta) {
4276
- const rec = asRecord2(meta);
4277
- const type = rec.phase === "start" ? "dictate:start" : rec.phase === "stop" ? "dictate:stop" : "dictate:text";
4278
- return [this.push(type, rec)];
4279
- }
4280
- prompt(text, meta) {
4281
- return [this.push("prompt:submit", { text: text ?? "", ...asRecord2(meta) })];
4282
- }
4283
- laser(meta) {
4284
- return [this.push("laser:gesture", asRecord2(meta))];
4285
- }
4286
- latex(meta) {
4287
- return [this.push("latex:render", asRecord2(meta))];
4288
- }
4289
- history(kind, meta) {
4290
- return [this.push(kind, asRecord2(meta))];
4291
- }
4292
- markGestureBusy(_busy) {
4293
- }
4294
- batch(incoming) {
4295
- const now = Date.now();
4296
- if (!this.buffer.length) this.lastFlush = now;
4297
- for (const event of incoming) {
4298
- const last = this.buffer[this.buffer.length - 1];
4299
- if (last && HIGH_FREQ.has(event.type) && eventKey(last) === eventKey(event)) {
4300
- this.buffer[this.buffer.length - 1] = {
4301
- ...event,
4302
- seq: last.seq,
4303
- ts: last.ts,
4304
- payload: mergePayload(last.payload, event.payload)
4305
- };
4306
- } else {
4307
- this.buffer.push(event);
4308
- }
4309
- }
4310
- if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
4311
- return [];
4312
- }
4313
- const flushed = this.buffer;
4314
- this.buffer = [];
4315
- this.lastFlush = now;
4316
- return flushed;
4317
- }
4318
- flush() {
4319
- const flushed = this.buffer;
4320
- this.buffer = [];
4321
- this.lastFlush = Date.now();
4322
- return flushed;
4323
- }
4324
- };
4325
- function unsysCanvasGestureBusy(_opts) {
4326
- return false;
4327
- }
4328
-
4329
- // src/lib/work-canvas/work-canvas-xai.ts
4330
- var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
4331
- var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
4332
- function unsysCanvasXaiNeedsBoardContext(kind) {
4333
- return !kind || kind === "ask" || kind === "draw";
4334
- }
4335
- function unsysCanvasXaiMaxTokens(kind) {
4336
- if (kind === "concepts") return 220;
4337
- if (kind === "simplify") return 280;
4338
- if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
4339
- if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
4340
- return 800;
4341
- }
4342
- function unsysCanvasXaiFetchTimeout(kind) {
4343
- return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
4344
- }
4345
- function unsysCanvasContextSkipChrome(el) {
4346
- const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
4347
- return part === "header" || part === "label" || part === "body";
4348
- }
4349
- function unsysCanvasCompactListing(scene, options) {
4350
- const live = serializeUnsysCanvasScene(scene).elements.filter(
4351
- (el) => !el.isDeleted && el.type !== "cursor" && !unsysCanvasContextSkipChrome(el)
4352
- );
4353
- if (!live.length) return "(no live elements)";
4354
- const cap = Math.max(1, UNSYS_CANVAS_CONTEXT_MAX_MARKS);
4355
- const shown = live.slice(0, cap);
4356
- const lines = shown.map((el) => {
4357
- const text = String(el.originalText || el.text || "").replace(/\s+/g, " ").trim().slice(0, UNSYS_CANVAS_CONTEXT_TEXT_MAX);
4358
- return text ? `[${el.type}] ${JSON.stringify(text)}` : `[${el.type}]`;
4359
- });
4360
- if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
4361
- return lines.join("\n");
4362
- }
4363
- function unsysCanvasTurnContextMessage(scene, input) {
4364
- const board = String(input?.boardLabel || "CHAPTER").trim() || "CHAPTER";
4365
- const listing = unsysCanvasCompactListing(scene);
4366
- const body = `CURRENT ${board} WORK CANVAS (compact: type and text of live marks; positions omitted). Co-author this board: your reply is placed as a Work note the learner can move and edit. ${unsysCanvasXaiToolsInstruction()}
4367
- ${listing}`;
4368
- return unsysCanvasWithDomainPrefix(body, input?.workspace);
4369
- }
4370
- var UNSYS_CONCEPT_LABEL_MAX = 8;
4371
- var UNSYS_CONCEPT_LABEL_MAX_CHARS = 72;
4372
- function unsysCanvasCleanConceptLabel(raw) {
4373
- return String(raw || "").replace(/^\s*(?:[-*•]+|\d+[.)])\s+/, "").replace(/\s+/g, " ").trim();
4448
+ var UNSYS_CONCEPT_LABEL_MAX = 8;
4449
+ var UNSYS_CONCEPT_LABEL_MAX_CHARS = 72;
4450
+ function unsysCanvasCleanConceptLabel(raw) {
4451
+ return String(raw || "").replace(/^\s*(?:[-*•]+|\d+[.)])\s+/, "").replace(/\s+/g, " ").trim();
4374
4452
  }
4375
4453
  function unsysCanvasTakeConceptLabels(items) {
4376
4454
  const out = [];
@@ -4562,6 +4640,13 @@ function applyUnsysCanvasAskReply(input) {
4562
4640
  if (text) {
4563
4641
  next = fanUnsysCanvasLabeledNodes(live, selected, [text], "ileSimplify").scene;
4564
4642
  }
4643
+ } else if (kind === "pretty") {
4644
+ const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
4645
+ const placed = placeUnsysCanvasPrettyReply(live, selected, {
4646
+ text,
4647
+ elements: input.payload.elements
4648
+ });
4649
+ if (placed.placed) next = placed.scene;
4565
4650
  } else if (kind === "concepts") {
4566
4651
  const labels = unsysCanvasConceptLabels(source, {
4567
4652
  text: input.payload.text,
@@ -4619,18 +4704,857 @@ function unsysCanvasAddedElementIds(before, after) {
4619
4704
  return ids;
4620
4705
  }
4621
4706
 
4622
- // src/lib/work-canvas/work-canvas-laser-gestures.ts
4623
- var LASER_DOUBLE_LINE_MS = 650;
4624
- var LASER_TARGET_PAD = 36;
4625
- var UNSYS_CANVAS_POINTER_LABEL = "pointer";
4626
- var UNSYS_CANVAS_POINTER_SHORTCUT = "k";
4627
- var UNSYS_CANVAS_POINTER_TOOLTIP = "Laser pointer. Click again to put it away. Shortcut K. Gestures: ? Simplify, line Concepts, two lines Subdivide.";
4628
- function unsysCanvasPointerToolActive(activeTool) {
4629
- if (typeof activeTool === "string") return activeTool.trim().toLowerCase() === "laser";
4630
- if (activeTool && typeof activeTool === "object" && !Array.isArray(activeTool)) {
4631
- return String(activeTool.type || "").trim().toLowerCase() === "laser";
4632
- }
4633
- return false;
4707
+ // src/lib/work-canvas/command-registry.ts
4708
+ var UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT = [
4709
+ "You sit beside the learner on a work canvas. Speak in complete, unhurried sentences. Be eloquent and plain.",
4710
+ "Answer the topic directly. Never mention canvas commands, origin, or placement.",
4711
+ "Never mention the host product, event names, or platform jargon.",
4712
+ "Write mathematics as LaTeX: $...$ inline and $$...$$ on its own line.",
4713
+ 'Reply as JSON with a "text" field. Do not put JSON or code fences inside "text".'
4714
+ ].join(" ");
4715
+ var UNSYS_CANVAS_MODEL_COMMAND_IDS = [
4716
+ "ask",
4717
+ "draw",
4718
+ "simplify",
4719
+ "concepts",
4720
+ "check",
4721
+ "selective-compress",
4722
+ "refactor",
4723
+ "suggest-insight",
4724
+ "clear-overlaps",
4725
+ "declutter"
4726
+ ];
4727
+ var CONTEXT_TEXT_MAX = 2e3;
4728
+ var CONTEXT_PROMPT_MAX = 4e3;
4729
+ var CONTEXT_SELECTED_MAX = 64;
4730
+ var CONTEXT_LIVE_MAX = 48;
4731
+ var CONTEXT_ID_MAX = 80;
4732
+ var ELEMENT_TYPES = /* @__PURE__ */ new Set([
4733
+ "text",
4734
+ "freedraw",
4735
+ "rectangle",
4736
+ "diamond",
4737
+ "ellipse",
4738
+ "arrow",
4739
+ "line",
4740
+ "image",
4741
+ "frame",
4742
+ "embeddable"
4743
+ ]);
4744
+ function finiteNumber(value) {
4745
+ const n = Number(value);
4746
+ return Number.isFinite(n) ? n : 0;
4747
+ }
4748
+ function clipText(value, max) {
4749
+ return String(value ?? "").replace(/\s+/g, " ").trim().slice(0, max);
4750
+ }
4751
+ function compactUnsysCanvasContextElement(el) {
4752
+ if (!el || typeof el !== "object") return null;
4753
+ const id = String(el.id || "").trim().slice(0, CONTEXT_ID_MAX);
4754
+ const type = String(el.type || "").trim().slice(0, 32);
4755
+ if (!id || !type || !ELEMENT_TYPES.has(type)) return null;
4756
+ const text = clipText(
4757
+ "originalText" in el ? el.originalText || el.text : el.text,
4758
+ CONTEXT_TEXT_MAX
4759
+ );
4760
+ const compact = {
4761
+ id,
4762
+ type,
4763
+ x: finiteNumber(el.x),
4764
+ y: finiteNumber(el.y)
4765
+ };
4766
+ if (el.width != null) compact.width = finiteNumber(el.width);
4767
+ if (el.height != null) compact.height = finiteNumber(el.height);
4768
+ if (text) compact.text = text;
4769
+ return compact;
4770
+ }
4771
+ function compactList(elements, max) {
4772
+ const out = [];
4773
+ for (const item of elements ?? []) {
4774
+ const compact = compactUnsysCanvasContextElement(item);
4775
+ if (!compact) continue;
4776
+ out.push(compact);
4777
+ if (out.length >= max) break;
4778
+ }
4779
+ return out;
4780
+ }
4781
+ function asSceneFromContext(context) {
4782
+ const live = context.liveElements?.length ? context.liveElements : context.selectedElements;
4783
+ return {
4784
+ elements: live,
4785
+ appState: {},
4786
+ files: {}
4787
+ };
4788
+ }
4789
+ function asSelectedFromContext(context) {
4790
+ return context.selectedElements;
4791
+ }
4792
+ function extractUnsysCanvasCommandContext(input) {
4793
+ const scene = input.scene ?? { elements: [], appState: {}, files: {} };
4794
+ const selected = expandUnsysCanvasCommandSelection(scene, input.selectedElements);
4795
+ const payload = {
4796
+ selectedElements: compactList(selected, CONTEXT_SELECTED_MAX)
4797
+ };
4798
+ if (unsysCanvasXaiNeedsBoardContext(input.commandId)) {
4799
+ payload.liveElements = compactList(
4800
+ (scene.elements ?? []).filter((el) => el && !el.isDeleted),
4801
+ CONTEXT_LIVE_MAX
4802
+ );
4803
+ }
4804
+ const prompt = clipText(input.prompt, CONTEXT_PROMPT_MAX);
4805
+ if (prompt) payload.prompt = prompt;
4806
+ if (input.workspace) payload.workspace = input.workspace;
4807
+ return payload;
4808
+ }
4809
+ function defaultParse(raw) {
4810
+ const parsed = parseUnsysCanvasAskReply(raw);
4811
+ const turn = parseUnsysCanvasCanvasTurn(raw);
4812
+ return {
4813
+ text: parsed.message,
4814
+ elements: parsed.canvasElements,
4815
+ origin: turn.origin ?? null,
4816
+ raw: parsed.raw
4817
+ };
4818
+ }
4819
+ function defaultBuildPrompt(commandId, context) {
4820
+ const kind = commandId;
4821
+ const scene = asSceneFromContext(context);
4822
+ const selected = asSelectedFromContext(context);
4823
+ const userText = [
4824
+ buildUnsysCanvasCommandUserMessage({
4825
+ kind,
4826
+ prompt: context.prompt,
4827
+ selectedElements: selected,
4828
+ workspace: context.workspace
4829
+ }),
4830
+ unsysCanvasXaiNeedsBoardContext(kind) ? unsysCanvasTurnContextMessage(scene, {
4831
+ boardLabel: context.boardLabel,
4832
+ workspace: context.workspace
4833
+ }) : ""
4834
+ ].filter(Boolean).join("\n\n");
4835
+ return {
4836
+ messages: [
4837
+ { role: "system", content: `${UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT} ${unsysCanvasXaiToolsInstruction()}` },
4838
+ { role: "user", content: userText }
4839
+ ],
4840
+ responseFormat: "json",
4841
+ maxTokens: unsysCanvasXaiMaxTokens(kind),
4842
+ timeoutMs: unsysCanvasXaiFetchTimeout(kind)
4843
+ };
4844
+ }
4845
+ var MODEL_KIND_LABEL = {
4846
+ ask: "Ask",
4847
+ check: "Check",
4848
+ "selective-compress": "Compress",
4849
+ "suggest-insight": "Suggest insight",
4850
+ "clear-overlaps": "Clear overlaps",
4851
+ declutter: "Declutter"
4852
+ };
4853
+ function hiddenModelDef(id) {
4854
+ return {
4855
+ id,
4856
+ label: MODEL_KIND_LABEL[id] ?? id,
4857
+ tooltip: MODEL_KIND_LABEL[id] ?? id,
4858
+ shortcut: "",
4859
+ needsSelection: id !== "ask",
4860
+ boardOnly: false,
4861
+ replacesSelection: id === "refactor" || id === "selective-compress",
4862
+ catalog: false,
4863
+ needsModel: true,
4864
+ placement: id === "refactor" || id === "selective-compress" ? "replace" : "beside",
4865
+ extractContext: (input) => extractUnsysCanvasCommandContext({
4866
+ commandId: id,
4867
+ scene: input.scene,
4868
+ selectedElements: input.selectedElements,
4869
+ prompt: input.prompt,
4870
+ workspace: input.workspace
4871
+ }),
4872
+ buildPrompt: (context) => defaultBuildPrompt(id, context),
4873
+ parseResponse: defaultParse
4874
+ };
4875
+ }
4876
+ function catalogDef(command) {
4877
+ const needsModel = command.id !== "breakdown";
4878
+ return {
4879
+ ...command,
4880
+ catalog: true,
4881
+ needsModel,
4882
+ placement: command.replacesSelection ? "replace" : "beside",
4883
+ extractContext: (input) => extractUnsysCanvasCommandContext({
4884
+ commandId: command.id,
4885
+ scene: input.scene,
4886
+ selectedElements: input.selectedElements,
4887
+ prompt: input.prompt,
4888
+ workspace: input.workspace
4889
+ }),
4890
+ buildPrompt: needsModel ? (context) => defaultBuildPrompt(command.id, context) : void 0,
4891
+ parseResponse: defaultParse
4892
+ };
4893
+ }
4894
+ var BUILTIN_BY_ID = /* @__PURE__ */ new Map();
4895
+ for (const command of UNSYS_CANVAS_COMMANDS) {
4896
+ BUILTIN_BY_ID.set(command.id, catalogDef(command));
4897
+ }
4898
+ for (const id of UNSYS_CANVAS_MODEL_COMMAND_IDS) {
4899
+ if (!BUILTIN_BY_ID.has(id)) BUILTIN_BY_ID.set(id, hiddenModelDef(id));
4900
+ }
4901
+ function extraToDefinition(extra) {
4902
+ const id = String(extra.id || "").trim();
4903
+ const needsModel = Boolean(extra.buildPrompt) || extra.needsModel === true;
4904
+ return {
4905
+ id,
4906
+ label: extra.label,
4907
+ tooltip: extra.tooltip ?? extra.label,
4908
+ shortcut: extra.shortcut ?? "",
4909
+ needsSelection: extra.needsSelection ?? false,
4910
+ boardOnly: false,
4911
+ replacesSelection: false,
4912
+ slash: extra.slash,
4913
+ run: extra.run,
4914
+ catalog: extra.catalog !== false,
4915
+ needsModel,
4916
+ placement: extra.placement ?? "beside",
4917
+ gesture: extra.gesture,
4918
+ gestureHint: extra.gestureHint,
4919
+ extractContext: extra.extractContext ?? ((input) => extractUnsysCanvasCommandContext({
4920
+ commandId: id,
4921
+ scene: input.scene,
4922
+ selectedElements: input.selectedElements,
4923
+ prompt: input.prompt,
4924
+ workspace: input.workspace
4925
+ })),
4926
+ buildPrompt: extra.buildPrompt,
4927
+ parseResponse: extra.parseResponse ?? defaultParse
4928
+ };
4929
+ }
4930
+ function listUnsysCanvasCommandDefinitions(extras = []) {
4931
+ const out = [...BUILTIN_BY_ID.values()];
4932
+ const seen = new Set(out.map((command) => command.id));
4933
+ for (const extra of extras) {
4934
+ const id = String(extra?.id || "").trim();
4935
+ if (!id || seen.has(id)) continue;
4936
+ seen.add(id);
4937
+ out.push(extraToDefinition(extra));
4938
+ }
4939
+ return out;
4940
+ }
4941
+ function getUnsysCanvasCommand(id, extras = []) {
4942
+ const key = String(id || "").trim();
4943
+ if (!key) return null;
4944
+ const extra = extras.find((command) => String(command?.id || "").trim() === key);
4945
+ if (extra) return extraToDefinition(extra);
4946
+ return BUILTIN_BY_ID.get(key) ?? null;
4947
+ }
4948
+ function isUnsysCanvasKnownCommandId(id, extras = []) {
4949
+ return getUnsysCanvasCommand(id, extras) != null;
4950
+ }
4951
+ function buildUnsysCanvasCommandPrompt(commandId, context, extras = []) {
4952
+ const command = getUnsysCanvasCommand(commandId, extras);
4953
+ if (!command) {
4954
+ throw new Error(`Unknown canvas command: ${commandId}`);
4955
+ }
4956
+ if (command.buildPrompt) return command.buildPrompt(context);
4957
+ return defaultBuildPrompt(commandId, context);
4958
+ }
4959
+ function parseUnsysCanvasCommandResponse(commandId, raw, extras = []) {
4960
+ const command = getUnsysCanvasCommand(commandId, extras);
4961
+ const parse = command?.parseResponse ?? defaultParse;
4962
+ return parse(raw);
4963
+ }
4964
+ function unsysCanvasCommandPlacement(id) {
4965
+ return String(id || "").trim() === "refactor" ? "replace" : "beside";
4966
+ }
4967
+ function unsysCanvasCommandEventInputs(input) {
4968
+ const selectedElementIds = (input.selectedElements ?? []).map((el) => String(el?.id || "").trim()).filter(Boolean);
4969
+ const prompt = String(input.prompt || "").trim();
4970
+ return prompt ? { selectedElementIds, prompt } : { selectedElementIds };
4971
+ }
4972
+ function unsysCanvasGestureCommandId(gesture) {
4973
+ const kind = String(gesture || "").trim();
4974
+ if (!kind) return null;
4975
+ for (const command of UNSYS_CANVAS_COMMANDS) {
4976
+ if (command.gesture === kind) return command.id;
4977
+ }
4978
+ return null;
4979
+ }
4980
+
4981
+ // src/lib/work-canvas/command-model.ts
4982
+ var INJECTION_KEYS = /* @__PURE__ */ new Set([
4983
+ "messages",
4984
+ "system",
4985
+ "user",
4986
+ "prompt",
4987
+ "thought",
4988
+ "instructions",
4989
+ "systemPrompt"
4990
+ ]);
4991
+ function asRecord2(value) {
4992
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
4993
+ return value;
4994
+ }
4995
+ function validateContext(raw, commandId) {
4996
+ const rec = asRecord2(raw);
4997
+ if (!rec) return { ok: false, error: "context is required" };
4998
+ for (const key of Object.keys(rec)) {
4999
+ if (INJECTION_KEYS.has(key) && key !== "prompt") {
5000
+ return { ok: false, error: "context contains disallowed fields" };
5001
+ }
5002
+ }
5003
+ if (rec.commandId != null && String(rec.commandId).trim() !== commandId) {
5004
+ return { ok: false, error: "context.commandId does not match commandId" };
5005
+ }
5006
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements.map(compactUnsysCanvasContextElement).filter(Boolean) : [];
5007
+ const live = Array.isArray(rec.liveElements) ? rec.liveElements.map(compactUnsysCanvasContextElement).filter(Boolean) : void 0;
5008
+ const prompt = typeof rec.prompt === "string" ? rec.prompt.replace(/\s+/g, " ").trim().slice(0, 4e3) : "";
5009
+ const boardLabel = typeof rec.boardLabel === "string" ? rec.boardLabel.trim().slice(0, 80) : void 0;
5010
+ const workspace = rec.workspace && typeof rec.workspace === "object" ? rec.workspace : void 0;
5011
+ const context = {
5012
+ selectedElements: selected
5013
+ };
5014
+ if (live?.length) context.liveElements = live;
5015
+ if (prompt) context.prompt = prompt;
5016
+ if (boardLabel) context.boardLabel = boardLabel;
5017
+ if (workspace) context.workspace = workspace;
5018
+ return { ok: true, context };
5019
+ }
5020
+ function parseUnsysCanvasModelClientBody(body, extras = []) {
5021
+ const rec = asRecord2(body);
5022
+ if (!rec) return { ok: false, status: 400, error: "JSON object required" };
5023
+ for (const key of ["messages", "system", "systemPrompt", "instructions", "user"]) {
5024
+ if (key in rec) {
5025
+ return { ok: false, status: 400, error: "Only commandId and context are allowed" };
5026
+ }
5027
+ }
5028
+ const commandId = String(rec.commandId || rec.canvasAskKind || "").trim();
5029
+ if (!commandId) return { ok: false, status: 400, error: "commandId is required" };
5030
+ if (!isUnsysCanvasKnownCommandId(commandId, extras)) {
5031
+ return { ok: false, status: 400, error: `Unknown command id: ${commandId}` };
5032
+ }
5033
+ const command = getUnsysCanvasCommand(commandId, extras);
5034
+ if (!command?.needsModel && !command?.buildPrompt) {
5035
+ return { ok: false, status: 400, error: `Command does not use a model: ${commandId}` };
5036
+ }
5037
+ let contextRaw = rec.context;
5038
+ if (!contextRaw) {
5039
+ contextRaw = {
5040
+ selectedElements: rec.selectedElements,
5041
+ liveElements: rec.liveElements,
5042
+ prompt: rec.thought ?? rec.prompt
5043
+ };
5044
+ }
5045
+ const context = validateContext(contextRaw, commandId);
5046
+ if (!context.ok) return { ok: false, status: 400, error: context.error };
5047
+ return { ok: true, commandId, context: context.context };
5048
+ }
5049
+ function buildUnsysCanvasModelRequest(input) {
5050
+ const extras = input.extras ?? [];
5051
+ const command = getUnsysCanvasCommand(input.commandId, extras);
5052
+ if (!command) {
5053
+ throw new Error(`Unknown canvas command: ${input.commandId}`);
5054
+ }
5055
+ const context = input.context ?? extractUnsysCanvasCommandContext({
5056
+ commandId: input.commandId,
5057
+ scene: input.scene,
5058
+ selectedElements: input.selectedElements,
5059
+ prompt: input.prompt,
5060
+ workspace: input.workspace
5061
+ });
5062
+ const built = buildUnsysCanvasCommandPrompt(input.commandId, context, extras);
5063
+ return {
5064
+ commandId: input.commandId,
5065
+ messages: built.messages,
5066
+ responseFormat: built.responseFormat,
5067
+ jsonSchema: built.jsonSchema,
5068
+ maxTokens: built.maxTokens,
5069
+ timeoutMs: built.timeoutMs,
5070
+ signal: input.signal,
5071
+ context
5072
+ };
5073
+ }
5074
+ async function handleCanvasModelRequest(body, options) {
5075
+ const parsed = parseUnsysCanvasModelClientBody(body, options.extras);
5076
+ if (!parsed.ok) return parsed;
5077
+ try {
5078
+ const request = buildUnsysCanvasModelRequest({
5079
+ commandId: parsed.commandId,
5080
+ context: parsed.context,
5081
+ extras: options.extras,
5082
+ signal: options.signal
5083
+ });
5084
+ const result = await options.runModel(request);
5085
+ const text = String(result?.text ?? "");
5086
+ const reply = parseUnsysCanvasCommandResponse(parsed.commandId, text, options.extras);
5087
+ return { ok: true, ...reply };
5088
+ } catch (error) {
5089
+ const message = error instanceof Error ? error.message : "Canvas model failed";
5090
+ return { ok: false, status: 500, error: message };
5091
+ }
5092
+ }
5093
+ async function handleCanvasModelHttpRequest(req, options) {
5094
+ const body = await req.json().catch(() => null);
5095
+ const result = await handleCanvasModelRequest(body, {
5096
+ runModel: options.runModel,
5097
+ extras: options.extras,
5098
+ signal: req.signal
5099
+ });
5100
+ if (!result.ok) {
5101
+ return Response.json(
5102
+ { error: { message: result.error } },
5103
+ { status: result.status }
5104
+ );
5105
+ }
5106
+ return Response.json({
5107
+ message: result.text,
5108
+ canvasElements: result.elements,
5109
+ raw: result.raw
5110
+ });
5111
+ }
5112
+ function choiceContent(data) {
5113
+ const choices = Array.isArray(data.choices) ? data.choices : [];
5114
+ const first = choices[0];
5115
+ if (!first || typeof first !== "object") return "";
5116
+ const message = first.message;
5117
+ const content = message?.content;
5118
+ if (typeof content === "string") return content;
5119
+ if (Array.isArray(content)) {
5120
+ return content.map((part) => part && typeof part === "object" && "text" in part ? String(part.text || "") : "").filter(Boolean).join("\n");
5121
+ }
5122
+ return "";
5123
+ }
5124
+ function modelSendsReasoningEffort(model) {
5125
+ const id = model.toLowerCase();
5126
+ if (!id || id.includes("non-reasoning")) return false;
5127
+ return /^grok-4\.(5|6|7)/.test(id) || id.includes("grok-4.20") && id.includes("reasoning");
5128
+ }
5129
+ function createUnsysCanvasXaiBrowserRunner(options) {
5130
+ const fetchImpl = options.fetch ?? fetch;
5131
+ return async (request) => {
5132
+ const apiKey = String(await options.getApiKey() || "").trim();
5133
+ if (!apiKey) {
5134
+ throw new Error("No API key.");
5135
+ }
5136
+ const baseURL = String(await options.getBaseUrl?.() || "").replace(/\/+$/, "") || "https://api.x.ai/v1";
5137
+ const model = typeof options.model === "function" ? options.model(request.commandId) : options.model || "grok-4.7";
5138
+ const timeout = request.timeoutMs || 6e4;
5139
+ const signal = request.signal ?? AbortSignal.timeout(timeout);
5140
+ const body = {
5141
+ model,
5142
+ messages: request.messages,
5143
+ max_tokens: request.maxTokens,
5144
+ temperature: 0.55
5145
+ };
5146
+ if (request.responseFormat === "json") {
5147
+ body.response_format = { type: "json_object" };
5148
+ } else if (request.responseFormat === "json_schema" && request.jsonSchema) {
5149
+ body.response_format = { type: "json_schema", json_schema: request.jsonSchema };
5150
+ }
5151
+ if (modelSendsReasoningEffort(model)) {
5152
+ body.reasoning_effort = options.reasoningEffort ?? "low";
5153
+ }
5154
+ const response = await fetchImpl(`${baseURL}/chat/completions`, {
5155
+ method: "POST",
5156
+ headers: {
5157
+ Authorization: `Bearer ${apiKey}`,
5158
+ "Content-Type": "application/json"
5159
+ },
5160
+ body: JSON.stringify(body),
5161
+ signal
5162
+ });
5163
+ const data = await response.json().catch(() => ({}));
5164
+ if (!response.ok) {
5165
+ const err = data.error;
5166
+ const message = typeof err === "string" ? err : err && typeof err === "object" && "message" in err ? String(err.message || "") : "";
5167
+ throw new Error(message.trim() || `Canvas model failed (${response.status})`);
5168
+ }
5169
+ const text = choiceContent(data).trim();
5170
+ if (!text) throw new Error("Canvas chat returned an empty reply.");
5171
+ return { text };
5172
+ };
5173
+ }
5174
+ function createUnsysCanvasModelProxyRunner(options) {
5175
+ const fetchImpl = options.fetch ?? fetch;
5176
+ return async (request) => {
5177
+ const headers = {
5178
+ "Content-Type": "application/json",
5179
+ ...options.headers ? await options.headers() : {}
5180
+ };
5181
+ const response = await fetchImpl(options.url, {
5182
+ method: "POST",
5183
+ headers,
5184
+ body: JSON.stringify({
5185
+ commandId: request.commandId,
5186
+ context: request.context
5187
+ }),
5188
+ signal: request.signal ?? AbortSignal.timeout(request.timeoutMs || 6e4)
5189
+ });
5190
+ const data = await response.json().catch(() => ({}));
5191
+ if (!response.ok) {
5192
+ const err = asRecord2(data.error);
5193
+ const message = err && typeof err.message === "string" && err.message || (typeof data.error === "string" ? data.error : "") || `Canvas model failed (${response.status})`;
5194
+ throw new Error(message);
5195
+ }
5196
+ const raw = typeof data.raw === "string" && data.raw.trim() ? data.raw : typeof data.message === "string" ? data.message : "";
5197
+ if (!raw.trim()) throw new Error("Canvas chat returned an empty reply.");
5198
+ return { text: raw };
5199
+ };
5200
+ }
5201
+ async function runUnsysCanvasModelAsk(runModel, input) {
5202
+ const request = buildUnsysCanvasModelRequest(input);
5203
+ const result = await runModel(request);
5204
+ return parseUnsysCanvasCommandResponse(input.commandId, result.text, input.extras);
5205
+ }
5206
+
5207
+ // src/lib/events.ts
5208
+ var UNSYS_CANVAS_EVENT_TYPES = [
5209
+ "element:added",
5210
+ "element:updated",
5211
+ "element:deleted",
5212
+ "element:moved",
5213
+ "element:resized",
5214
+ "text:edited",
5215
+ "selection:changed",
5216
+ "tool:changed",
5217
+ "viewport:changed",
5218
+ "command:run",
5219
+ "command:complete",
5220
+ "prompt:submit",
5221
+ "dictate:start",
5222
+ "dictate:stop",
5223
+ "dictate:text",
5224
+ "laser:gesture",
5225
+ "latex:render",
5226
+ "undo",
5227
+ "redo"
5228
+ ];
5229
+ var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
5230
+ var HIGH_FREQ = /* @__PURE__ */ new Set([
5231
+ "viewport:changed",
5232
+ "element:moved",
5233
+ "element:resized",
5234
+ "element:updated",
5235
+ "text:edited"
5236
+ ]);
5237
+ function asRecord3(value) {
5238
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
5239
+ return value;
5240
+ }
5241
+ function elementMap(elements) {
5242
+ const map = /* @__PURE__ */ new Map();
5243
+ for (const el of elements) {
5244
+ if (el && typeof el.id === "string") map.set(el.id, el);
5245
+ }
5246
+ return map;
5247
+ }
5248
+ function changedProps(prev, next) {
5249
+ const changed = {};
5250
+ const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
5251
+ for (const key of keys) {
5252
+ if (SKIP_KEYS.has(key)) continue;
5253
+ const from = prev?.[key];
5254
+ const to = next[key];
5255
+ if (JSON.stringify(from) !== JSON.stringify(to)) {
5256
+ changed[key] = { from, to };
5257
+ }
5258
+ }
5259
+ return changed;
5260
+ }
5261
+ function selectedIds(appState) {
5262
+ const raw = asRecord3(appState.selectedElementIds);
5263
+ return Object.keys(raw).filter((id) => raw[id]);
5264
+ }
5265
+ function zoomValue(appState) {
5266
+ const zoom = appState.zoom;
5267
+ if (zoom && typeof zoom === "object" && "value" in zoom) {
5268
+ return Number(zoom.value) || 1;
5269
+ }
5270
+ return Number(zoom) || 1;
5271
+ }
5272
+ function toolName(appState) {
5273
+ const tool = appState.activeTool;
5274
+ if (typeof tool === "string") return tool;
5275
+ if (tool && typeof tool === "object" && "type" in tool) {
5276
+ return String(tool.type || "") || null;
5277
+ }
5278
+ return null;
5279
+ }
5280
+ function snapshot(scene) {
5281
+ const rec = asRecord3(scene);
5282
+ const elements = Array.isArray(rec.elements) ? rec.elements : [];
5283
+ return {
5284
+ elements,
5285
+ appState: asRecord3(rec.appState),
5286
+ files: asRecord3(rec.files)
5287
+ };
5288
+ }
5289
+ function eventKey(event) {
5290
+ const id = typeof event.payload.id === "string" ? event.payload.id : "";
5291
+ return `${event.type}:${id}`;
5292
+ }
5293
+ function mergePayload(prev, next) {
5294
+ const merged = { ...prev, ...next };
5295
+ if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
5296
+ if ("to" in next) merged.to = next.to;
5297
+ if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
5298
+ const a = prev.changed;
5299
+ const b = next.changed;
5300
+ const changed = { ...a };
5301
+ for (const [key, value] of Object.entries(b)) {
5302
+ const earlier = a[key];
5303
+ changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
5304
+ }
5305
+ merged.changed = changed;
5306
+ }
5307
+ return merged;
5308
+ }
5309
+ var UnsysCanvasEventCollector = class {
5310
+ constructor(options) {
5311
+ this.seq = 0;
5312
+ this.prev = null;
5313
+ this.buffer = [];
5314
+ this.lastFlush = 0;
5315
+ this.batchMs = options?.batchMs ?? 0;
5316
+ }
5317
+ reset(scene) {
5318
+ this.prev = snapshot(scene);
5319
+ this.seq = 0;
5320
+ this.buffer = [];
5321
+ this.lastFlush = 0;
5322
+ }
5323
+ syncWithoutEmit(scene) {
5324
+ this.prev = snapshot(scene);
5325
+ }
5326
+ push(type, payload) {
5327
+ this.seq += 1;
5328
+ return { seq: this.seq, ts: Date.now(), type, payload };
5329
+ }
5330
+ observeScene(scene, _opts) {
5331
+ const next = snapshot(scene);
5332
+ const prev = this.prev ?? { elements: [], appState: {}};
5333
+ const events = [];
5334
+ const prevEls = elementMap(prev.elements);
5335
+ const nextEls = elementMap(next.elements);
5336
+ for (const [id, el] of nextEls) {
5337
+ const before = prevEls.get(id);
5338
+ const deleted = Boolean(el.isDeleted);
5339
+ const wasDeleted = Boolean(before?.isDeleted);
5340
+ if (!before || wasDeleted && !deleted) {
5341
+ if (!deleted) {
5342
+ events.push(
5343
+ this.push("element:added", {
5344
+ id,
5345
+ type: el.type,
5346
+ element: el
5347
+ })
5348
+ );
5349
+ }
5350
+ continue;
5351
+ }
5352
+ if (!wasDeleted && deleted) {
5353
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
5354
+ continue;
5355
+ }
5356
+ if (deleted) continue;
5357
+ const changed = changedProps(before, el);
5358
+ if (!Object.keys(changed).length) continue;
5359
+ events.push(
5360
+ this.push("element:updated", {
5361
+ id,
5362
+ type: el.type,
5363
+ changed
5364
+ })
5365
+ );
5366
+ if ("x" in changed || "y" in changed) {
5367
+ events.push(
5368
+ this.push("element:moved", {
5369
+ id,
5370
+ type: el.type,
5371
+ from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
5372
+ to: { x: el.x, y: el.y }
5373
+ })
5374
+ );
5375
+ }
5376
+ if ("width" in changed || "height" in changed) {
5377
+ events.push(
5378
+ this.push("element:resized", {
5379
+ id,
5380
+ type: el.type,
5381
+ from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
5382
+ to: { width: el.width, height: el.height }
5383
+ })
5384
+ );
5385
+ }
5386
+ if ("text" in changed || "originalText" in changed) {
5387
+ events.push(
5388
+ this.push("text:edited", {
5389
+ id,
5390
+ type: el.type,
5391
+ from: changed.text?.from ?? changed.originalText?.from ?? before.text,
5392
+ to: el.text ?? el.originalText
5393
+ })
5394
+ );
5395
+ }
5396
+ }
5397
+ for (const [id, el] of prevEls) {
5398
+ if (nextEls.has(id)) continue;
5399
+ if (el.isDeleted) continue;
5400
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
5401
+ }
5402
+ const prevSel = selectedIds(prev.appState);
5403
+ const nextSel = selectedIds(next.appState);
5404
+ if (prevSel.join(",") !== nextSel.join(",")) {
5405
+ events.push(this.push("selection:changed", { from: prevSel, to: nextSel }));
5406
+ }
5407
+ const prevTool = toolName(prev.appState);
5408
+ const nextTool = toolName(next.appState);
5409
+ if (prevTool !== nextTool) {
5410
+ events.push(this.push("tool:changed", { from: prevTool, to: nextTool }));
5411
+ }
5412
+ const prevView = {
5413
+ zoom: zoomValue(prev.appState),
5414
+ scrollX: Number(prev.appState.scrollX) || 0,
5415
+ scrollY: Number(prev.appState.scrollY) || 0
5416
+ };
5417
+ const nextView = {
5418
+ zoom: zoomValue(next.appState),
5419
+ scrollX: Number(next.appState.scrollX) || 0,
5420
+ scrollY: Number(next.appState.scrollY) || 0
5421
+ };
5422
+ if (prevView.zoom !== nextView.zoom || prevView.scrollX !== nextView.scrollX || prevView.scrollY !== nextView.scrollY) {
5423
+ events.push(this.push("viewport:changed", { from: prevView, to: nextView }));
5424
+ }
5425
+ this.prev = next;
5426
+ return this.batch(events);
5427
+ }
5428
+ command(id, meta) {
5429
+ const rec = asRecord3(meta);
5430
+ const inputs = asRecord3(rec.inputs);
5431
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements : [];
5432
+ const selectedElementIds = Array.isArray(inputs.selectedElementIds) ? inputs.selectedElementIds : selected.map((el) => el && typeof el === "object" && "id" in el ? String(el.id || "") : "").filter(Boolean);
5433
+ const prompt = typeof inputs.prompt === "string" ? inputs.prompt : typeof rec.prompt === "string" ? rec.prompt : void 0;
5434
+ const eventInputs = prompt ? { selectedElementIds, prompt } : { selectedElementIds };
5435
+ return [
5436
+ this.push("command:run", {
5437
+ id: id ?? null,
5438
+ args: rec,
5439
+ inputs: eventInputs,
5440
+ outputs: rec.outputs ?? null
5441
+ })
5442
+ ];
5443
+ }
5444
+ commandComplete(id, meta) {
5445
+ const rec = asRecord3(meta);
5446
+ return [
5447
+ this.push("command:complete", {
5448
+ id: id ?? null,
5449
+ inputs: rec.inputs ?? {},
5450
+ outputs: rec.outputs ?? {}
5451
+ })
5452
+ ];
5453
+ }
5454
+ dictate(meta) {
5455
+ const rec = asRecord3(meta);
5456
+ const type = rec.phase === "start" ? "dictate:start" : rec.phase === "stop" ? "dictate:stop" : "dictate:text";
5457
+ return [this.push(type, rec)];
5458
+ }
5459
+ prompt(text, meta) {
5460
+ return [this.push("prompt:submit", { text: text ?? "", ...asRecord3(meta) })];
5461
+ }
5462
+ laser(meta) {
5463
+ return [this.push("laser:gesture", asRecord3(meta))];
5464
+ }
5465
+ latex(meta) {
5466
+ return [this.push("latex:render", asRecord3(meta))];
5467
+ }
5468
+ history(kind, meta) {
5469
+ return [this.push(kind, asRecord3(meta))];
5470
+ }
5471
+ markGestureBusy(_busy) {
5472
+ }
5473
+ batch(incoming) {
5474
+ const now = Date.now();
5475
+ if (!this.buffer.length) this.lastFlush = now;
5476
+ for (const event of incoming) {
5477
+ const last = this.buffer[this.buffer.length - 1];
5478
+ if (last && HIGH_FREQ.has(event.type) && eventKey(last) === eventKey(event)) {
5479
+ this.buffer[this.buffer.length - 1] = {
5480
+ ...event,
5481
+ seq: last.seq,
5482
+ ts: last.ts,
5483
+ payload: mergePayload(last.payload, event.payload)
5484
+ };
5485
+ } else {
5486
+ this.buffer.push(event);
5487
+ }
5488
+ }
5489
+ if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
5490
+ return [];
5491
+ }
5492
+ const flushed = this.buffer;
5493
+ this.buffer = [];
5494
+ this.lastFlush = now;
5495
+ return flushed;
5496
+ }
5497
+ flush() {
5498
+ const flushed = this.buffer;
5499
+ this.buffer = [];
5500
+ this.lastFlush = Date.now();
5501
+ return flushed;
5502
+ }
5503
+ };
5504
+ function unsysCanvasGestureBusy(_opts) {
5505
+ return false;
5506
+ }
5507
+
5508
+ // src/lib/work-canvas/work-canvas-laser-gestures.ts
5509
+ var LASER_DOUBLE_LINE_MS = 650;
5510
+ var LASER_TARGET_PAD = 36;
5511
+ var UNSYS_CANVAS_POINTER_LABEL = "pointer";
5512
+ var UNSYS_CANVAS_POINTER_SHORTCUT = "k";
5513
+ var UNSYS_CANVAS_POINTER_TOOLTIP = "Laser pointer. Click again to put it away. Shortcut K. Gestures: ? Simplify, line Concepts, two lines Subdivide, loop Do/run, zigzag Refactor, check Pretty.";
5514
+ var UNSYS_CANVAS_LASER_GESTURES = [
5515
+ {
5516
+ command: "simplify",
5517
+ label: "Simplify",
5518
+ gesture: "Question mark",
5519
+ hint: "Draw a question mark over a mark."
5520
+ },
5521
+ {
5522
+ command: "concepts",
5523
+ label: "Concepts",
5524
+ gesture: "Line",
5525
+ hint: "Draw a line from a mark into empty space."
5526
+ },
5527
+ {
5528
+ command: "breakdown",
5529
+ label: "Subdivide",
5530
+ gesture: "Two lines",
5531
+ hint: "Draw two quick lines from a mark into empty space."
5532
+ },
5533
+ {
5534
+ command: "draw",
5535
+ label: "Do/run",
5536
+ gesture: "Loop",
5537
+ hint: "Draw a circle or loop over a mark."
5538
+ },
5539
+ {
5540
+ command: "refactor",
5541
+ label: "Refactor",
5542
+ gesture: "Zigzag",
5543
+ hint: "Draw a zigzag over a mark."
5544
+ },
5545
+ {
5546
+ command: "pretty",
5547
+ label: "Pretty",
5548
+ gesture: "Check mark",
5549
+ hint: "Draw a check mark over a mark."
5550
+ }
5551
+ ];
5552
+ function unsysCanvasPointerToolActive(activeTool) {
5553
+ if (typeof activeTool === "string") return activeTool.trim().toLowerCase() === "laser";
5554
+ if (activeTool && typeof activeTool === "object" && !Array.isArray(activeTool)) {
5555
+ return String(activeTool.type || "").trim().toLowerCase() === "laser";
5556
+ }
5557
+ return false;
4634
5558
  }
4635
5559
  function unsysCanvasPointerNextTool(active) {
4636
5560
  return { type: active ? "selection" : "laser" };
@@ -4710,6 +5634,29 @@ function resample(points, count) {
4710
5634
  if (out.length < count) out.push(live[live.length - 1]);
4711
5635
  return out;
4712
5636
  }
5637
+ function axisReversals(samples, axis) {
5638
+ let prevSign = 0;
5639
+ let reversals = 0;
5640
+ for (let i = 1; i < samples.length; i += 1) {
5641
+ const delta = samples[i][axis] - samples[i - 1][axis];
5642
+ if (Math.abs(delta) < 2) continue;
5643
+ const sign = delta > 0 ? 1 : -1;
5644
+ if (prevSign && sign !== prevSign) reversals += 1;
5645
+ prevSign = sign;
5646
+ }
5647
+ return reversals;
5648
+ }
5649
+ function valleyIndex(samples) {
5650
+ let best = 0;
5651
+ let y = -Infinity;
5652
+ for (let i = 0; i < samples.length; i += 1) {
5653
+ if (samples[i].y > y) {
5654
+ y = samples[i].y;
5655
+ best = i;
5656
+ }
5657
+ }
5658
+ return best;
5659
+ }
4713
5660
  function classifyLaserStroke(points) {
4714
5661
  const samples = resample(points, 24);
4715
5662
  if (samples.length < 6) return "unknown";
@@ -4727,6 +5674,20 @@ function classifyLaserStroke(points) {
4727
5674
  const startY = (start.y - box.minY) / height;
4728
5675
  const endY = (end.y - box.minY) / height;
4729
5676
  const aspect = height / width;
5677
+ const diag = Math.hypot(width, height);
5678
+ const closed = diag > 0 && span / diag <= 0.42;
5679
+ if (closed && turns >= 4.2 && aspect >= 0.45 && aspect <= 2.2 && length >= diag * 1.55) {
5680
+ return "loop";
5681
+ }
5682
+ const valleyAt = valleyIndex(samples);
5683
+ const valleyT = valleyAt / Math.max(1, samples.length - 1);
5684
+ const valleyRel = (samples[valleyAt].y - box.minY) / height;
5685
+ const check = !closed && end.x > start.x + 8 && valleyT >= 0.15 && valleyT <= 0.72 && valleyRel >= 0.55 && endY <= 0.45 && startY <= valleyRel - 0.12 && turns >= 0.7 && turns <= 3.6 && straightness < 0.78 && samples[valleyAt].y - start.y > 8 && end.y - samples[valleyAt].y < -8;
5686
+ if (check) return "check";
5687
+ const reversals = Math.max(axisReversals(samples, "x"), axisReversals(samples, "y"));
5688
+ if (!closed && reversals >= 2 && turns >= 2.4 && straightness < 0.72 && span / diag >= 0.28) {
5689
+ return "zigzag";
5690
+ }
4730
5691
  const first = samples.slice(0, Math.max(4, Math.floor(samples.length * 0.45)));
4731
5692
  const last = samples.slice(Math.floor(samples.length * 0.65));
4732
5693
  const meanX = (pts) => pts.reduce((s, p) => s + p.x, 0) / Math.max(1, pts.length);
@@ -4825,12 +5786,13 @@ function finishLaserStroke(input) {
4825
5786
  if (kind === "unknown") {
4826
5787
  return { session: pendingDue.session, fire: pendingDue.fire, waitMs: null };
4827
5788
  }
4828
- if (kind === "question-mark") {
5789
+ if (kind === "question-mark" || kind === "loop" || kind === "zigzag" || kind === "check") {
4829
5790
  const target2 = targetForQuestion(input.elements, input.stroke);
4830
5791
  if (!target2) return { session: pendingDue.session, fire: pendingDue.fire, waitMs: null };
5792
+ const command = kind === "question-mark" ? "simplify" : kind === "loop" ? "draw" : kind === "zigzag" ? "refactor" : "pretty";
4831
5793
  return {
4832
5794
  session: { pending: null },
4833
- fire: { command: "simplify", targetId: target2.id },
5795
+ fire: { command, targetId: target2.id },
4834
5796
  waitMs: null
4835
5797
  };
4836
5798
  }
@@ -4888,6 +5850,17 @@ function openCanvasScene(scene, scrollToContent, chrome) {
4888
5850
  return scrollToContent ? unsysCanvasWithScrollToContent(next) : next;
4889
5851
  }
4890
5852
 
5853
+ // src/lib/require-onask.ts
5854
+ function assertOnAsk(onAsk) {
5855
+ if (typeof onAsk !== "function") {
5856
+ throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
5857
+ }
5858
+ }
5859
+ function assertCanvasModel(input) {
5860
+ if (typeof input.runModel === "function" || typeof input.onAsk === "function") return;
5861
+ throw new Error("UnsysCanvas requires a runModel or onAsk handler; the package does not call any LLM.");
5862
+ }
5863
+
4891
5864
  // src/components/excalidraw-canvas/excalidraw-api.ts
4892
5865
  function liveSceneElements(api) {
4893
5866
  if (!api) return [];
@@ -5866,6 +6839,20 @@ function useWorkCanvasCommands(input) {
5866
6839
  appState: api.getAppState() ?? {},
5867
6840
  files: api.getFiles() ?? {}
5868
6841
  });
6842
+ emitCanvasEventsRef.current(
6843
+ canvasEventCollectorRef.current.commandComplete(askInput.kind ?? "ask", {
6844
+ inputs: unsysCanvasCommandEventInputs({
6845
+ commandId: String(askInput.kind || "ask"),
6846
+ selectedElements: askInput.selectedElements,
6847
+ prompt: askInput.prompt
6848
+ }),
6849
+ outputs: {
6850
+ ok: true,
6851
+ text: payload.text,
6852
+ addedElementIds: [...addedIds]
6853
+ }
6854
+ })
6855
+ );
5869
6856
  };
5870
6857
  try {
5871
6858
  const scene = liveWorkCanvasScene(api);
@@ -5933,7 +6920,12 @@ function useWorkCanvasCommands(input) {
5933
6920
  if (extra?.run) {
5934
6921
  const live2 = liveWorkCanvasScene(api);
5935
6922
  emitCanvasEventsRef.current(
5936
- canvasEventCollectorRef.current.command(action, { extra: true, selectedElements: selected })
6923
+ canvasEventCollectorRef.current.command(action, {
6924
+ extra: true,
6925
+ selectedElements: selected,
6926
+ inputs: unsysCanvasCommandEventInputs({ selectedElements: selected }),
6927
+ outputs: { local: true }
6928
+ })
5937
6929
  );
5938
6930
  void extra.run({ selectedElements: selected, scene: live2 });
5939
6931
  return;
@@ -5946,9 +6938,19 @@ function useWorkCanvasCommands(input) {
5946
6938
  scene: live,
5947
6939
  selectedElements: selected});
5948
6940
  const emitCommand = (commandId, prompt) => {
6941
+ const inputs = unsysCanvasCommandEventInputs({
6942
+ selectedElements: outcome.selected,
6943
+ prompt
6944
+ });
5949
6945
  const powEvents = canvasEventCollectorRef.current.command(commandId, {
5950
6946
  prompt,
5951
- selectedElements: outcome.selected
6947
+ selectedElements: outcome.selected,
6948
+ inputs,
6949
+ outputs: {
6950
+ askKind: outcome.ask?.kind ?? null,
6951
+ local: !outcome.ask,
6952
+ notice: outcome.notice
6953
+ }
5952
6954
  });
5953
6955
  emitCanvasEventsRef.current(powEvents);
5954
6956
  };
@@ -6341,85 +7343,921 @@ function WorkCanvasLatexLayer({
6341
7343
  mount
6342
7344
  );
6343
7345
  }
6344
- var LASER_ICON = /* @__PURE__ */ jsxs("svg", { "aria-hidden": "true", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [
6345
- /* @__PURE__ */ jsx("path", { d: "M6.2 11.8a5.3 5.3 0 1 1 5.3-5.3l8.8 8.8a3.3 3.3 0 0 1-4.7 4.7z" }),
6346
- /* @__PURE__ */ jsx("path", { d: "m14.2 14.2 3.3 3.3M11 11.6l2 2M6.2 6.2l3 3" })
6347
- ] });
6348
- function UnsysLaserToolbarSlot({
6349
- hostRef,
6350
- apiRef,
6351
- active,
6352
- onToggle
6353
- }) {
6354
- const [slot, setSlot] = useState(null);
6355
- useLayoutEffect(() => {
6356
- const host = hostRef.current;
6357
- if (!host) return;
6358
- let node = host.querySelector("[data-unsys-canvas-toolbar-laser-slot]");
6359
- const place = () => {
6360
- const toolbar = host.querySelector(".App-toolbar");
6361
- if (!toolbar) return;
6362
- if (!node) {
6363
- node = document.createElement("div");
6364
- node.setAttribute("data-unsys-canvas-toolbar-laser-slot", "");
6365
- node.style.display = "contents";
7346
+ var LASER_ICON = /* @__PURE__ */ jsxs("svg", { "aria-hidden": "true", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [
7347
+ /* @__PURE__ */ jsx("path", { d: "M6.2 11.8a5.3 5.3 0 1 1 5.3-5.3l8.8 8.8a3.3 3.3 0 0 1-4.7 4.7z" }),
7348
+ /* @__PURE__ */ jsx("path", { d: "m14.2 14.2 3.3 3.3M11 11.6l2 2M6.2 6.2l3 3" })
7349
+ ] });
7350
+ function UnsysLaserToolbarSlot({
7351
+ hostRef,
7352
+ apiRef,
7353
+ active,
7354
+ onToggle
7355
+ }) {
7356
+ const [slot, setSlot] = useState(null);
7357
+ useLayoutEffect(() => {
7358
+ const host = hostRef.current;
7359
+ if (!host) return;
7360
+ let node = host.querySelector("[data-unsys-canvas-toolbar-laser-slot]");
7361
+ const place = () => {
7362
+ const toolbar = host.querySelector(".App-toolbar");
7363
+ if (!toolbar) return;
7364
+ if (!node) {
7365
+ node = document.createElement("div");
7366
+ node.setAttribute("data-unsys-canvas-toolbar-laser-slot", "");
7367
+ node.style.display = "contents";
7368
+ }
7369
+ const divider = toolbar.querySelector(".App-toolbar__divider");
7370
+ if (divider && node.nextSibling !== divider && node.parentElement !== toolbar) {
7371
+ toolbar.insertBefore(node, divider);
7372
+ } else if (!node.parentElement) {
7373
+ toolbar.appendChild(node);
7374
+ }
7375
+ setSlot((prev) => prev === node ? prev : node);
7376
+ };
7377
+ place();
7378
+ let raf = 0;
7379
+ const schedule = () => {
7380
+ if (raf) return;
7381
+ raf = window.requestAnimationFrame(() => {
7382
+ raf = 0;
7383
+ place();
7384
+ });
7385
+ };
7386
+ let observed = null;
7387
+ const observer = new MutationObserver(() => {
7388
+ schedule();
7389
+ attach();
7390
+ });
7391
+ const attach = () => {
7392
+ const toolbar = host.querySelector(".App-toolbar");
7393
+ const target = toolbar ?? host;
7394
+ if (observed === target) return;
7395
+ observer.disconnect();
7396
+ observed = target;
7397
+ observer.observe(target, {
7398
+ childList: true,
7399
+ subtree: target === host
7400
+ });
7401
+ };
7402
+ attach();
7403
+ return () => {
7404
+ observer.disconnect();
7405
+ if (raf) window.cancelAnimationFrame(raf);
7406
+ node?.remove();
7407
+ };
7408
+ }, [hostRef]);
7409
+ if (!slot) return null;
7410
+ return createPortal(
7411
+ /* @__PURE__ */ jsx(
7412
+ "button",
7413
+ {
7414
+ type: "button",
7415
+ "data-unsys-canvas-toolbar-laser": true,
7416
+ className: `ToolIcon ToolIcon_type_toggle${active ? " ToolIcon--checked" : ""}`,
7417
+ title: "Laser pointer \u2014 K",
7418
+ "aria-label": "Laser pointer",
7419
+ "aria-pressed": active ? "true" : "false",
7420
+ onClick: () => onToggle ? onToggle() : setLiveActiveTool(apiRef.current, { type: "laser" }),
7421
+ children: /* @__PURE__ */ jsx("div", { className: "ToolIcon__icon", children: LASER_ICON })
7422
+ }
7423
+ ),
7424
+ slot
7425
+ );
7426
+ }
7427
+
7428
+ // src/lib/work-canvas/work-canvas-url.ts
7429
+ var UNSYS_CANVAS_HASH_PREFIX = "tc1.";
7430
+ var UNSYS_CANVAS_MAX_HASH_LENGTH = 75e4;
7431
+ function unsysCanvasUrlSnapshot(scene) {
7432
+ const serialized = serializeUnsysCanvasScene(scene);
7433
+ const elements = serialized.elements.filter((el) => el && !el.isDeleted);
7434
+ const usedFileIds = new Set(
7435
+ elements.map((el) => typeof el.fileId === "string" ? el.fileId : "").filter(Boolean)
7436
+ );
7437
+ const files = {};
7438
+ for (const [id, file] of Object.entries(serialized.files || {})) {
7439
+ if (usedFileIds.has(id)) files[id] = file;
7440
+ }
7441
+ return {
7442
+ elements,
7443
+ appState: serialized.appState,
7444
+ files
7445
+ };
7446
+ }
7447
+ async function encodeUnsysCanvasHash(scene, options) {
7448
+ const maxHashLength = options?.maxHashLength ?? UNSYS_CANVAS_MAX_HASH_LENGTH;
7449
+ const snapshot2 = unsysCanvasUrlSnapshot(scene);
7450
+ if (!unsysCanvasHasLiveElements(snapshot2)) {
7451
+ return { kind: "empty", hash: "" };
7452
+ }
7453
+ const withFiles = await hashFromPayload({
7454
+ v: 1,
7455
+ elements: snapshot2.elements,
7456
+ appState: snapshot2.appState,
7457
+ files: Object.keys(snapshot2.files).length ? snapshot2.files : void 0
7458
+ });
7459
+ if (withFiles && withFiles.length <= maxHashLength) {
7460
+ return { kind: "ok", hash: withFiles };
7461
+ }
7462
+ const withoutFiles = await hashFromPayload({
7463
+ v: 1,
7464
+ elements: snapshot2.elements,
7465
+ appState: snapshot2.appState
7466
+ });
7467
+ if (withoutFiles && withoutFiles.length <= maxHashLength) {
7468
+ return { kind: "omitted-files", hash: withoutFiles };
7469
+ }
7470
+ return { kind: "too-large", hash: "" };
7471
+ }
7472
+ async function decodeUnsysCanvasHash(hash) {
7473
+ const payload = hashPayload(hash);
7474
+ if (!payload) return null;
7475
+ try {
7476
+ const bytes = await gunzipBytes(base64UrlToBytes(payload));
7477
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
7478
+ return sceneFromPayload(parsed);
7479
+ } catch {
7480
+ return null;
7481
+ }
7482
+ }
7483
+ async function readUnsysCanvasHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
7484
+ return decodeUnsysCanvasHash(hash);
7485
+ }
7486
+ function replaceUnsysCanvasLocationHash(hash) {
7487
+ if (typeof window === "undefined") return;
7488
+ const next = normalizeHash(hash);
7489
+ const current = window.location.hash || "";
7490
+ if (current === next) return;
7491
+ const url = `${window.location.pathname}${window.location.search}${next}`;
7492
+ window.history.replaceState(window.history.state, "", url);
7493
+ }
7494
+ function hashPayload(hash) {
7495
+ const raw = String(hash || "").trim();
7496
+ const body = raw.startsWith("#") ? raw.slice(1) : raw;
7497
+ if (!body.startsWith(UNSYS_CANVAS_HASH_PREFIX)) return null;
7498
+ const payload = body.slice(UNSYS_CANVAS_HASH_PREFIX.length);
7499
+ return payload || null;
7500
+ }
7501
+ function normalizeHash(hash) {
7502
+ if (!hash) return "";
7503
+ return hash.startsWith("#") ? hash : `#${hash}`;
7504
+ }
7505
+ async function hashFromPayload(payload) {
7506
+ try {
7507
+ const json = JSON.stringify(payload);
7508
+ const compressed = await gzipBytes(new TextEncoder().encode(json));
7509
+ return `#${UNSYS_CANVAS_HASH_PREFIX}${bytesToBase64Url(compressed)}`;
7510
+ } catch {
7511
+ return null;
7512
+ }
7513
+ }
7514
+ function sceneFromPayload(parsed) {
7515
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
7516
+ const rec = parsed;
7517
+ if (rec.v !== 1) return null;
7518
+ if (!Array.isArray(rec.elements)) return null;
7519
+ return serializeUnsysCanvasScene({
7520
+ elements: rec.elements,
7521
+ appState: rec.appState,
7522
+ files: rec.files
7523
+ });
7524
+ }
7525
+ async function gzipBytes(bytes) {
7526
+ const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(new CompressionStream("gzip"));
7527
+ return new Uint8Array(await new Response(stream).arrayBuffer());
7528
+ }
7529
+ async function gunzipBytes(bytes) {
7530
+ const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(
7531
+ new DecompressionStream("gzip")
7532
+ );
7533
+ return new Uint8Array(await new Response(stream).arrayBuffer());
7534
+ }
7535
+ function toArrayBuffer(bytes) {
7536
+ const copy = new Uint8Array(bytes.byteLength);
7537
+ copy.set(bytes);
7538
+ return copy.buffer;
7539
+ }
7540
+ function bytesToBase64Url(bytes) {
7541
+ const chunk = 8192;
7542
+ let binary = "";
7543
+ for (let i = 0; i < bytes.length; i += chunk) {
7544
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
7545
+ }
7546
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
7547
+ }
7548
+ function base64UrlToBytes(value) {
7549
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");
7550
+ const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
7551
+ const binary = atob(padded + pad);
7552
+ const bytes = new Uint8Array(binary.length);
7553
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
7554
+ return bytes;
7555
+ }
7556
+
7557
+ // src/lib/collaboration/collab-url.ts
7558
+ var UNSYS_CANVAS_COLLAB_HASH_PREFIX = "uc1.";
7559
+ var ROOM_ID_BYTES = 12;
7560
+ var KEY_BYTES = 32;
7561
+ function bytesToUnsysCanvasCollabB64(bytes) {
7562
+ const chunk = 8192;
7563
+ let binary = "";
7564
+ for (let i = 0; i < bytes.length; i += chunk) {
7565
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
7566
+ }
7567
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
7568
+ }
7569
+ function unsysCanvasCollabB64ToBytes(value) {
7570
+ const trimmed = String(value || "").trim();
7571
+ if (!trimmed || /[^A-Za-z0-9_-]/.test(trimmed)) return null;
7572
+ try {
7573
+ const padded = trimmed.replace(/-/g, "+").replace(/_/g, "/");
7574
+ const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
7575
+ const binary = atob(padded + pad);
7576
+ const bytes = new Uint8Array(binary.length);
7577
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
7578
+ return bytes;
7579
+ } catch {
7580
+ return null;
7581
+ }
7582
+ }
7583
+ function generateUnsysCanvasCollabRoomId() {
7584
+ const bytes = new Uint8Array(ROOM_ID_BYTES);
7585
+ crypto.getRandomValues(bytes);
7586
+ return bytesToUnsysCanvasCollabB64(bytes);
7587
+ }
7588
+ function generateUnsysCanvasCollabKey() {
7589
+ const bytes = new Uint8Array(KEY_BYTES);
7590
+ crypto.getRandomValues(bytes);
7591
+ return bytesToUnsysCanvasCollabB64(bytes);
7592
+ }
7593
+ function generateUnsysCanvasCollabRoom() {
7594
+ return {
7595
+ roomId: generateUnsysCanvasCollabRoomId(),
7596
+ key: generateUnsysCanvasCollabKey()
7597
+ };
7598
+ }
7599
+ function buildUnsysCanvasCollabHash(room) {
7600
+ const roomId = String(room.roomId || "").trim();
7601
+ const key = String(room.key || "").trim();
7602
+ if (!roomId || !key) return "";
7603
+ return `#${UNSYS_CANVAS_COLLAB_HASH_PREFIX}${roomId}.${key}`;
7604
+ }
7605
+ function parseUnsysCanvasCollabHash(hash) {
7606
+ const raw = String(hash || "").trim();
7607
+ const body = raw.startsWith("#") ? raw.slice(1) : raw;
7608
+ if (!body.startsWith(UNSYS_CANVAS_COLLAB_HASH_PREFIX)) return null;
7609
+ const rest = body.slice(UNSYS_CANVAS_COLLAB_HASH_PREFIX.length);
7610
+ const dot = rest.indexOf(".");
7611
+ if (dot <= 0 || dot === rest.length - 1) return null;
7612
+ const roomId = rest.slice(0, dot);
7613
+ const key = rest.slice(dot + 1);
7614
+ if (!unsysCanvasCollabB64ToBytes(roomId) || !unsysCanvasCollabB64ToBytes(key)) return null;
7615
+ const keyBytes = unsysCanvasCollabB64ToBytes(key);
7616
+ if (!keyBytes || keyBytes.byteLength < 16) return null;
7617
+ return { roomId, key };
7618
+ }
7619
+ function isUnsysCanvasCollabHash(hash) {
7620
+ return parseUnsysCanvasCollabHash(hash) !== null;
7621
+ }
7622
+ function readUnsysCanvasCollabHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
7623
+ return parseUnsysCanvasCollabHash(hash);
7624
+ }
7625
+ function replaceUnsysCanvasCollabLocationHash(room) {
7626
+ const next = buildUnsysCanvasCollabHash(room);
7627
+ replaceUnsysCanvasLocationHash(next);
7628
+ return next;
7629
+ }
7630
+ function buildUnsysCanvasCollabShareUrl(room, href = typeof window === "undefined" ? "" : window.location.href) {
7631
+ const url = String(href || "");
7632
+ const hash = buildUnsysCanvasCollabHash(room);
7633
+ const hashAt = url.indexOf("#");
7634
+ const base = hashAt >= 0 ? url.slice(0, hashAt) : url;
7635
+ return `${base}${hash}`;
7636
+ }
7637
+
7638
+ // src/lib/collaboration/collab-colors.ts
7639
+ var PALETTE = [
7640
+ { background: "#70b1ec", stroke: "#3b88c3" },
7641
+ { background: "#e8a838", stroke: "#c47c12" },
7642
+ { background: "#a987eb", stroke: "#7a5cc5" },
7643
+ { background: "#75c7c0", stroke: "#3a9e96" },
7644
+ { background: "#e86868", stroke: "#c24545" },
7645
+ { background: "#9dd655", stroke: "#6ea62e" }
7646
+ ];
7647
+ function unsysCanvasCollabColorForId(id) {
7648
+ let hash = 0;
7649
+ for (let i = 0; i < id.length; i += 1) hash = hash * 33 + id.charCodeAt(i) >>> 0;
7650
+ return PALETTE[hash % PALETTE.length];
7651
+ }
7652
+ function defaultUnsysCanvasCollabName(userId) {
7653
+ const tail = userId.replace(/[^A-Za-z0-9]/g, "").slice(-4).toUpperCase() || "BOARD";
7654
+ return `Guest-${tail}`;
7655
+ }
7656
+
7657
+ // src/lib/collaboration/collab-identity.ts
7658
+ var USER_ID_KEY = "unsys-canvas.collabUserId";
7659
+ var USER_NAME_KEY = "unsys-canvas.collabName";
7660
+ function randomId() {
7661
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
7662
+ return crypto.randomUUID();
7663
+ }
7664
+ const bytes = new Uint8Array(16);
7665
+ crypto.getRandomValues(bytes);
7666
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
7667
+ }
7668
+ function storageGet(storage, key) {
7669
+ try {
7670
+ return String(storage?.getItem(key) || "").trim();
7671
+ } catch {
7672
+ return "";
7673
+ }
7674
+ }
7675
+ function storageSet(storage, key, value) {
7676
+ try {
7677
+ if (!storage) return;
7678
+ if (value) storage.setItem(key, value);
7679
+ else storage.removeItem(key);
7680
+ } catch {
7681
+ }
7682
+ }
7683
+ function readUnsysCanvasCollabUserId(sessionStorageRef = typeof sessionStorage === "undefined" ? void 0 : sessionStorage) {
7684
+ const existing = storageGet(sessionStorageRef, USER_ID_KEY);
7685
+ if (existing) return existing;
7686
+ const id = randomId();
7687
+ storageSet(sessionStorageRef, USER_ID_KEY, id);
7688
+ return id;
7689
+ }
7690
+ function readUnsysCanvasCollabUsername(localStorageRef = typeof localStorage === "undefined" ? void 0 : localStorage) {
7691
+ return storageGet(localStorageRef, USER_NAME_KEY);
7692
+ }
7693
+ function writeUnsysCanvasCollabUsername(name, localStorageRef = typeof localStorage === "undefined" ? void 0 : localStorage) {
7694
+ storageSet(localStorageRef, USER_NAME_KEY, String(name || "").trim());
7695
+ }
7696
+ function resolveUnsysCanvasCollabUser(name) {
7697
+ const id = readUnsysCanvasCollabUserId();
7698
+ const resolved = String(name || readUnsysCanvasCollabUsername() || "").trim() || defaultUnsysCanvasCollabName(id);
7699
+ return {
7700
+ id,
7701
+ name: resolved,
7702
+ color: unsysCanvasCollabColorForId(id)
7703
+ };
7704
+ }
7705
+
7706
+ // src/lib/collaboration/collab-crypto.ts
7707
+ var IV_BYTES = 12;
7708
+ var MAGIC = 1;
7709
+ function subtle() {
7710
+ const api = globalThis.crypto?.subtle;
7711
+ if (!api) throw new Error("Web Crypto is required for board collaboration.");
7712
+ return api;
7713
+ }
7714
+ async function importUnsysCanvasCollabCryptoKey(keyB64) {
7715
+ const raw = unsysCanvasCollabB64ToBytes(keyB64);
7716
+ if (!raw || raw.byteLength < 16) throw new Error("Invalid collaboration key.");
7717
+ const material = raw.byteLength === 16 || raw.byteLength === 32 ? raw : raw.slice(0, 32);
7718
+ return subtle().importKey("raw", toBuffer(material), "AES-GCM", false, ["encrypt", "decrypt"]);
7719
+ }
7720
+ async function encryptUnsysCanvasCollabBytes(keyB64, plaintext) {
7721
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
7722
+ const iv = new Uint8Array(IV_BYTES);
7723
+ globalThis.crypto.getRandomValues(iv);
7724
+ const cipher = new Uint8Array(
7725
+ await subtle().encrypt({ name: "AES-GCM", iv }, cryptoKey, toBuffer(plaintext))
7726
+ );
7727
+ const packed = new Uint8Array(1 + iv.byteLength + cipher.byteLength);
7728
+ packed[0] = MAGIC;
7729
+ packed.set(iv, 1);
7730
+ packed.set(cipher, 1 + iv.byteLength);
7731
+ return packed;
7732
+ }
7733
+ async function decryptUnsysCanvasCollabBytes(keyB64, packed) {
7734
+ if (!packed.byteLength || packed[0] !== MAGIC) throw new Error("Unknown collaboration payload.");
7735
+ if (packed.byteLength < 1 + IV_BYTES + 16) throw new Error("Truncated collaboration payload.");
7736
+ const iv = packed.subarray(1, 1 + IV_BYTES);
7737
+ const cipher = packed.subarray(1 + IV_BYTES);
7738
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
7739
+ const plain = await subtle().decrypt({ name: "AES-GCM", iv: toBuffer(iv) }, cryptoKey, toBuffer(cipher));
7740
+ return new Uint8Array(plain);
7741
+ }
7742
+ async function encryptUnsysCanvasCollabJson(keyB64, value) {
7743
+ return encryptUnsysCanvasCollabBytes(keyB64, new TextEncoder().encode(JSON.stringify(value)));
7744
+ }
7745
+ async function decryptUnsysCanvasCollabJson(keyB64, packed) {
7746
+ const bytes = await decryptUnsysCanvasCollabBytes(keyB64, packed);
7747
+ return JSON.parse(new TextDecoder().decode(bytes));
7748
+ }
7749
+ function toBuffer(bytes) {
7750
+ const copy = new Uint8Array(bytes.byteLength);
7751
+ copy.set(bytes);
7752
+ return copy.buffer;
7753
+ }
7754
+
7755
+ // src/lib/collaboration/collab-reconcile.ts
7756
+ function versionOf(el) {
7757
+ return Number(el?.version) || 0;
7758
+ }
7759
+ function versionNonceOf(el) {
7760
+ return Number(el?.versionNonce) || 0;
7761
+ }
7762
+ function shouldDiscardRemoteUnsysCanvasElement(local, remote, editingIds) {
7763
+ if (editingIds?.has(remote.id)) return true;
7764
+ if (!local) return false;
7765
+ if (editingIds?.has(local.id)) return true;
7766
+ if (versionOf(local) > versionOf(remote)) return true;
7767
+ if (versionOf(local) === versionOf(remote) && versionNonceOf(local) < versionNonceOf(remote)) {
7768
+ return true;
7769
+ }
7770
+ return false;
7771
+ }
7772
+ function reconcileUnsysCanvasElements(local, remote, options) {
7773
+ const localList = Array.isArray(local) ? local.filter((el) => el && typeof el.id === "string") : [];
7774
+ const remoteList = Array.isArray(remote) ? remote.filter((el) => el && typeof el.id === "string") : [];
7775
+ const editingIds = options?.editingIds ? new Set(options.editingIds) : null;
7776
+ const localMap = new Map(localList.map((el) => [el.id, el]));
7777
+ const added = /* @__PURE__ */ new Set();
7778
+ const next = [];
7779
+ for (const remoteEl of remoteList) {
7780
+ const localEl = localMap.get(remoteEl.id);
7781
+ if (shouldDiscardRemoteUnsysCanvasElement(localEl, remoteEl, editingIds)) {
7782
+ if (localEl && !added.has(localEl.id)) {
7783
+ next.push(localEl);
7784
+ added.add(localEl.id);
6366
7785
  }
6367
- const divider = toolbar.querySelector(".App-toolbar__divider");
6368
- if (divider && node.nextSibling !== divider && node.parentElement !== toolbar) {
6369
- toolbar.insertBefore(node, divider);
6370
- } else if (!node.parentElement) {
6371
- toolbar.appendChild(node);
7786
+ continue;
7787
+ }
7788
+ next.push(remoteEl);
7789
+ added.add(remoteEl.id);
7790
+ }
7791
+ for (const localEl of localList) {
7792
+ if (added.has(localEl.id)) continue;
7793
+ next.push(localEl);
7794
+ added.add(localEl.id);
7795
+ }
7796
+ return next;
7797
+ }
7798
+ function reconcileUnsysCanvasFiles(local, remote) {
7799
+ return { ...local ?? {}, ...remote ?? {} };
7800
+ }
7801
+ function unsysCanvasEditingElementIds(appState) {
7802
+ if (!appState) return [];
7803
+ const ids = [];
7804
+ for (const key of [
7805
+ "editingTextElement",
7806
+ "editingElement",
7807
+ "resizingElement",
7808
+ "newElement",
7809
+ "draggingElement"
7810
+ ]) {
7811
+ const value = appState[key];
7812
+ if (value && typeof value === "object" && typeof value.id === "string") {
7813
+ ids.push(value.id);
7814
+ }
7815
+ }
7816
+ return ids;
7817
+ }
7818
+ function reconcileUnsysCanvasScene(local, remote, options) {
7819
+ return {
7820
+ elements: reconcileUnsysCanvasElements(local?.elements, remote?.elements, options),
7821
+ files: reconcileUnsysCanvasFiles(local?.files, remote?.files ?? {})
7822
+ };
7823
+ }
7824
+
7825
+ // src/lib/collaboration/collab-session.ts
7826
+ function isPlainMessage(value) {
7827
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
7828
+ const rec = value;
7829
+ if (rec.v !== 1 || typeof rec.from !== "string" || !rec.from) return false;
7830
+ if (rec.type !== "hello" && rec.type !== "scene" && rec.type !== "pointer") return false;
7831
+ return true;
7832
+ }
7833
+ function collaboratorFromUser(user, extra) {
7834
+ return {
7835
+ id: user.id,
7836
+ username: user.name,
7837
+ color: user.color,
7838
+ userState: "active",
7839
+ ...extra
7840
+ };
7841
+ }
7842
+ var UnsysCanvasCollabSession = class {
7843
+ constructor(options) {
7844
+ this.socket = null;
7845
+ this.collaborators = /* @__PURE__ */ new Map();
7846
+ this.closed = false;
7847
+ this.roomId = options.roomId;
7848
+ this.key = options.key;
7849
+ this.user = options.user;
7850
+ this.transport = options.transport;
7851
+ this.handlers = options.handlers ?? {};
7852
+ this.getLocalScene = options.getLocalScene;
7853
+ this.getEditingIds = options.getEditingIds;
7854
+ }
7855
+ start() {
7856
+ if (this.socket || this.closed) return;
7857
+ this.socket = this.transport.open(this.roomId, {
7858
+ onOpen: () => {
7859
+ void this.sendHello();
7860
+ this.handlers.onOpen?.();
7861
+ },
7862
+ onMessage: (bytes) => {
7863
+ void this.handleBytes(bytes);
7864
+ },
7865
+ onClose: () => {
7866
+ this.handlers.onClose?.();
7867
+ },
7868
+ onError: (error) => {
7869
+ this.handlers.onError?.(error);
6372
7870
  }
6373
- setSlot((prev) => prev === node ? prev : node);
6374
- };
6375
- place();
6376
- let raf = 0;
6377
- const schedule = () => {
6378
- if (raf) return;
6379
- raf = window.requestAnimationFrame(() => {
6380
- raf = 0;
6381
- place();
7871
+ });
7872
+ }
7873
+ close() {
7874
+ this.closed = true;
7875
+ this.socket?.close();
7876
+ this.socket = null;
7877
+ this.collaborators = /* @__PURE__ */ new Map();
7878
+ this.emitCollaborators();
7879
+ }
7880
+ async broadcastScene(scene) {
7881
+ await this.send({
7882
+ v: 1,
7883
+ from: this.user.id,
7884
+ type: "scene",
7885
+ user: this.user,
7886
+ scene: {
7887
+ elements: scene.elements ?? [],
7888
+ files: scene.files ?? {}
7889
+ }
7890
+ });
7891
+ }
7892
+ async broadcastPointer(pointer) {
7893
+ await this.send({
7894
+ v: 1,
7895
+ from: this.user.id,
7896
+ type: "pointer",
7897
+ user: this.user,
7898
+ pointer
7899
+ });
7900
+ }
7901
+ async sendHello() {
7902
+ await this.send({ v: 1, from: this.user.id, type: "hello", user: this.user });
7903
+ const scene = this.getLocalScene?.();
7904
+ if (scene?.elements?.length) await this.broadcastScene(scene);
7905
+ }
7906
+ async send(message) {
7907
+ if (!this.socket || this.closed) return;
7908
+ try {
7909
+ const packed = await encryptUnsysCanvasCollabJson(this.key, message);
7910
+ this.socket.send(packed);
7911
+ } catch (error) {
7912
+ this.handlers.onError?.(error);
7913
+ }
7914
+ }
7915
+ async handleBytes(bytes) {
7916
+ if (this.closed) return;
7917
+ let parsed;
7918
+ try {
7919
+ parsed = await decryptUnsysCanvasCollabJson(this.key, bytes);
7920
+ } catch {
7921
+ return;
7922
+ }
7923
+ if (!isPlainMessage(parsed) || parsed.from === this.user.id) return;
7924
+ this.touchCollaborator(parsed);
7925
+ if (parsed.type === "hello") {
7926
+ const scene = this.getLocalScene?.();
7927
+ if (scene) await this.broadcastScene(scene);
7928
+ return;
7929
+ }
7930
+ if (parsed.type === "pointer") {
7931
+ this.collaborators.set(
7932
+ parsed.from,
7933
+ collaboratorFromUser(parsed.user, {
7934
+ pointer: parsed.pointer.pointer,
7935
+ button: parsed.pointer.button,
7936
+ selectedElementIds: parsed.pointer.selectedElementIds
7937
+ })
7938
+ );
7939
+ this.emitCollaborators();
7940
+ return;
7941
+ }
7942
+ if (parsed.type === "scene") {
7943
+ const local = this.getLocalScene?.() ?? { elements: [], files: {} };
7944
+ const remote = {
7945
+ elements: parsed.scene.elements ?? [],
7946
+ files: parsed.scene.files ?? {}
7947
+ };
7948
+ const merged = reconcileUnsysCanvasScene(local, remote, {
7949
+ editingIds: this.getEditingIds?.() ?? null
6382
7950
  });
6383
- };
6384
- let observed = null;
6385
- const observer = new MutationObserver(() => {
6386
- schedule();
6387
- attach();
7951
+ this.handlers.onRemoteScene?.(merged, parsed.user);
7952
+ }
7953
+ }
7954
+ touchCollaborator(message) {
7955
+ const prev = this.collaborators.get(message.from);
7956
+ this.collaborators.set(message.from, {
7957
+ ...collaboratorFromUser(message.user),
7958
+ pointer: prev?.pointer,
7959
+ button: prev?.button,
7960
+ selectedElementIds: prev?.selectedElementIds
6388
7961
  });
6389
- const attach = () => {
6390
- const toolbar = host.querySelector(".App-toolbar");
6391
- const target = toolbar ?? host;
6392
- if (observed === target) return;
6393
- observer.disconnect();
6394
- observed = target;
6395
- observer.observe(target, {
6396
- childList: true,
6397
- subtree: target === host
7962
+ this.emitCollaborators();
7963
+ }
7964
+ emitCollaborators() {
7965
+ this.handlers.onCollaborators?.(new Map(this.collaborators));
7966
+ }
7967
+ };
7968
+
7969
+ // src/components/collaboration/use-work-canvas-collaboration.ts
7970
+ var SCENE_THROTTLE_MS = 80;
7971
+ var POINTER_THROTTLE_MS = 40;
7972
+ var TOAST_MS = 2200;
7973
+ async function copyText(text) {
7974
+ try {
7975
+ if (navigator.clipboard?.writeText) {
7976
+ await navigator.clipboard.writeText(text);
7977
+ return true;
7978
+ }
7979
+ } catch {
7980
+ }
7981
+ try {
7982
+ const field = document.createElement("textarea");
7983
+ field.value = text;
7984
+ field.setAttribute("readonly", "true");
7985
+ field.style.position = "fixed";
7986
+ field.style.left = "-9999px";
7987
+ document.body.appendChild(field);
7988
+ field.select();
7989
+ const ok = document.execCommand("copy");
7990
+ field.remove();
7991
+ return ok;
7992
+ } catch {
7993
+ return false;
7994
+ }
7995
+ }
7996
+ function useWorkCanvasCollaboration({
7997
+ enabled,
7998
+ adapter,
7999
+ getScene,
8000
+ getEditingIds,
8001
+ applyRemoteScene
8002
+ }) {
8003
+ const adapterRef = useRef(adapter);
8004
+ adapterRef.current = adapter;
8005
+ const getSceneRef = useRef(getScene);
8006
+ getSceneRef.current = getScene;
8007
+ const getEditingIdsRef = useRef(getEditingIds);
8008
+ getEditingIdsRef.current = getEditingIds;
8009
+ const applyRemoteSceneRef = useRef(applyRemoteScene);
8010
+ applyRemoteSceneRef.current = applyRemoteScene;
8011
+ const sessionRef = useRef(null);
8012
+ const roomRef = useRef(null);
8013
+ const lastPointerAtRef = useRef(0);
8014
+ const sceneTimerRef = useRef(null);
8015
+ const lastBroadcastSigRef = useRef("");
8016
+ const pendingInviteRef = useRef(false);
8017
+ const [collaborators, setCollaborators] = useState(
8018
+ () => /* @__PURE__ */ new Map()
8019
+ );
8020
+ const [isCollaborating, setIsCollaborating] = useState(false);
8021
+ const [toast, setToast] = useState(null);
8022
+ const [nameDraft, setNameDraft] = useState("");
8023
+ const [namePromptOpen, setNamePromptOpen] = useState(false);
8024
+ const showToast = useCallback((message) => {
8025
+ setToast(message);
8026
+ window.setTimeout(() => {
8027
+ setToast((current) => current === message ? null : current);
8028
+ }, TOAST_MS);
8029
+ }, []);
8030
+ const stopSession = useCallback(() => {
8031
+ if (sceneTimerRef.current) {
8032
+ window.clearTimeout(sceneTimerRef.current);
8033
+ sceneTimerRef.current = null;
8034
+ }
8035
+ sessionRef.current?.close();
8036
+ sessionRef.current = null;
8037
+ setCollaborators(/* @__PURE__ */ new Map());
8038
+ setIsCollaborating(false);
8039
+ }, []);
8040
+ const startSession = useCallback(
8041
+ (room, username) => {
8042
+ const transport = adapterRef.current;
8043
+ if (!transport) return false;
8044
+ stopSession();
8045
+ const user = resolveUnsysCanvasCollabUser(username);
8046
+ roomRef.current = room;
8047
+ const session = new UnsysCanvasCollabSession({
8048
+ roomId: room.roomId,
8049
+ key: room.key,
8050
+ user,
8051
+ transport,
8052
+ getLocalScene: () => {
8053
+ const scene = getSceneRef.current();
8054
+ if (!scene) return null;
8055
+ return { elements: scene.elements ?? [], files: scene.files ?? {} };
8056
+ },
8057
+ getEditingIds: () => getEditingIdsRef.current(),
8058
+ handlers: {
8059
+ onRemoteScene: (scene) => {
8060
+ lastBroadcastSigRef.current = unsysCanvasPersistSignature({
8061
+ elements: scene.elements,
8062
+ files: scene.files
8063
+ });
8064
+ applyRemoteSceneRef.current(scene);
8065
+ },
8066
+ onCollaborators: setCollaborators,
8067
+ onOpen: () => setIsCollaborating(true),
8068
+ onClose: () => setIsCollaborating(false)
8069
+ }
6398
8070
  });
8071
+ sessionRef.current = session;
8072
+ session.start();
8073
+ setIsCollaborating(true);
8074
+ return true;
8075
+ },
8076
+ [stopSession]
8077
+ );
8078
+ useEffect(() => {
8079
+ if (!enabled) {
8080
+ stopSession();
8081
+ return;
8082
+ }
8083
+ const room = parseUnsysCanvasCollabHash(
8084
+ typeof window === "undefined" ? "" : window.location.hash
8085
+ );
8086
+ if (!room) return;
8087
+ if (!adapterRef.current) return;
8088
+ startSession(room);
8089
+ return () => {
8090
+ stopSession();
6399
8091
  };
6400
- attach();
8092
+ }, [enabled, adapter, startSession, stopSession]);
8093
+ const broadcastScene = useCallback((scene) => {
8094
+ if (!sessionRef.current) return;
8095
+ const sig = unsysCanvasPersistSignature(scene);
8096
+ if (sig === lastBroadcastSigRef.current) return;
8097
+ lastBroadcastSigRef.current = sig;
8098
+ if (sceneTimerRef.current) window.clearTimeout(sceneTimerRef.current);
8099
+ sceneTimerRef.current = window.setTimeout(() => {
8100
+ sceneTimerRef.current = null;
8101
+ const live = getSceneRef.current();
8102
+ if (!live || !sessionRef.current) return;
8103
+ void sessionRef.current.broadcastScene({
8104
+ elements: live.elements ?? [],
8105
+ files: live.files ?? {}
8106
+ });
8107
+ }, SCENE_THROTTLE_MS);
8108
+ }, []);
8109
+ const broadcastPointer = useCallback((pointer) => {
8110
+ const session = sessionRef.current;
8111
+ if (!session) return;
8112
+ const now = Date.now();
8113
+ if (pointer.button === "up" || now - lastPointerAtRef.current >= POINTER_THROTTLE_MS) {
8114
+ lastPointerAtRef.current = now;
8115
+ void session.broadcastPointer(pointer);
8116
+ }
8117
+ }, []);
8118
+ const finishInvite = useCallback(async () => {
8119
+ const existing = roomRef.current ?? parseUnsysCanvasCollabHash(window.location.hash);
8120
+ const room = existing ?? generateUnsysCanvasCollabRoom();
8121
+ replaceUnsysCanvasCollabLocationHash(room);
8122
+ roomRef.current = room;
8123
+ if (!sessionRef.current) startSession(room);
8124
+ const share = buildUnsysCanvasCollabShareUrl(room);
8125
+ const copied = await copyText(share);
8126
+ showToast(copied ? "Link copied" : "Copy the URL from the address bar");
8127
+ }, [showToast, startSession]);
8128
+ const invite = useCallback(() => {
8129
+ if (!adapterRef.current) return;
8130
+ const stored = readUnsysCanvasCollabUsername();
8131
+ if (!stored) {
8132
+ pendingInviteRef.current = true;
8133
+ setNameDraft(resolveUnsysCanvasCollabUser().name);
8134
+ setNamePromptOpen(true);
8135
+ return;
8136
+ }
8137
+ void finishInvite();
8138
+ }, [finishInvite]);
8139
+ const confirmName = useCallback(() => {
8140
+ const name = nameDraft.trim() || resolveUnsysCanvasCollabUser().name;
8141
+ writeUnsysCanvasCollabUsername(name);
8142
+ setNamePromptOpen(false);
8143
+ const shouldInvite = pendingInviteRef.current;
8144
+ pendingInviteRef.current = false;
8145
+ const room = roomRef.current ?? parseUnsysCanvasCollabHash(window.location.hash);
8146
+ if (room && !sessionRef.current) startSession(room, name);
8147
+ if (shouldInvite) void finishInvite();
8148
+ }, [finishInvite, nameDraft, startSession]);
8149
+ const cancelName = useCallback(() => {
8150
+ pendingInviteRef.current = false;
8151
+ setNamePromptOpen(false);
8152
+ }, []);
8153
+ useEffect(() => {
6401
8154
  return () => {
6402
- observer.disconnect();
6403
- if (raf) window.cancelAnimationFrame(raf);
6404
- node?.remove();
8155
+ if (sceneTimerRef.current) window.clearTimeout(sceneTimerRef.current);
8156
+ sessionRef.current?.close();
6405
8157
  };
6406
- }, [hostRef]);
6407
- if (!slot) return null;
6408
- return createPortal(
6409
- /* @__PURE__ */ jsx(
6410
- "button",
6411
- {
6412
- type: "button",
6413
- "data-unsys-canvas-toolbar-laser": true,
6414
- className: `ToolIcon ToolIcon_type_toggle${active ? " ToolIcon--checked" : ""}`,
6415
- title: "Laser pointer \u2014 K",
6416
- "aria-label": "Laser pointer",
6417
- "aria-pressed": active ? "true" : "false",
6418
- onClick: () => onToggle ? onToggle() : setLiveActiveTool(apiRef.current, { type: "laser" }),
6419
- children: /* @__PURE__ */ jsx("div", { className: "ToolIcon__icon", children: LASER_ICON })
6420
- }
6421
- ),
6422
- slot
8158
+ }, []);
8159
+ return {
8160
+ collaborators,
8161
+ isCollaborating,
8162
+ toast,
8163
+ namePromptOpen,
8164
+ nameDraft,
8165
+ setNameDraft,
8166
+ invite,
8167
+ confirmName,
8168
+ cancelName,
8169
+ broadcastScene,
8170
+ broadcastPointer,
8171
+ canInvite: Boolean(adapter)
8172
+ };
8173
+ }
8174
+ function CanvasCollabToast({ message }) {
8175
+ if (!message) return null;
8176
+ return /* @__PURE__ */ jsx(
8177
+ "div",
8178
+ {
8179
+ "data-unsys-canvas-collab-toast": true,
8180
+ className: "pointer-events-none absolute right-3 top-14 z-30 border border-white/40 bg-black px-3 py-2 font-mono text-[11px] uppercase tracking-[0.12em] text-white shadow-[0_8px_24px_rgba(0,0,0,0.45)]",
8181
+ role: "status",
8182
+ children: message
8183
+ }
8184
+ );
8185
+ }
8186
+ function CanvasInviteButton({
8187
+ disabled,
8188
+ hint,
8189
+ onClick
8190
+ }) {
8191
+ return /* @__PURE__ */ jsx(
8192
+ "button",
8193
+ {
8194
+ type: "button",
8195
+ "data-unsys-canvas-invite": true,
8196
+ "aria-label": "Invite",
8197
+ title: disabled ? hint || "Invite needs a collaboration relay." : "Copy a live board link",
8198
+ disabled,
8199
+ onClick,
8200
+ className: "absolute right-3 top-3 z-30 border border-white/45 bg-black px-2.5 py-1.5 font-mono text-[11px] font-semibold uppercase tracking-[0.14em] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.35)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:text-neutral-500",
8201
+ children: "Invite"
8202
+ }
8203
+ );
8204
+ }
8205
+ function CanvasCollabNamePrompt({
8206
+ value,
8207
+ onChange,
8208
+ onSubmit,
8209
+ onCancel
8210
+ }) {
8211
+ return /* @__PURE__ */ jsx(
8212
+ "div",
8213
+ {
8214
+ "data-unsys-canvas-collab-name": true,
8215
+ className: "absolute inset-0 z-40 flex items-start justify-end bg-black/40 p-3",
8216
+ children: /* @__PURE__ */ jsxs(
8217
+ "form",
8218
+ {
8219
+ className: "w-72 border border-white/40 bg-black p-3 shadow-[0_12px_32px_rgba(0,0,0,0.5)]",
8220
+ onSubmit: (event) => {
8221
+ event.preventDefault();
8222
+ onSubmit();
8223
+ },
8224
+ children: [
8225
+ /* @__PURE__ */ jsxs("label", { className: "block font-mono text-[10px] uppercase tracking-[0.14em] text-white/70", children: [
8226
+ "Display name",
8227
+ /* @__PURE__ */ jsx(
8228
+ "input",
8229
+ {
8230
+ "data-unsys-canvas-collab-name-input": true,
8231
+ value,
8232
+ onChange: (event) => onChange(event.target.value),
8233
+ autoComplete: "nickname",
8234
+ className: "mt-2 w-full border border-white/30 bg-neutral-950 px-2 py-1.5 font-mono text-[12px] text-white"
8235
+ }
8236
+ )
8237
+ ] }),
8238
+ /* @__PURE__ */ jsxs("div", { className: "mt-3 flex justify-end gap-2", children: [
8239
+ /* @__PURE__ */ jsx(
8240
+ "button",
8241
+ {
8242
+ type: "button",
8243
+ className: "border border-white/30 px-2 py-1 font-mono text-[10px] uppercase tracking-wider text-white/70 hover:text-white",
8244
+ onClick: onCancel,
8245
+ children: "Cancel"
8246
+ }
8247
+ ),
8248
+ /* @__PURE__ */ jsx(
8249
+ "button",
8250
+ {
8251
+ type: "submit",
8252
+ className: "border border-white bg-white px-2 py-1 font-mono text-[10px] font-semibold uppercase tracking-wider text-black hover:bg-neutral-200",
8253
+ children: "Join"
8254
+ }
8255
+ )
8256
+ ] })
8257
+ ]
8258
+ }
8259
+ )
8260
+ }
6423
8261
  );
6424
8262
  }
6425
8263
 
@@ -6550,6 +8388,7 @@ function ExcalidrawCanvas({
6550
8388
  scrollAppliedElements = true,
6551
8389
  onEvent,
6552
8390
  onAsk,
8391
+ runModel,
6553
8392
  boardId = null,
6554
8393
  askBusy = false,
6555
8394
  onLearnerWaitChange,
@@ -6566,11 +8405,12 @@ function ExcalidrawCanvas({
6566
8405
  sidebarStyle: sidebarStyleProp,
6567
8406
  style: styleProp,
6568
8407
  liveCanvasChrome = false,
6569
- extraCommands = []
8408
+ extraCommands = [],
8409
+ collaboration = null,
8410
+ invite = false,
8411
+ inviteHint = null
6570
8412
  }) {
6571
- if (typeof onAsk !== "function") {
6572
- throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
6573
- }
8413
+ assertCanvasModel({ onAsk, runModel });
6574
8414
  const { t } = useI18n();
6575
8415
  const submitButtonLabel = submitLabel || t("whiteboard.submitBoard");
6576
8416
  const sidebarStyle = parseUnsysCanvasStyle(styleProp ?? sidebarStyleProp);
@@ -6585,7 +8425,10 @@ function ExcalidrawCanvas({
6585
8425
  const [canvasApiReady, setCanvasApiReady] = useState(false);
6586
8426
  const [commandText, setCommandText] = useState("");
6587
8427
  const [slashBarOpen, setSlashBarOpen] = useState(false);
8428
+ const [pickerPos, setPickerPos] = useState({ left: 24, top: 24 });
6588
8429
  const commandInputRef = useRef(null);
8430
+ const lastPointerHostRef = useRef({ x: 24, y: 24 });
8431
+ const pickerSelectedRef = useRef([]);
6589
8432
  const selectionWasActiveRef = useRef(false);
6590
8433
  const [askInFlight, setAskInFlight] = useState(0);
6591
8434
  const lastReplaceNonceRef = useRef(null);
@@ -6607,7 +8450,32 @@ function ExcalidrawCanvas({
6607
8450
  sessionBranchRef.current = null;
6608
8451
  const branchQuestions = openBranchQuestions(sessionBranchRef.current);
6609
8452
  const markQuestionsForBar = branchQuestions.length > 0 ? branchQuestions : markQuestions;
6610
- const onAskRef = useRef(onAsk);
8453
+ const extraCommandsRef = useRef(extraCommands);
8454
+ extraCommandsRef.current = extraCommands;
8455
+ const runModelRef = useRef(runModel);
8456
+ runModelRef.current = runModel;
8457
+ const hostAskRef = useRef(onAsk);
8458
+ hostAskRef.current = onAsk;
8459
+ const resolveAsk = useCallback(
8460
+ async (input) => {
8461
+ const model = runModelRef.current;
8462
+ if (model) {
8463
+ const commandId = input.kind && input.kind !== "ask" ? String(input.kind) : "ask";
8464
+ return runUnsysCanvasModelAsk(model, {
8465
+ commandId,
8466
+ scene: input.scene,
8467
+ selectedElements: input.selectedElements,
8468
+ prompt: input.prompt,
8469
+ extras: extraCommandsRef.current
8470
+ });
8471
+ }
8472
+ const ask = hostAskRef.current;
8473
+ if (!ask) throw new Error("UnsysCanvas requires a runModel or onAsk handler; the package does not call any LLM.");
8474
+ return ask(input);
8475
+ },
8476
+ []
8477
+ );
8478
+ const onAskRef = useRef(resolveAsk);
6611
8479
  const askInFlightRef = useRef(0);
6612
8480
  const applyingRemoteRef = useRef(false);
6613
8481
  const sceneDataRef = useRef(null);
@@ -6860,8 +8728,8 @@ function ExcalidrawCanvas({
6860
8728
  );
6861
8729
  }, [boardId]);
6862
8730
  useEffect(() => {
6863
- onAskRef.current = onAsk;
6864
- }, [onAsk]);
8731
+ onAskRef.current = resolveAsk;
8732
+ }, [resolveAsk]);
6865
8733
  const onLearnerWaitChangeRef = useRef(onLearnerWaitChange);
6866
8734
  useEffect(() => {
6867
8735
  onLearnerWaitChangeRef.current = onLearnerWaitChange;
@@ -6963,6 +8831,49 @@ function ExcalidrawCanvas({
6963
8831
  writeDictatedText,
6964
8832
  submitCommand
6965
8833
  } = commands;
8834
+ const applyRemoteCollabScene = useCallback(
8835
+ (remote) => {
8836
+ const api = excalidrawAPIRef.current;
8837
+ if (!api) return;
8838
+ commitScene(
8839
+ api,
8840
+ { elements: remote.elements, files: remote.files },
8841
+ { applyingRemote: applyingRemoteRef }
8842
+ );
8843
+ },
8844
+ []
8845
+ );
8846
+ const {
8847
+ collaborators,
8848
+ isCollaborating,
8849
+ toast,
8850
+ namePromptOpen,
8851
+ nameDraft,
8852
+ setNameDraft,
8853
+ invite: inviteToRoom,
8854
+ confirmName,
8855
+ cancelName,
8856
+ broadcastScene,
8857
+ broadcastPointer,
8858
+ canInvite
8859
+ } = useWorkCanvasCollaboration({
8860
+ enabled: Boolean(collaboration),
8861
+ adapter: collaboration,
8862
+ getScene: () => sceneDataRef.current,
8863
+ getEditingIds: () => unsysCanvasEditingElementIds(
8864
+ excalidrawAPIRef.current?.getAppState() ?? {}
8865
+ ),
8866
+ applyRemoteScene: applyRemoteCollabScene
8867
+ });
8868
+ useEffect(() => {
8869
+ const api = excalidrawAPIRef.current;
8870
+ if (!api) return;
8871
+ commitScene(
8872
+ api,
8873
+ { collaborators: isCollaborating ? collaborators : /* @__PURE__ */ new Map() },
8874
+ { applyingRemote: applyingRemoteRef }
8875
+ );
8876
+ }, [canvasApiReady, collaborators, isCollaborating]);
6966
8877
  const { onLaserPointerUpdate } = useWorkCanvasLaser({
6967
8878
  apiRef: excalidrawAPIRef,
6968
8879
  handleQuickActionRef,
@@ -6970,10 +8881,30 @@ function ExcalidrawCanvas({
6970
8881
  emitCanvasEventsRef.current(canvasEventCollectorRef.current.laser(payload));
6971
8882
  }
6972
8883
  });
8884
+ const openCommandPickerAt = useCallback(
8885
+ (x, y) => {
8886
+ const host = canvasHostRef.current;
8887
+ const width = host?.clientWidth ?? 320;
8888
+ const height = host?.clientHeight ?? 240;
8889
+ setPickerPos({
8890
+ left: Math.max(8, Math.min(Math.round(x), width - 272)),
8891
+ top: Math.max(8, Math.min(Math.round(y), height - 220))
8892
+ });
8893
+ pickerSelectedRef.current = selectedCanvasElements();
8894
+ setCommandText("");
8895
+ setSlashBarOpen(true);
8896
+ },
8897
+ [selectedCanvasElements]
8898
+ );
6973
8899
  useEffect(() => {
6974
8900
  const onKey = (event) => {
6975
8901
  const target = event.target;
6976
8902
  const typingInField = target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || Boolean(target?.isContentEditable);
8903
+ if (slashBarOpen && event.key === "Escape" && !typingInField) {
8904
+ event.preventDefault();
8905
+ setSlashBarOpen(false);
8906
+ return;
8907
+ }
6977
8908
  if (typingInField) return;
6978
8909
  const letter = unsysCanvasCommandShortcutKeyFromEvent(event);
6979
8910
  const key = String(event.key || "").toLowerCase();
@@ -6982,7 +8913,7 @@ function ExcalidrawCanvas({
6982
8913
  const kind = event.shiftKey ? "redo" : "undo";
6983
8914
  emitCanvasEventsRef.current(canvasEventCollectorRef.current.history(kind, { key }));
6984
8915
  }
6985
- if (letter) {
8916
+ if (letter && !slashBarOpen) {
6986
8917
  const command = unsysCanvasCommandByShortcut(letter, markModeRef.current, extraCommands);
6987
8918
  if (command) {
6988
8919
  event.preventDefault();
@@ -6998,12 +8929,17 @@ function ExcalidrawCanvas({
6998
8929
  return;
6999
8930
  }
7000
8931
  event.preventDefault();
7001
- setSlashBarOpen(true);
7002
- setCommandText((current) => current.startsWith("/") ? current : "/");
8932
+ openCommandPickerAt(lastPointerHostRef.current.x, lastPointerHostRef.current.y);
7003
8933
  };
7004
8934
  window.addEventListener("keydown", onKey);
7005
8935
  return () => window.removeEventListener("keydown", onKey);
7006
- }, [canvasSelectionActive, extraCommands, handleQuickActionRef]);
8936
+ }, [
8937
+ canvasSelectionActive,
8938
+ extraCommands,
8939
+ handleQuickActionRef,
8940
+ openCommandPickerAt,
8941
+ slashBarOpen
8942
+ ]);
7007
8943
  useEffect(() => {
7008
8944
  if (!unsysCanvasSlashBarOpen({
7009
8945
  selectionActive: canvasSelectionActive,
@@ -7156,6 +9092,7 @@ function ExcalidrawCanvas({
7156
9092
  gestureBusy: unsysCanvasGestureBusy()
7157
9093
  });
7158
9094
  emitCanvasEventsRef.current(powEvents);
9095
+ broadcastScene(sceneData);
7159
9096
  }
7160
9097
  if (scenePersistTimeoutRef.current) clearTimeout(scenePersistTimeoutRef.current);
7161
9098
  scenePersistTimeoutRef.current = setTimeout(() => {
@@ -7179,11 +9116,16 @@ function ExcalidrawCanvas({
7179
9116
  const laserOn = unsysCanvasPointerToolActive(appState.activeTool);
7180
9117
  setLaserToolActive((prev) => prev === laserOn ? prev : laserOn);
7181
9118
  },
7182
- [debouncedExportPNG, syncCanvasSelection, syncLatexOverlay, syncThinkingOverlay]
9119
+ [broadcastScene, debouncedExportPNG, syncCanvasSelection, syncLatexOverlay, syncThinkingOverlay]
7183
9120
  );
7184
9121
  const handlePointerUpdate = useCallback(
7185
9122
  (payload) => {
7186
9123
  onLaserPointerUpdate(payload);
9124
+ broadcastPointer({
9125
+ pointer: payload.pointer,
9126
+ button: payload.button,
9127
+ selectedElementIds: excalidrawAPIRef.current?.getAppState?.()?.selectedElementIds
9128
+ });
7187
9129
  const api = excalidrawAPIRef.current;
7188
9130
  if (payload.button === "down" && api) {
7189
9131
  syncCanvasSelection(api.getAppState?.() ?? {});
@@ -7203,7 +9145,7 @@ function ExcalidrawCanvas({
7203
9145
  emitCanvasEventsRef.current(powEvents);
7204
9146
  }
7205
9147
  },
7206
- [onLaserPointerUpdate, syncCanvasSelection]
9148
+ [broadcastPointer, onLaserPointerUpdate, syncCanvasSelection]
7207
9149
  );
7208
9150
  const handleSubmitBoard = useCallback(async () => {
7209
9151
  if (!onSubmitBoard || isSubmittingBoard || !canSubmitBoard) return;
@@ -7324,6 +9266,19 @@ function ExcalidrawCanvas({
7324
9266
  className: "relative min-h-0 flex-1",
7325
9267
  "data-unsys-canvas-host": true,
7326
9268
  style: { backgroundColor: sidebarStyle.canvas.background },
9269
+ onMouseMove: (event) => {
9270
+ const rect = event.currentTarget.getBoundingClientRect();
9271
+ lastPointerHostRef.current = {
9272
+ x: event.clientX - rect.left,
9273
+ y: event.clientY - rect.top
9274
+ };
9275
+ },
9276
+ onContextMenu: (event) => {
9277
+ if (!canvasSelectionActive) return;
9278
+ event.preventDefault();
9279
+ const rect = event.currentTarget.getBoundingClientRect();
9280
+ openCommandPickerAt(event.clientX - rect.left, event.clientY - rect.top);
9281
+ },
7327
9282
  children: [
7328
9283
  isLoaded && /* @__PURE__ */ jsx(UnsysExcalidrawErrorBoundary, { children: /* @__PURE__ */ jsx(
7329
9284
  UnsysExcalidrawMount,
@@ -7332,9 +9287,28 @@ function ExcalidrawCanvas({
7332
9287
  onChange: handleChange,
7333
9288
  onPointerUpdate: handlePointerUpdate,
7334
9289
  initialData: initialSceneDataRef.current,
7335
- viewModeEnabled
9290
+ viewModeEnabled,
9291
+ isCollaborating
7336
9292
  }
7337
9293
  ) }),
9294
+ invite ? /* @__PURE__ */ jsx(
9295
+ CanvasInviteButton,
9296
+ {
9297
+ disabled: !canInvite,
9298
+ hint: inviteHint,
9299
+ onClick: inviteToRoom
9300
+ }
9301
+ ) : null,
9302
+ /* @__PURE__ */ jsx(CanvasCollabToast, { message: toast }),
9303
+ namePromptOpen ? /* @__PURE__ */ jsx(
9304
+ CanvasCollabNamePrompt,
9305
+ {
9306
+ value: nameDraft,
9307
+ onChange: setNameDraft,
9308
+ onSubmit: confirmName,
9309
+ onCancel: cancelName
9310
+ }
9311
+ ) : null,
7338
9312
  /* @__PURE__ */ jsx(
7339
9313
  UnsysLaserToolbarSlot,
7340
9314
  {
@@ -7390,7 +9364,56 @@ function ExcalidrawCanvas({
7390
9364
  selectedMarkTexts: selectedCanvasElements().map((element) => element.text || "").filter((text) => text.trim()),
7391
9365
  markSpeech: dictateTranscript || ""
7392
9366
  }
7393
- )
9367
+ ),
9368
+ (() => {
9369
+ const selected = selectedCanvasElements();
9370
+ const hostRect = unsysCanvasSelectionHostRect(
9371
+ selected,
9372
+ excalidrawAPIRef.current?.getAppState?.() ?? {}
9373
+ );
9374
+ const pickerOpen = unsysCanvasSlashBarOpen({
9375
+ selectionActive: canvasSelectionActive,
9376
+ slashIntent: slashBarOpen
9377
+ });
9378
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
9379
+ /* @__PURE__ */ jsx(
9380
+ UnsysCanvasCommandPickerAffordance,
9381
+ {
9382
+ visible: canvasSelectionActive && !pickerOpen && Boolean(hostRect),
9383
+ left: Math.round((hostRect?.right ?? 0) + 6),
9384
+ top: Math.round(hostRect?.top ?? 0),
9385
+ onOpen: () => openCommandPickerAt(
9386
+ (hostRect?.right ?? lastPointerHostRef.current.x) + 8,
9387
+ hostRect?.top ?? lastPointerHostRef.current.y
9388
+ )
9389
+ }
9390
+ ),
9391
+ /* @__PURE__ */ jsx(
9392
+ UnsysCanvasCommandPicker,
9393
+ {
9394
+ open: pickerOpen,
9395
+ left: pickerPos.left,
9396
+ top: pickerPos.top,
9397
+ query: commandText,
9398
+ extras: extraCommands,
9399
+ onQueryChange: setCommandText,
9400
+ onClose: () => {
9401
+ setSlashBarOpen(false);
9402
+ setCommandText("");
9403
+ },
9404
+ onRun: (id) => {
9405
+ const selectedForRun = pickerSelectedRef.current;
9406
+ setSlashBarOpen(false);
9407
+ setCommandText("");
9408
+ handleQuickActionRef.current(
9409
+ id,
9410
+ selectedForRun.length ? selectedForRun : void 0
9411
+ );
9412
+ }
9413
+ }
9414
+ )
9415
+ ] });
9416
+ })()
7394
9417
  ]
7395
9418
  }
7396
9419
  )
@@ -7411,51 +9434,6 @@ function ExtraCommandsProvider({
7411
9434
  function useExtraCommands() {
7412
9435
  return useContext(ExtraCommandsContext);
7413
9436
  }
7414
- var UNSYS_CANVAS_COMMAND_RAIL_CLASS = "pointer-events-auto relative flex min-h-9 w-full min-w-0 flex-row items-center justify-start gap-1.5 whitespace-nowrap rounded-none border border-white/45 bg-black px-1.5 py-2 text-left font-mono text-[11px] leading-tight text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.35)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
7415
- var UNSYS_CANVAS_COMMAND_SIDEBAR_CLASS = "pointer-events-auto relative flex min-h-9 w-full min-w-0 flex-row items-center justify-start gap-1.5 overflow-hidden whitespace-nowrap rounded-none border border-white/35 bg-black px-1.5 py-1.5 text-left font-mono text-[11px] leading-tight text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
7416
- var UNSYS_CANVAS_COMMAND_SIDEBAR_MARK_CLASS = "h-3.5 w-3.5 shrink-0";
7417
- var UNSYS_CANVAS_COMMAND_STRIPE_CLASS = "pointer-events-auto relative flex h-10 w-10 shrink-0 items-center justify-center rounded-none border border-white/35 bg-black text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] hover:border-white hover:bg-neutral-950 disabled:cursor-not-allowed disabled:border-neutral-800 disabled:bg-neutral-950 disabled:text-neutral-600 disabled:opacity-100 disabled:shadow-none disabled:hover:border-neutral-800 disabled:hover:bg-neutral-950 disabled:hover:text-neutral-600";
7418
- var UNSYS_CANVAS_COMMAND_STRIPE_MARK_CLASS = "h-4 w-4 shrink-0";
7419
- var ICON_PATHS = {
7420
- focus: "M8 2v2.5M8 11.5V14M2 8h2.5M11.5 8H14M8 5.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z",
7421
- next: "M2 8h9M8 4.5l4.5 3.5L8 11.5M13.5 3.5v9",
7422
- simplify: "M3 4h10M3 8h7M3 12h4",
7423
- breakdown: "M2 6.5h4v3H2zM10 2.5h4v3h-4zM10 10.5h4v3h-4zM6 8h4M10 8V4M10 8v6.5",
7424
- concepts: "M2 2.5h4v3H2zM10 2.5h4v3h-4zM6 10.5h4v3H6zM4 5.5v5M12 5.5v5M8 8.5v2",
7425
- define: "M3 2.5h10v11H3zM5.5 5.5h5M5.5 8h7M5.5 10.5h4",
7426
- answer: "M3 3h10v7H8l-3 3v-3H3z",
7427
- draw: "M10.5 2.5l3 3-8 8H2.5v-3zM9 4l3 3",
7428
- refactor: "M4 3h5v2H6.5A4.5 4.5 0 1 1 3 10M12 13H7v-2h2.5A4.5 4.5 0 1 1 13 6",
7429
- dictate: "M8 2.5a2 2 0 0 1 2 2V8a2 2 0 1 1-4 0V4.5a2 2 0 0 1 2-2zM5 8.5a3 3 0 0 0 6 0M8 11.5V14",
7430
- pointer: "M4.2 8.2a3.6 3.6 0 1 1 3.6-3.6l5.8 5.8a2.2 2.2 0 0 1-3.1 3.1zM9.4 9.4l2.1 2.1M7 7.2l1.3 1.3M4.8 4.8l1.8 1.8",
7431
- commit: "M3 8h10M10 5l3 3-3 3",
7432
- "rail-expand": "M6 3l5 5-5 5",
7433
- "rail-collapse": "M10 3L5 8l5 5",
7434
- boards: "M2.5 3.5h4.5v4.5H2.5zM9 3.5h4.5v4.5H9zM2.5 10h4.5v3H2.5zM9 10h4.5v3H9z",
7435
- save: "M3 8.5V13h10V8.5M8 2.5v8M5 8l3 3 3-3"
7436
- };
7437
- function CommandMark({
7438
- id,
7439
- className = "h-3.5 w-3.5"
7440
- }) {
7441
- const d = ICON_PATHS[id] ?? ICON_PATHS.simplify;
7442
- return /* @__PURE__ */ jsx(
7443
- "svg",
7444
- {
7445
- viewBox: "0 0 16 16",
7446
- className,
7447
- fill: "none",
7448
- stroke: "currentColor",
7449
- strokeWidth: 1.4,
7450
- strokeLinecap: "round",
7451
- strokeLinejoin: "round",
7452
- "aria-hidden": true,
7453
- "data-unsys-canvas-command-mark": id,
7454
- "data-command-icon": id,
7455
- children: /* @__PURE__ */ jsx("path", { d })
7456
- }
7457
- );
7458
- }
7459
9437
  function dictateButtonClass(kind, square, wide, plate, iconOnly) {
7460
9438
  const pressed = kind === "idle" ? " aria-pressed:bg-white aria-pressed:text-neutral-950" : "";
7461
9439
  if (iconOnly) return `${UNSYS_CANVAS_COMMAND_STRIPE_CLASS}${pressed}`;
@@ -7701,12 +9679,30 @@ function CanvasCommandCheatsheet({
7701
9679
  /* @__PURE__ */ jsx("kbd", { "data-shortcut-alt": command.shortcut, className: "text-white/40", children: unsysCanvasCommandShortcutAltLabel(command.shortcut) })
7702
9680
  ] })
7703
9681
  ] }),
7704
- /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: command.tooltip })
9682
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: command.tooltip }),
9683
+ command.gestureHint ? /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[10px] leading-snug text-white/50", children: command.gestureHint }) : null
7705
9684
  ] })
7706
9685
  ]
7707
9686
  },
7708
9687
  command.id
7709
9688
  )),
9689
+ /* @__PURE__ */ jsxs(
9690
+ "li",
9691
+ {
9692
+ "data-unsys-canvas-command-cheatsheet-row": "picker",
9693
+ className: "flex items-start gap-2 border border-white/20 px-2 py-2",
9694
+ children: [
9695
+ /* @__PURE__ */ jsx(CommandMark, { id: "picker", label: UNSYS_CANVAS_COMMAND_PICKER_LABEL, className: "mt-0.5 h-4 w-4 shrink-0" }),
9696
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
9697
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
9698
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-[12px] font-semibold", children: UNSYS_CANVAS_COMMAND_PICKER_LABEL }),
9699
+ /* @__PURE__ */ jsx("span", { className: "flex shrink-0 items-baseline gap-1.5 font-mono text-[10px] text-white/55", children: /* @__PURE__ */ jsx("kbd", { "data-shortcut-apple": UNSYS_CANVAS_COMMAND_PICKER_SHORTCUT, children: UNSYS_CANVAS_COMMAND_PICKER_SHORTCUT }) })
9700
+ ] }),
9701
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: UNSYS_CANVAS_COMMAND_PICKER_TOOLTIP })
9702
+ ] })
9703
+ ]
9704
+ }
9705
+ ),
7710
9706
  /* @__PURE__ */ jsxs(
7711
9707
  "li",
7712
9708
  {
@@ -7727,7 +9723,33 @@ function CanvasCommandCheatsheet({
7727
9723
  ]
7728
9724
  }
7729
9725
  )
7730
- ] })
9726
+ ] }),
9727
+ /* @__PURE__ */ jsx("h3", { className: "mb-2 mt-4 font-mono text-[11px] font-semibold uppercase tracking-[0.16em] text-white/80", children: "Pointer gestures" }),
9728
+ /* @__PURE__ */ jsx("ul", { className: "flex flex-col gap-2", children: UNSYS_CANVAS_LASER_GESTURES.map((row) => /* @__PURE__ */ jsxs(
9729
+ "li",
9730
+ {
9731
+ "data-unsys-canvas-command-cheatsheet-gesture": row.command,
9732
+ className: "flex items-start gap-2 border border-white/20 px-2 py-2",
9733
+ children: [
9734
+ /* @__PURE__ */ jsx(
9735
+ CommandMark,
9736
+ {
9737
+ id: row.command,
9738
+ label: row.label,
9739
+ className: "mt-0.5 h-4 w-4 shrink-0"
9740
+ }
9741
+ ),
9742
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
9743
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
9744
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-[12px] font-semibold", children: row.label }),
9745
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 font-mono text-[10px] text-white/55", children: row.gesture })
9746
+ ] }),
9747
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: row.hint })
9748
+ ] })
9749
+ ]
9750
+ },
9751
+ row.command
9752
+ )) })
7731
9753
  ]
7732
9754
  }
7733
9755
  )
@@ -7736,7 +9758,7 @@ function CanvasCommandCheatsheet({
7736
9758
  }
7737
9759
 
7738
9760
  // src/lib/session-instructions.ts
7739
- var CANVAS_HELP = "Write and draw on the board. Select marks, then run a command. Dictate places a Work note from speech. The pointer laser can Simplify, Concepts, or Subdivide.";
9761
+ var CANVAS_HELP = "Write and draw on the board. Select marks, then run a command. / opens the command picker. Dictate places a Work note from speech. The pointer laser can Simplify, Concepts, Subdivide, Do/run, Refactor, or Pretty.";
7740
9762
  var SESSION_INSTRUCTIONS = {
7741
9763
  board: CANVAS_HELP
7742
9764
  };
@@ -7901,6 +9923,7 @@ function UnsysCanvas({
7901
9923
  onEvent,
7902
9924
  onCanvasEvents,
7903
9925
  onAsk,
9926
+ runModel,
7904
9927
  style,
7905
9928
  slots,
7906
9929
  commands,
@@ -7910,9 +9933,7 @@ function UnsysCanvas({
7910
9933
  className,
7911
9934
  ...boardProps
7912
9935
  }) {
7913
- if (typeof onAsk !== "function") {
7914
- throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
7915
- }
9936
+ assertCanvasModel({ onAsk, runModel });
7916
9937
  const resolvedStyle = parseUnsysCanvasStyle(style);
7917
9938
  const cssVars = unsysCanvasSidebarStyleCssVars(resolvedStyle);
7918
9939
  const hideRail = slots && "rail" in slots && slots.rail === null;
@@ -7977,6 +9998,7 @@ function UnsysCanvas({
7977
9998
  onSceneChange,
7978
9999
  onEvent: onEvent ?? onCanvasEvents,
7979
10000
  onAsk,
10001
+ runModel,
7980
10002
  style: resolvedStyle,
7981
10003
  extraCommands: commands,
7982
10004
  liveCanvasChrome: true
@@ -8033,142 +10055,95 @@ function CanvasTopicCard({
8033
10055
  );
8034
10056
  }
8035
10057
 
8036
- // src/lib/work-canvas/work-canvas-url.ts
8037
- var UNSYS_CANVAS_HASH_PREFIX = "tc1.";
8038
- var UNSYS_CANVAS_MAX_HASH_LENGTH = 75e4;
8039
- function unsysCanvasUrlSnapshot(scene) {
8040
- const serialized = serializeUnsysCanvasScene(scene);
8041
- const elements = serialized.elements.filter((el) => el && !el.isDeleted);
8042
- const usedFileIds = new Set(
8043
- elements.map((el) => typeof el.fileId === "string" ? el.fileId : "").filter(Boolean)
8044
- );
8045
- const files = {};
8046
- for (const [id, file] of Object.entries(serialized.files || {})) {
8047
- if (usedFileIds.has(id)) files[id] = file;
8048
- }
8049
- return {
8050
- elements,
8051
- appState: serialized.appState,
8052
- files
8053
- };
8054
- }
8055
- async function encodeUnsysCanvasHash(scene, options) {
8056
- const maxHashLength = options?.maxHashLength ?? UNSYS_CANVAS_MAX_HASH_LENGTH;
8057
- const snapshot2 = unsysCanvasUrlSnapshot(scene);
8058
- if (!unsysCanvasHasLiveElements(snapshot2)) {
8059
- return { kind: "empty", hash: "" };
8060
- }
8061
- const withFiles = await hashFromPayload({
8062
- v: 1,
8063
- elements: snapshot2.elements,
8064
- appState: snapshot2.appState,
8065
- files: Object.keys(snapshot2.files).length ? snapshot2.files : void 0
8066
- });
8067
- if (withFiles && withFiles.length <= maxHashLength) {
8068
- return { kind: "ok", hash: withFiles };
8069
- }
8070
- const withoutFiles = await hashFromPayload({
8071
- v: 1,
8072
- elements: snapshot2.elements,
8073
- appState: snapshot2.appState
8074
- });
8075
- if (withoutFiles && withoutFiles.length <= maxHashLength) {
8076
- return { kind: "omitted-files", hash: withoutFiles };
8077
- }
8078
- return { kind: "too-large", hash: "" };
8079
- }
8080
- async function decodeUnsysCanvasHash(hash) {
8081
- const payload = hashPayload(hash);
8082
- if (!payload) return null;
8083
- try {
8084
- const bytes = await gunzipBytes(base64UrlToBytes(payload));
8085
- const parsed = JSON.parse(new TextDecoder().decode(bytes));
8086
- return sceneFromPayload(parsed);
8087
- } catch {
8088
- return null;
8089
- }
8090
- }
8091
- async function readUnsysCanvasHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
8092
- return decodeUnsysCanvasHash(hash);
8093
- }
8094
- function replaceUnsysCanvasLocationHash(hash) {
8095
- if (typeof window === "undefined") return;
8096
- const next = normalizeHash(hash);
8097
- const current = window.location.hash || "";
8098
- if (current === next) return;
8099
- const url = `${window.location.pathname}${window.location.search}${next}`;
8100
- window.history.replaceState(window.history.state, "", url);
8101
- }
8102
- function hashPayload(hash) {
8103
- const raw = String(hash || "").trim();
8104
- const body = raw.startsWith("#") ? raw.slice(1) : raw;
8105
- if (!body.startsWith(UNSYS_CANVAS_HASH_PREFIX)) return null;
8106
- const payload = body.slice(UNSYS_CANVAS_HASH_PREFIX.length);
8107
- return payload || null;
8108
- }
8109
- function normalizeHash(hash) {
8110
- if (!hash) return "";
8111
- return hash.startsWith("#") ? hash : `#${hash}`;
8112
- }
8113
- async function hashFromPayload(payload) {
8114
- try {
8115
- const json = JSON.stringify(payload);
8116
- const compressed = await gzipBytes(new TextEncoder().encode(json));
8117
- return `#${UNSYS_CANVAS_HASH_PREFIX}${bytesToBase64Url(compressed)}`;
8118
- } catch {
8119
- return null;
8120
- }
8121
- }
8122
- function sceneFromPayload(parsed) {
8123
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
8124
- const rec = parsed;
8125
- if (rec.v !== 1) return null;
8126
- if (!Array.isArray(rec.elements)) return null;
8127
- return serializeUnsysCanvasScene({
8128
- elements: rec.elements,
8129
- appState: rec.appState,
8130
- files: rec.files
10058
+ // src/lib/collaboration/memory-transport.ts
10059
+ function createUnsysCanvasMemoryTransportHub() {
10060
+ const peers = /* @__PURE__ */ new Map();
10061
+ let nextId = 1;
10062
+ const createTransport = () => ({
10063
+ open(roomId, handlers) {
10064
+ const id = nextId;
10065
+ nextId += 1;
10066
+ const peer = { id, roomId, handlers };
10067
+ peers.set(id, peer);
10068
+ queueMicrotask(() => {
10069
+ if (peers.get(id) === peer) handlers.onOpen?.();
10070
+ });
10071
+ return {
10072
+ send(bytes) {
10073
+ const copy = new Uint8Array(bytes);
10074
+ for (const other of peers.values()) {
10075
+ if (other.id === id || other.roomId !== roomId) continue;
10076
+ other.handlers.onMessage(copy);
10077
+ }
10078
+ },
10079
+ close() {
10080
+ peers.delete(id);
10081
+ handlers.onClose?.();
10082
+ }
10083
+ };
10084
+ }
8131
10085
  });
10086
+ return { createTransport };
8132
10087
  }
8133
- async function gzipBytes(bytes) {
8134
- const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(new CompressionStream("gzip"));
8135
- return new Uint8Array(await new Response(stream).arrayBuffer());
8136
- }
8137
- async function gunzipBytes(bytes) {
8138
- const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(
8139
- new DecompressionStream("gzip")
8140
- );
8141
- return new Uint8Array(await new Response(stream).arrayBuffer());
8142
- }
8143
- function toArrayBuffer(bytes) {
8144
- const copy = new Uint8Array(bytes.byteLength);
8145
- copy.set(bytes);
8146
- return copy.buffer;
8147
- }
8148
- function bytesToBase64Url(bytes) {
8149
- const chunk = 8192;
8150
- let binary = "";
8151
- for (let i = 0; i < bytes.length; i += chunk) {
8152
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
8153
- }
8154
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
10088
+
10089
+ // src/lib/collaboration/websocket-transport.ts
10090
+ function asBytes(data) {
10091
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
10092
+ if (data instanceof Uint8Array) return data;
10093
+ if (typeof Blob !== "undefined" && data instanceof Blob) return null;
10094
+ return null;
8155
10095
  }
8156
- function base64UrlToBytes(value) {
8157
- const padded = value.replace(/-/g, "+").replace(/_/g, "/");
8158
- const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
8159
- const binary = atob(padded + pad);
8160
- const bytes = new Uint8Array(binary.length);
8161
- for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
8162
- return bytes;
10096
+ function createUnsysCanvasWebsocketTransport(options) {
10097
+ const url = String(options.url || "").trim();
10098
+ return {
10099
+ open(roomId, handlers) {
10100
+ if (!url || typeof WebSocket === "undefined") {
10101
+ queueMicrotask(() => handlers.onError?.(new Error("Collaboration relay URL is missing.")));
10102
+ return { send() {
10103
+ }, close() {
10104
+ } };
10105
+ }
10106
+ const ws = new WebSocket(url);
10107
+ ws.binaryType = "arraybuffer";
10108
+ let opened = false;
10109
+ ws.onopen = () => {
10110
+ opened = true;
10111
+ ws.send(JSON.stringify({ type: "join", roomId }));
10112
+ handlers.onOpen?.();
10113
+ };
10114
+ ws.onmessage = (event) => {
10115
+ if (typeof event.data === "string") return;
10116
+ const bytes = asBytes(event.data);
10117
+ if (bytes) handlers.onMessage(bytes);
10118
+ };
10119
+ ws.onerror = () => {
10120
+ handlers.onError?.(new Error("Collaboration relay error."));
10121
+ };
10122
+ ws.onclose = () => {
10123
+ if (opened) handlers.onClose?.();
10124
+ };
10125
+ return {
10126
+ send(bytes) {
10127
+ if (ws.readyState !== WebSocket.OPEN) return;
10128
+ const copy = new Uint8Array(bytes.byteLength);
10129
+ copy.set(bytes);
10130
+ ws.send(copy);
10131
+ },
10132
+ close() {
10133
+ try {
10134
+ ws.close();
10135
+ } catch {
10136
+ }
10137
+ }
10138
+ };
10139
+ }
10140
+ };
8163
10141
  }
8164
-
8165
- // src/lib/require-onask.ts
8166
- function assertOnAsk(onAsk) {
8167
- if (typeof onAsk !== "function") {
8168
- throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
8169
- }
10142
+ function isUnsysCanvasRelayUrl(value) {
10143
+ const url = String(value || "").trim();
10144
+ return url.startsWith("ws://") || url.startsWith("wss://");
8170
10145
  }
8171
10146
 
8172
- export { CanvasCommandRail, CanvasTopicCard, CommandMark, DEFAULT_UNSYS_CANVAS_BOARD_STYLE, DEFAULT_UNSYS_CANVAS_STYLE_TOKENS, EMPTY_UNSYS_CANVAS_STYLE, ExcalidrawCanvas, UNSYS_CANVAS_COMMANDS, UNSYS_CANVAS_COMMAND_SIDEBAR_CLASS, UNSYS_CANVAS_COMMAND_SIDEBAR_MARK_CLASS, UNSYS_CANVAS_COMMAND_STRIPE_CLASS, UNSYS_CANVAS_COMMAND_STRIPE_MARK_CLASS, UNSYS_CANVAS_EVENT_TYPES, UNSYS_CANVAS_HASH_PREFIX, UnsysCanvas, UnsysCanvasEventCollector, WorkCanvas, applyUnsysCanvasAskReply, assertOnAsk, buildUnsysCanvasCommandUserMessage, convertToExcalidrawElements, decodeUnsysCanvasHash, emptyUnsysCanvasScene, encodeUnsysCanvasHash, normalizeUnsysCanvasLinearElement, parseUnsysCanvasAskReply, parseUnsysCanvasStyle, readUnsysCanvasHashFromLocation, replaceUnsysCanvasLocationHash, runUnsysCanvasCommand, serializeUnsysCanvasScene, unsysCanvasAskFromSessionChat, unsysCanvasCommandsFor, unsysCanvasHasLiveElements, unsysCanvasSidebarStyleCssVars, unsysCanvasTurnContextMessage, unsysCanvasXaiFetchTimeout, unsysCanvasXaiMaxTokens, unsysCanvasXaiNeedsBoardContext };
10147
+ export { CanvasCommandRail, CanvasTopicCard, CommandMark, DEFAULT_UNSYS_CANVAS_BOARD_STYLE, DEFAULT_UNSYS_CANVAS_STYLE_TOKENS, EMPTY_UNSYS_CANVAS_STYLE, ExcalidrawCanvas, UNSYS_CANVAS_COLLAB_HASH_PREFIX, UNSYS_CANVAS_COMMANDS, UNSYS_CANVAS_COMMAND_SIDEBAR_CLASS, UNSYS_CANVAS_COMMAND_SIDEBAR_MARK_CLASS, UNSYS_CANVAS_COMMAND_STRIPE_CLASS, UNSYS_CANVAS_COMMAND_STRIPE_MARK_CLASS, UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT, UNSYS_CANVAS_EVENT_TYPES, UNSYS_CANVAS_HASH_PREFIX, UnsysCanvas, UnsysCanvasCollabSession, UnsysCanvasEventCollector, WorkCanvas, applyUnsysCanvasAskReply, assertCanvasModel, assertOnAsk, buildUnsysCanvasCollabHash, buildUnsysCanvasCollabShareUrl, buildUnsysCanvasCommandPrompt, buildUnsysCanvasCommandUserMessage, buildUnsysCanvasModelRequest, convertToExcalidrawElements, createUnsysCanvasMemoryTransportHub, createUnsysCanvasModelProxyRunner, createUnsysCanvasWebsocketTransport, createUnsysCanvasXaiBrowserRunner, decodeUnsysCanvasHash, decryptUnsysCanvasCollabJson, emptyUnsysCanvasScene, encodeUnsysCanvasHash, encryptUnsysCanvasCollabJson, extractUnsysCanvasCommandContext, generateUnsysCanvasCollabRoom, getUnsysCanvasCommand, handleCanvasModelHttpRequest, handleCanvasModelRequest, isUnsysCanvasCollabHash, isUnsysCanvasKnownCommandId, isUnsysCanvasRelayUrl, listUnsysCanvasCommandDefinitions, normalizeUnsysCanvasLinearElement, parseUnsysCanvasAskReply, parseUnsysCanvasCollabHash, parseUnsysCanvasCommandResponse, parseUnsysCanvasModelClientBody, parseUnsysCanvasStyle, readUnsysCanvasCollabHashFromLocation, readUnsysCanvasHashFromLocation, reconcileUnsysCanvasElements, reconcileUnsysCanvasFiles, reconcileUnsysCanvasScene, replaceUnsysCanvasCollabLocationHash, replaceUnsysCanvasLocationHash, runUnsysCanvasCommand, runUnsysCanvasModelAsk, serializeUnsysCanvasScene, unsysCanvasAskFromSessionChat, unsysCanvasCommandPlacement, unsysCanvasCommandsFor, unsysCanvasGestureCommandId, unsysCanvasHasLiveElements, unsysCanvasSidebarStyleCssVars, unsysCanvasTurnContextMessage, unsysCanvasXaiFetchTimeout, unsysCanvasXaiMaxTokens, unsysCanvasXaiNeedsBoardContext };
8173
10148
  //# sourceMappingURL=index.js.map
8174
10149
  //# sourceMappingURL=index.js.map