unsys-canvas 0.1.2 → 0.2.1

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":
@@ -1988,6 +2007,11 @@ function unsysCanvasZoomAtPoint(input) {
1988
2007
  scrollY: baseScrollY - (appLayerY - appLayerY / nextZoom)
1989
2008
  };
1990
2009
  }
2010
+ function clampUnsysRange(value, min, max) {
2011
+ if (!Number.isFinite(value)) return min;
2012
+ if (max < min) return min;
2013
+ return Math.min(max, Math.max(min, value));
2014
+ }
1991
2015
  function unsysCanvasSceneToViewport(scene, appState) {
1992
2016
  const zoom = unsysCanvasZoomValue(appState);
1993
2017
  const scrollX = Number(appState?.scrollX) || 0;
@@ -2056,12 +2080,74 @@ function unsysCanvasRevealScroll(elements, appState, pad = 40) {
2056
2080
  }
2057
2081
  return { scrollX, scrollY };
2058
2082
  }
2083
+ function unsysCanvasSelectionViewportRect(elements, appState) {
2084
+ const bounds = unsysCanvasContentBounds(elements);
2085
+ if (!bounds) return null;
2086
+ const topLeft = unsysCanvasSceneToViewport({ x: bounds.minX, y: bounds.minY }, appState);
2087
+ const bottomRight = unsysCanvasSceneToViewport({ x: bounds.maxX, y: bounds.maxY }, appState);
2088
+ return {
2089
+ left: Math.min(topLeft.x, bottomRight.x),
2090
+ top: Math.min(topLeft.y, bottomRight.y),
2091
+ right: Math.max(topLeft.x, bottomRight.x),
2092
+ bottom: Math.max(topLeft.y, bottomRight.y)
2093
+ };
2094
+ }
2059
2095
  function unsysCanvasViewportToHost(point, host) {
2060
2096
  return {
2061
2097
  x: point.x - (Number(host?.left) || 0),
2062
2098
  y: point.y - (Number(host?.top) || 0)
2063
2099
  };
2064
2100
  }
2101
+ function unsysCanvasSelectionHostRect(elements, appState, host) {
2102
+ const rect = unsysCanvasSelectionViewportRect(elements, appState);
2103
+ if (!rect) return null;
2104
+ const originLeft = Number(host?.left) || 0;
2105
+ const originTop = Number(host?.top) || 0;
2106
+ return {
2107
+ left: rect.left - originLeft,
2108
+ top: rect.top - originTop,
2109
+ right: rect.right - originLeft,
2110
+ bottom: rect.bottom - originTop
2111
+ };
2112
+ }
2113
+ var UNSYS_CANVAS_COMMAND_PICKER_WIDTH = 264;
2114
+ var UNSYS_CANVAS_COMMAND_PICKER_HEIGHT = 220;
2115
+ var UNSYS_CANVAS_COMMAND_PICKER_GAP = 8;
2116
+ var UNSYS_CANVAS_COMMAND_PICKER_PAD = 8;
2117
+ var UNSYS_CANVAS_COMMAND_PICKER_AFFORDANCE_SIZE = 24;
2118
+ function placeUnsysCanvasCommandPicker(input) {
2119
+ const pad = input.pad ?? UNSYS_CANVAS_COMMAND_PICKER_PAD;
2120
+ const gap = input.gap ?? UNSYS_CANVAS_COMMAND_PICKER_GAP;
2121
+ const boxW = input.box?.width ?? UNSYS_CANVAS_COMMAND_PICKER_WIDTH;
2122
+ const boxH = input.box?.height ?? UNSYS_CANVAS_COMMAND_PICKER_HEIGHT;
2123
+ const viewW = Math.max(0, Number(input.viewport.width) || 0);
2124
+ const viewH = Math.max(0, Number(input.viewport.height) || 0);
2125
+ const maxLeft = Math.max(pad, viewW - boxW - pad);
2126
+ const maxTop = Math.max(pad, viewH - boxH - pad);
2127
+ const clamp = (left2, top2) => ({
2128
+ left: Math.round(clampUnsysRange(left2, pad, maxLeft)),
2129
+ top: Math.round(clampUnsysRange(top2, pad, maxTop))
2130
+ });
2131
+ const sel = input.selection;
2132
+ if (!sel) {
2133
+ const pointer = input.pointer ?? { x: pad, y: pad };
2134
+ return clamp(Number(pointer.x) || 0, Number(pointer.y) || 0);
2135
+ }
2136
+ const left = sel.left;
2137
+ let top = sel.bottom + gap;
2138
+ if (top + boxH + pad > viewH) top = sel.top - gap - boxH;
2139
+ return clamp(left, top);
2140
+ }
2141
+ function placeUnsysCanvasCommandPickerAffordance(input) {
2142
+ const size = input.size ?? UNSYS_CANVAS_COMMAND_PICKER_AFFORDANCE_SIZE;
2143
+ return placeUnsysCanvasCommandPicker({
2144
+ selection: input.selection,
2145
+ viewport: input.viewport,
2146
+ box: { width: size, height: size },
2147
+ gap: input.gap,
2148
+ pad: input.pad
2149
+ });
2150
+ }
2065
2151
  function ileLearnMoreSelectionKey(selectedElementIds) {
2066
2152
  return Object.keys(selectedElementIds ?? {}).filter((id) => Boolean(selectedElementIds?.[id])).sort().join(",");
2067
2153
  }
@@ -2073,7 +2159,8 @@ function unsysCanvasSlashBarOpen(input) {
2073
2159
  }
2074
2160
  function unsysCanvasSlashKeyOpensBar(input) {
2075
2161
  if (input.typingInField) return false;
2076
- return input.key === "/" && Boolean(input.selectionActive);
2162
+ if (!input.selectionActive) return false;
2163
+ return input.key === "/";
2077
2164
  }
2078
2165
 
2079
2166
  // src/lib/work-canvas/work-canvas-xai-parse.ts
@@ -2883,6 +2970,8 @@ var UNSYS_CANVAS_COMMANDS = [
2883
2970
  label: "Simplify",
2884
2971
  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
2972
  shortcut: "s",
2973
+ gesture: "question-mark",
2974
+ gestureHint: "Laser: question mark over a mark.",
2886
2975
  needsSelection: true,
2887
2976
  boardOnly: false,
2888
2977
  replacesSelection: false
@@ -2892,6 +2981,8 @@ var UNSYS_CANVAS_COMMANDS = [
2892
2981
  label: "Subdivide",
2893
2982
  tooltip: "Keep the original mark and fan its parts into smaller nodes, linked with arrows.",
2894
2983
  shortcut: "b",
2984
+ gesture: "double-line",
2985
+ gestureHint: "Laser: two quick lines from a mark into empty space.",
2895
2986
  needsSelection: true,
2896
2987
  boardOnly: false,
2897
2988
  replacesSelection: false
@@ -2901,6 +2992,8 @@ var UNSYS_CANVAS_COMMANDS = [
2901
2992
  label: "Concepts",
2902
2993
  tooltip: "Keep the original and fan its named concepts into linked nodes.",
2903
2994
  shortcut: "c",
2995
+ gesture: "line",
2996
+ gestureHint: "Laser: line from a mark into empty space.",
2904
2997
  needsSelection: true,
2905
2998
  boardOnly: false,
2906
2999
  replacesSelection: false
@@ -2911,6 +3004,8 @@ var UNSYS_CANVAS_COMMANDS = [
2911
3004
  slash: "run",
2912
3005
  tooltip: "Work the highlighted problem: carry it out, compute it, or show the result.",
2913
3006
  shortcut: "d",
3007
+ gesture: "loop",
3008
+ gestureHint: "Laser: circle or loop over a mark.",
2914
3009
  needsSelection: true,
2915
3010
  boardOnly: false,
2916
3011
  replacesSelection: false
@@ -2920,12 +3015,28 @@ var UNSYS_CANVAS_COMMANDS = [
2920
3015
  label: "Refactor",
2921
3016
  tooltip: "Delete the selected marks and replace them with a clearer rewrite.",
2922
3017
  shortcut: "r",
3018
+ gesture: "zigzag",
3019
+ gestureHint: "Laser: zigzag over a mark.",
2923
3020
  needsSelection: true,
2924
3021
  boardOnly: false,
2925
3022
  replacesSelection: true
3023
+ },
3024
+ {
3025
+ id: "pretty",
3026
+ label: "Pretty",
3027
+ tooltip: "Keep the original marks and place a tidied, well-formatted Excalidraw note next to them.",
3028
+ shortcut: "p",
3029
+ gesture: "check",
3030
+ gestureHint: "Laser: check mark over a mark.",
3031
+ needsSelection: true,
3032
+ boardOnly: false,
3033
+ replacesSelection: false
2926
3034
  }
2927
3035
  ];
2928
3036
  var UNSYS_CANVAS_CHEATSHEET_LABEL = "Command cheat sheet";
3037
+ var UNSYS_CANVAS_COMMAND_PICKER_LABEL = "Command picker";
3038
+ var UNSYS_CANVAS_COMMAND_PICKER_SHORTCUT = "/";
3039
+ 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
3040
  function unsysCanvasCommandsFor(_guide, extras = []) {
2930
3041
  const catalog = UNSYS_CANVAS_COMMANDS.map((command) => ({ ...command }));
2931
3042
  const seen = new Set(catalog.map((command) => command.id));
@@ -2942,6 +3053,8 @@ function unsysCanvasCommandsFor(_guide, extras = []) {
2942
3053
  boardOnly: false,
2943
3054
  replacesSelection: false,
2944
3055
  slash: extra.slash,
3056
+ gesture: extra.gesture,
3057
+ gestureHint: extra.gestureHint,
2945
3058
  run: extra.run
2946
3059
  });
2947
3060
  }
@@ -3003,6 +3116,33 @@ function filterUnsysCanvasCommands(query, guide, extras = []) {
3003
3116
  (command) => unsysCanvasCommandMatchNames(command).some((name) => name.startsWith(q))
3004
3117
  );
3005
3118
  }
3119
+ function unsysCanvasFuzzySubsequence(name, query) {
3120
+ let i = 0;
3121
+ for (const ch of name) {
3122
+ if (ch === query[i]) i += 1;
3123
+ if (i >= query.length) return true;
3124
+ }
3125
+ return false;
3126
+ }
3127
+ function unsysCanvasCommandFuzzyScore(command, query) {
3128
+ const q = String(query || "").trim().toLowerCase();
3129
+ if (!q) return 1;
3130
+ if (command.shortcut && command.shortcut.toLowerCase() === q) return 100;
3131
+ let best = 0;
3132
+ for (const name of unsysCanvasCommandMatchNames(command)) {
3133
+ if (name === q) best = Math.max(best, 90);
3134
+ else if (name.startsWith(q)) best = Math.max(best, 80);
3135
+ else if (name.includes(q)) best = Math.max(best, 50);
3136
+ else if (unsysCanvasFuzzySubsequence(name, q)) best = Math.max(best, 20);
3137
+ }
3138
+ return best;
3139
+ }
3140
+ function fuzzyFilterUnsysCanvasCommands(query, guide, extras = []) {
3141
+ const catalog = unsysCanvasCommandsFor(guide, extras);
3142
+ const q = String(query || "").trim().toLowerCase();
3143
+ if (!q) return catalog;
3144
+ 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);
3145
+ }
3006
3146
  function unsysCanvasCommandDraft(raw) {
3007
3147
  const trimmed = String(raw ?? "").trim();
3008
3148
  if (!trimmed.startsWith("/")) {
@@ -3115,6 +3255,7 @@ function unsysCanvasBindFanArrow(arrow, start, end, hostBounds) {
3115
3255
  function unsysCanvasFanNoteKind(mark) {
3116
3256
  if (mark === "ileConcepts") return "concepts";
3117
3257
  if (mark === "ileSimplify") return "simplify";
3258
+ if (mark === "ilePretty") return "pretty";
3118
3259
  return "breakdown";
3119
3260
  }
3120
3261
  function unsysCanvasFanStem(host, hostRect, end, toX, toY, mark, hostBounds) {
@@ -3274,6 +3415,80 @@ function fanUnsysCanvasLabeledNodes(scene, selectedElements, chunks, mark) {
3274
3415
  parts
3275
3416
  };
3276
3417
  }
3418
+ function placeUnsysCanvasPrettyReply(scene, selectedElements, payload) {
3419
+ const current = serializeUnsysCanvasScene(scene);
3420
+ const extra = normalizeExtraSkeletons(payload.elements);
3421
+ const text = String(payload.text || "").trim();
3422
+ if (extra.length) {
3423
+ const found = unsysCanvasFanHost(current, selectedElements);
3424
+ if (!found) return { scene: current, placed: false, parts: [] };
3425
+ const { host, expanded } = found;
3426
+ const hostRect = unsysCanvasNormalizedRect(host) ?? {
3427
+ minX: Number(host.x) || 0,
3428
+ minY: Number(host.y) || 0,
3429
+ maxX: (Number(host.x) || 0) + Math.max(1, Number(host.width) || 0),
3430
+ maxY: (Number(host.y) || 0) + Math.max(1, Number(host.height) || 0)
3431
+ };
3432
+ const created = [];
3433
+ for (const item of extra) {
3434
+ const converted = convertToExcalidrawElements([
3435
+ {
3436
+ ...item,
3437
+ customData: { ...item.customData ?? {}, ilePretty: true }
3438
+ }
3439
+ ]);
3440
+ created.push(...converted);
3441
+ }
3442
+ if (!created.length) return { scene: current, placed: false, parts: [] };
3443
+ const box = unsysCanvasContentBounds(created);
3444
+ const gapX = UNSYS_CANVAS_OVERLAP_GAP + 48;
3445
+ const dx = hostRect.maxX + gapX - (box?.minX ?? 0);
3446
+ const dy = hostRect.minY - (box?.minY ?? 0);
3447
+ for (const el of created) {
3448
+ el.x = Number(el.x) + dx;
3449
+ el.y = Number(el.y) + dy;
3450
+ }
3451
+ const settledNodes = settleUnsysCanvasIncoming(
3452
+ created,
3453
+ current.elements.filter((el) => !el.isDeleted)
3454
+ );
3455
+ const bind = settledNodes.find((el) => el.type === "frame" || el.type === "rectangle") ?? settledNodes.find((el) => el.type !== "arrow" && el.type !== "line") ?? settledNodes[0];
3456
+ const nodeHosts = bind ? [bind] : [];
3457
+ const { connectors, hostBounds } = unsysCanvasFanConnectors(
3458
+ host,
3459
+ hostRect,
3460
+ settledNodes,
3461
+ nodeHosts,
3462
+ "ilePretty"
3463
+ );
3464
+ const hostNext = {
3465
+ ...host,
3466
+ boundElements: hostBounds,
3467
+ version: (Number(host.version) || 1) + 1
3468
+ };
3469
+ const parts = [...settledNodes, ...connectors];
3470
+ return {
3471
+ scene: {
3472
+ ...current,
3473
+ elements: [
3474
+ ...current.elements.map((el) => el.id === host.id ? hostNext : el),
3475
+ ...parts
3476
+ ],
3477
+ appState: {
3478
+ ...current.appState,
3479
+ selectedElementIds: Object.fromEntries(
3480
+ expanded.filter((el) => el.id && !el.isDeleted).map((el) => [el.id, true])
3481
+ )
3482
+ }
3483
+ },
3484
+ placed: true,
3485
+ parts
3486
+ };
3487
+ }
3488
+ if (!text) return { scene: current, placed: false, parts: [] };
3489
+ const fanned = fanUnsysCanvasLabeledNodes(current, selectedElements, [text], "ilePretty");
3490
+ return { scene: fanned.scene, placed: fanned.split, parts: fanned.parts };
3491
+ }
3277
3492
  function breakdownUnsysCanvasSelection(scene, selectedElements) {
3278
3493
  const current = serializeUnsysCanvasScene(scene);
3279
3494
  const expanded = expandUnsysCanvasCommandSelection(current, selectedElements);
@@ -3290,6 +3505,7 @@ function unsysCanvasCommandPrompt(action) {
3290
3505
  if (action === "draw") return "Do/run";
3291
3506
  if (action === "breakdown") return "Subdivide";
3292
3507
  if (action === "concepts") return "Concepts";
3508
+ if (action === "pretty") return "Pretty";
3293
3509
  return action;
3294
3510
  }
3295
3511
  function unsysCanvasPlacedHarnessNext(scene) {
@@ -3411,6 +3627,9 @@ function runUnsysCanvasCommand(input) {
3411
3627
  if (input.action === "draw") {
3412
3628
  return idle(null, { kind: "draw", prompt });
3413
3629
  }
3630
+ if (input.action === "pretty") {
3631
+ return idle(null, { kind: "pretty", prompt });
3632
+ }
3414
3633
  return idle(null);
3415
3634
  }
3416
3635
  var CommandContext = createContext(null);
@@ -3529,6 +3748,185 @@ function CanvasPromptBar({
3529
3748
  useEffect(() => () => publishCommands(null), [publishCommands]);
3530
3749
  return null;
3531
3750
  }
3751
+ 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";
3752
+ 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";
3753
+ var UNSYS_CANVAS_COMMAND_SIDEBAR_MARK_CLASS = "h-3.5 w-3.5 shrink-0";
3754
+ 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";
3755
+ var UNSYS_CANVAS_COMMAND_STRIPE_MARK_CLASS = "h-4 w-4 shrink-0";
3756
+ var ICON_PATHS = {
3757
+ 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",
3758
+ next: "M2 8h9M8 4.5l4.5 3.5L8 11.5M13.5 3.5v9",
3759
+ simplify: "M3 4h10M3 8h7M3 12h4",
3760
+ breakdown: "M2 6.5h4v3H2zM10 2.5h4v3h-4zM10 10.5h4v3h-4zM6 8h4M10 8V4M10 8v6.5",
3761
+ concepts: "M2 2.5h4v3H2zM10 2.5h4v3h-4zM6 10.5h4v3H6zM4 5.5v5M12 5.5v5M8 8.5v2",
3762
+ define: "M3 2.5h10v11H3zM5.5 5.5h5M5.5 8h7M5.5 10.5h4",
3763
+ answer: "M3 3h10v7H8l-3 3v-3H3z",
3764
+ draw: "M10.5 2.5l3 3-8 8H2.5v-3zM9 4l3 3",
3765
+ refactor: "M4 3h5v2H6.5A4.5 4.5 0 1 1 3 10M12 13H7v-2h2.5A4.5 4.5 0 1 1 13 6",
3766
+ pretty: "M2.5 2.5h11v11H2.5zM5 6h6M5 8.5h6M5 11h4",
3767
+ picker: "M3 4.5h10M3 8h7M3 11.5h4",
3768
+ 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",
3769
+ 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",
3770
+ commit: "M3 8h10M10 5l3 3-3 3",
3771
+ "rail-expand": "M6 3l5 5-5 5",
3772
+ "rail-collapse": "M10 3L5 8l5 5",
3773
+ boards: "M2.5 3.5h4.5v4.5H2.5zM9 3.5h4.5v4.5H9zM2.5 10h4.5v3H2.5zM9 10h4.5v3H9z",
3774
+ save: "M3 8.5V13h10V8.5M8 2.5v8M5 8l3 3 3-3"
3775
+ };
3776
+ function CommandMark({
3777
+ id,
3778
+ className = "h-3.5 w-3.5"
3779
+ }) {
3780
+ const d = ICON_PATHS[id] ?? ICON_PATHS.simplify;
3781
+ return /* @__PURE__ */ jsx(
3782
+ "svg",
3783
+ {
3784
+ viewBox: "0 0 16 16",
3785
+ className,
3786
+ fill: "none",
3787
+ stroke: "currentColor",
3788
+ strokeWidth: 1.4,
3789
+ strokeLinecap: "round",
3790
+ strokeLinejoin: "round",
3791
+ "aria-hidden": true,
3792
+ "data-unsys-canvas-command-mark": id,
3793
+ "data-command-icon": id,
3794
+ children: /* @__PURE__ */ jsx("path", { d })
3795
+ }
3796
+ );
3797
+ }
3798
+ function UnsysCanvasCommandPicker({
3799
+ open,
3800
+ left,
3801
+ top,
3802
+ query,
3803
+ extras = [],
3804
+ onQueryChange,
3805
+ onRun,
3806
+ onClose
3807
+ }) {
3808
+ const inputRef = useRef(null);
3809
+ const [active, setActive] = useState(0);
3810
+ const matches = useMemo(
3811
+ () => fuzzyFilterUnsysCanvasCommands(query, null, extras),
3812
+ [extras, query]
3813
+ );
3814
+ useEffect(() => {
3815
+ setActive(0);
3816
+ }, [query, open]);
3817
+ useEffect(() => {
3818
+ if (!open) return;
3819
+ inputRef.current?.focus();
3820
+ inputRef.current?.select();
3821
+ }, [open]);
3822
+ if (!open) return null;
3823
+ const runAt = (index) => {
3824
+ const command = matches[index];
3825
+ if (!command) return;
3826
+ onRun(command.id);
3827
+ };
3828
+ return /* @__PURE__ */ jsxs(
3829
+ "div",
3830
+ {
3831
+ "data-unsys-canvas-command-picker": true,
3832
+ role: "dialog",
3833
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3834
+ 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)]",
3835
+ style: { left, top },
3836
+ onMouseDown: (event) => event.preventDefault(),
3837
+ children: [
3838
+ /* @__PURE__ */ jsx(
3839
+ "input",
3840
+ {
3841
+ ref: inputRef,
3842
+ "data-unsys-canvas-command-picker-input": true,
3843
+ value: query,
3844
+ onChange: (event) => onQueryChange(event.target.value.replace(/^\//, "")),
3845
+ placeholder: "Filter commands",
3846
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3847
+ 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",
3848
+ onKeyDown: (event) => {
3849
+ if (event.key === "Escape") {
3850
+ event.preventDefault();
3851
+ event.stopPropagation();
3852
+ onClose();
3853
+ return;
3854
+ }
3855
+ if (event.key === "ArrowDown") {
3856
+ event.preventDefault();
3857
+ setActive((prev) => Math.min(matches.length - 1, prev + 1));
3858
+ return;
3859
+ }
3860
+ if (event.key === "ArrowUp") {
3861
+ event.preventDefault();
3862
+ setActive((prev) => Math.max(0, prev - 1));
3863
+ return;
3864
+ }
3865
+ if (event.key === "Enter") {
3866
+ event.preventDefault();
3867
+ event.stopPropagation();
3868
+ runAt(active);
3869
+ }
3870
+ }
3871
+ }
3872
+ ),
3873
+ /* @__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(
3874
+ PickerRow,
3875
+ {
3876
+ command,
3877
+ active: index === active,
3878
+ onRun: () => onRun(command.id)
3879
+ },
3880
+ command.id
3881
+ )) : /* @__PURE__ */ jsx("li", { className: "px-2 py-2 font-mono text-[11px] text-white/45", children: "No matching commands" }) })
3882
+ ]
3883
+ }
3884
+ );
3885
+ }
3886
+ function PickerRow({
3887
+ command,
3888
+ active,
3889
+ onRun
3890
+ }) {
3891
+ const shortcut = unsysCanvasCommandShortcutLabel(command.shortcut);
3892
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
3893
+ "button",
3894
+ {
3895
+ type: "button",
3896
+ "data-unsys-canvas-command-picker-row": command.id,
3897
+ "data-active": active ? "true" : "false",
3898
+ onClick: onRun,
3899
+ 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"}`,
3900
+ children: [
3901
+ /* @__PURE__ */ jsx(CommandMark, { id: command.id, label: command.label, className: "h-3.5 w-3.5 shrink-0" }),
3902
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: command.label }),
3903
+ shortcut ? /* @__PURE__ */ jsx("kbd", { className: "shrink-0 text-[10px] opacity-55", children: shortcut }) : null
3904
+ ]
3905
+ }
3906
+ ) });
3907
+ }
3908
+ function UnsysCanvasCommandPickerAffordance({
3909
+ visible,
3910
+ left,
3911
+ top,
3912
+ onOpen
3913
+ }) {
3914
+ if (!visible) return null;
3915
+ return /* @__PURE__ */ jsx(
3916
+ "button",
3917
+ {
3918
+ type: "button",
3919
+ "data-unsys-canvas-command-picker-affordance": true,
3920
+ "aria-label": UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3921
+ title: UNSYS_CANVAS_COMMAND_PICKER_LABEL,
3922
+ 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",
3923
+ style: { left, top },
3924
+ onMouseDown: (event) => event.preventDefault(),
3925
+ onClick: onOpen,
3926
+ children: "/"
3927
+ }
3928
+ );
3929
+ }
3532
3930
 
3533
3931
  // src/lib/session-branch-model.ts
3534
3932
  function openBranchQuestions(_model) {
@@ -3719,7 +4117,8 @@ function UnsysExcalidrawMount({
3719
4117
  onChange,
3720
4118
  onPointerUpdate,
3721
4119
  initialData,
3722
- viewModeEnabled = false
4120
+ viewModeEnabled = false,
4121
+ isCollaborating = false
3723
4122
  }) {
3724
4123
  const onApiRef = useRef(onApi);
3725
4124
  const onChangeRef = useRef(onChange);
@@ -3736,7 +4135,8 @@ function UnsysExcalidrawMount({
3736
4135
  onPointerUpdateRef,
3737
4136
  initialData: initialDataRef.current,
3738
4137
  viewModeEnabled,
3739
- pointerEnabled: Boolean(onPointerUpdate)
4138
+ pointerEnabled: Boolean(onPointerUpdate),
4139
+ isCollaborating
3740
4140
  }
3741
4141
  );
3742
4142
  }
@@ -3746,7 +4146,8 @@ var UnsysExcalidrawStable = memo(function UnsysExcalidrawStable2({
3746
4146
  onPointerUpdateRef,
3747
4147
  initialData,
3748
4148
  viewModeEnabled,
3749
- pointerEnabled
4149
+ pointerEnabled,
4150
+ isCollaborating
3750
4151
  }) {
3751
4152
  useLayoutEffect(() => {
3752
4153
  return () => {
@@ -3783,6 +4184,7 @@ var UnsysExcalidrawStable = memo(function UnsysExcalidrawStable2({
3783
4184
  initialData,
3784
4185
  theme: "dark",
3785
4186
  viewModeEnabled,
4187
+ isCollaborating,
3786
4188
  UIOptions: UNSYS_EXCALIDRAW_UI_OPTIONS
3787
4189
  }
3788
4190
  ) });
@@ -4044,321 +4446,133 @@ function unsysCanvasWithLiveTransparentFill(scene) {
4044
4446
  };
4045
4447
  }
4046
4448
 
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;
4079
- }
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;
4449
+ // src/lib/work-canvas/command-errors.ts
4450
+ var MODEL_KIND_LABEL = {
4451
+ ask: "Ask",
4452
+ check: "Check",
4453
+ "selective-compress": "Compress",
4454
+ "suggest-insight": "Suggest insight",
4455
+ "clear-overlaps": "Clear overlaps",
4456
+ declutter: "Declutter"
4457
+ };
4458
+ function unsysCanvasCommandDisplayName(commandId) {
4459
+ const id = String(commandId || "").trim();
4460
+ if (!id || id === "ask") return "Ask";
4461
+ const catalog = UNSYS_CANVAS_COMMANDS.find((command) => command.id === id);
4462
+ if (catalog) return catalog.label;
4463
+ return MODEL_KIND_LABEL[id] ?? id;
4464
+ }
4465
+ function inferApiName(text, explicit) {
4466
+ const given = String(explicit || "").trim();
4467
+ if (given) return given;
4468
+ const lower = text.toLowerCase();
4469
+ if (lower.includes("openai")) return "OpenAI";
4470
+ if (lower.includes("anthropic") || lower.includes("claude")) return "Anthropic";
4471
+ return "xAI";
4472
+ }
4473
+ function unsysCanvasErrorHttpStatus(text) {
4474
+ const labeled = text.match(/\b(?:status|code|HTTP)\s*[:=]?\s*(\d{3})\b/i);
4475
+ if (labeled) return Number(labeled[1]);
4476
+ const parens = text.match(/\((\d{3})\)/);
4477
+ if (parens) return Number(parens[1]);
4478
+ const bare = text.match(/\b([1-9]\d{2})\b/);
4479
+ if (!bare) return null;
4480
+ const status = Number(bare[1]);
4481
+ return status >= 400 && status <= 599 ? status : null;
4482
+ }
4483
+ function statusReason(status, text) {
4484
+ if (status === 401 || status === 403) return "Check the API key.";
4485
+ if (status === 429) return "The API is rate-limiting requests.";
4486
+ if (status === 402) return "The API account has no credit.";
4487
+ if (status >= 500) return "The API had a server error.";
4488
+ const cut = text.replace(/^[^:]*:\s*/, "").replace(/\(\d{3}\)/g, "").replace(/\b(?:status|code|HTTP)\s*[:=]?\s*\d{3}\b/gi, "").replace(/\s+/g, " ").trim();
4489
+ return cut && cut.length < 180 ? cut : null;
4490
+ }
4491
+ function formatUnsysCanvasApiError(input) {
4492
+ const api = inferApiName(`${input.apiName || ""} ${input.baseUrl || ""}`, input.apiName);
4493
+ const status = input.status != null && Number.isFinite(Number(input.status)) ? Number(input.status) : null;
4494
+ if (status === 401 || status === 403) {
4495
+ return `the ${api} API returned ${status}. Check the API key.`;
4496
+ }
4497
+ if (status) {
4498
+ const reason2 = String(input.reason || "").trim();
4499
+ return reason2 ? `the ${api} API returned ${status} (${reason2}).` : `the ${api} API returned ${status}.`;
4500
+ }
4501
+ const reason = String(input.reason || "").trim();
4502
+ return reason ? `the ${api} API failed (${reason}).` : `the ${api} API failed.`;
4503
+ }
4504
+ function formatUnsysCanvasUnparseableReply(commandId) {
4505
+ const name = unsysCanvasCommandDisplayName(commandId);
4506
+ return `${name} couldn't use the model reply because it wasn't valid.`;
4507
+ }
4508
+ function formatUnsysCanvasCommandError(error, input) {
4509
+ const name = unsysCanvasCommandDisplayName(input?.commandId);
4510
+ const raw = error instanceof Error ? error.message : String(error ?? "");
4511
+ const text = raw.replace(/\s+/g, " ").trim();
4512
+ const lower = text.toLowerCase();
4513
+ const api = inferApiName(text, input?.apiName);
4514
+ const status = unsysCanvasErrorHttpStatus(text);
4515
+ if (/no api key|no xai api key|missing api key/i.test(text)) {
4516
+ return `${name} couldn't run: no ${api} API key. Check the API key.`;
4517
+ }
4518
+ if (!text) {
4519
+ return `${name} couldn't run: the ${api} API failed.`;
4520
+ }
4521
+ if (status === 401 || status === 403 || /unauthorized|invalid api key|incorrect api key/i.test(text)) {
4522
+ return `${name} couldn't run: the ${api} API returned ${status ?? 401}. Check the API key.`;
4523
+ }
4524
+ if (/timed? ?out|aborted|aborterror/i.test(lower)) {
4525
+ return `${name} couldn't run: the ${api} API timed out.`;
4526
+ }
4527
+ if (/empty reply|not valid|unparseable|could not parse|couldn't parse|invalid json|isn't valid/i.test(
4528
+ lower
4529
+ )) {
4530
+ return formatUnsysCanvasUnparseableReply(input?.commandId);
4531
+ }
4532
+ if (status) {
4533
+ const reason = statusReason(status, text);
4534
+ return `${name} couldn't run: ${formatUnsysCanvasApiError({ apiName: api, status, reason })}`;
4535
+ }
4536
+ if (/api failed|canvas model failed|failed to generate/i.test(lower)) {
4537
+ return `${name} couldn't run: ${formatUnsysCanvasApiError({ apiName: api, reason: text })}`;
4538
+ }
4539
+ return `${name} couldn't run: ${text}`;
4086
4540
  }
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;
4541
+
4542
+ // src/lib/work-canvas/work-canvas-xai.ts
4543
+ var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
4544
+ var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
4545
+ function unsysCanvasXaiNeedsBoardContext(kind) {
4546
+ return !kind || kind === "ask" || kind === "draw";
4099
4547
  }
4100
- function selectedIds(appState) {
4101
- const raw = asRecord2(appState.selectedElementIds);
4102
- return Object.keys(raw).filter((id) => raw[id]);
4548
+ function unsysCanvasXaiMaxTokens(kind) {
4549
+ if (kind === "concepts") return 220;
4550
+ if (kind === "simplify") return 280;
4551
+ if (kind === "pretty") return 1600;
4552
+ if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
4553
+ if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
4554
+ return 800;
4103
4555
  }
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;
4556
+ function unsysCanvasXaiFetchTimeout(kind) {
4557
+ return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
4110
4558
  }
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;
4559
+ function unsysCanvasContextSkipChrome(el) {
4560
+ const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
4561
+ return part === "header" || part === "label" || part === "body";
4118
4562
  }
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");
4563
+ function unsysCanvasCompactListing(scene, options) {
4564
+ const live = serializeUnsysCanvasScene(scene).elements.filter(
4565
+ (el) => !el.isDeleted && el.type !== "cursor" && !unsysCanvasContextSkipChrome(el)
4566
+ );
4567
+ if (!live.length) return "(no live elements)";
4568
+ const cap = Math.max(1, UNSYS_CANVAS_CONTEXT_MAX_MARKS);
4569
+ const shown = live.slice(0, cap);
4570
+ const lines = shown.map((el) => {
4571
+ const text = String(el.originalText || el.text || "").replace(/\s+/g, " ").trim().slice(0, UNSYS_CANVAS_CONTEXT_TEXT_MAX);
4572
+ return text ? `[${el.type}] ${JSON.stringify(text)}` : `[${el.type}]`;
4573
+ });
4574
+ if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
4575
+ return lines.join("\n");
4362
4576
  }
4363
4577
  function unsysCanvasTurnContextMessage(scene, input) {
4364
4578
  const board = String(input?.boardLabel || "CHAPTER").trim() || "CHAPTER";
@@ -4497,126 +4711,961 @@ function applyUnsysCanvasSuggestInsight(scene, selectedElements, suggestion) {
4497
4711
  author: "xai",
4498
4712
  ileSuggestedInsight: true
4499
4713
  }
4500
- }).elements;
4501
- if (!created.length) return current;
4502
- const settled = settleUnsysCanvasIncoming(
4503
- created,
4504
- current.elements.filter((el) => !el.isDeleted)
4505
- );
4506
- return {
4507
- ...current,
4508
- elements: [...current.elements, ...settled]
4509
- };
4510
- }
4511
- function unsysCanvasSceneVisiblyChanged(before, after) {
4512
- const previous = serializeUnsysCanvasScene(before).elements.filter((el) => !el.isDeleted);
4513
- const next = serializeUnsysCanvasScene(after).elements.filter((el) => !el.isDeleted);
4514
- if (previous.length !== next.length) return true;
4515
- const byId = new Map(previous.map((el) => [el.id, el]));
4516
- for (const el of next) {
4517
- const prior = byId.get(el.id);
4518
- if (!prior) return true;
4519
- if (prior.x !== el.x || prior.y !== el.y || prior.width !== el.width || prior.height !== el.height || String(prior.text || "") !== String(el.text || "") || String(prior.originalText || "") !== String(el.originalText || "")) {
4520
- return true;
4714
+ }).elements;
4715
+ if (!created.length) return current;
4716
+ const settled = settleUnsysCanvasIncoming(
4717
+ created,
4718
+ current.elements.filter((el) => !el.isDeleted)
4719
+ );
4720
+ return {
4721
+ ...current,
4722
+ elements: [...current.elements, ...settled]
4723
+ };
4724
+ }
4725
+ function unsysCanvasSceneVisiblyChanged(before, after) {
4726
+ const previous = serializeUnsysCanvasScene(before).elements.filter((el) => !el.isDeleted);
4727
+ const next = serializeUnsysCanvasScene(after).elements.filter((el) => !el.isDeleted);
4728
+ if (previous.length !== next.length) return true;
4729
+ const byId = new Map(previous.map((el) => [el.id, el]));
4730
+ for (const el of next) {
4731
+ const prior = byId.get(el.id);
4732
+ if (!prior) return true;
4733
+ if (prior.x !== el.x || prior.y !== el.y || prior.width !== el.width || prior.height !== el.height || String(prior.text || "") !== String(el.text || "") || String(prior.originalText || "") !== String(el.originalText || "")) {
4734
+ return true;
4735
+ }
4736
+ }
4737
+ return false;
4738
+ }
4739
+ function applyUnsysCanvasCommandErrorNotice(input) {
4740
+ const text = String(input.message || "").trim();
4741
+ if (!text) return serializeUnsysCanvasScene(input.live);
4742
+ return withUnsysCanvasAutoLayout(
4743
+ mergeUnsysCanvasTurnOntoLiveWorkCanvas(
4744
+ input.live,
4745
+ { text },
4746
+ { fallbackOrigin: input.fallbackOrigin, reserved: input.reserved }
4747
+ )
4748
+ );
4749
+ }
4750
+ function applyUnsysCanvasAskReply(input) {
4751
+ const live = serializeUnsysCanvasScene(input.live);
4752
+ const selected = expandUnsysCanvasCommandSelection(live, input.selectedElements);
4753
+ const kind = input.kind ?? null;
4754
+ const noteLabel = unsysCanvasNoteLabel(kind);
4755
+ const source = kind && kind !== "ask" ? String(input.payload.raw || "") : String(input.payload.text || "");
4756
+ const layoutReply = unsysCanvasLayoutReply(input.payload.raw, input.payload.elements);
4757
+ const merge = (text, extra) => mergeUnsysCanvasTurnOntoLiveWorkCanvas(
4758
+ live,
4759
+ {
4760
+ text,
4761
+ elements: input.payload.elements,
4762
+ turnId: input.payload.turnId,
4763
+ origin: input.payload.origin,
4764
+ label: noteLabel
4765
+ },
4766
+ {
4767
+ fallbackOrigin: input.fallbackOrigin,
4768
+ reserved: input.reserved
4769
+ }
4770
+ );
4771
+ let next = live;
4772
+ if (kind === "selective-compress") {
4773
+ next = compressUnsysCanvasSelection(live, selected, source);
4774
+ } else if (kind === "refactor") {
4775
+ next = replaceUnsysCanvasSelection(live, selected, {
4776
+ text: input.payload.text,
4777
+ elements: input.payload.elements,
4778
+ turnId: input.payload.turnId,
4779
+ label: noteLabel
4780
+ });
4781
+ } else if (kind === "simplify") {
4782
+ const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
4783
+ if (text) {
4784
+ next = fanUnsysCanvasLabeledNodes(live, selected, [text], "ileSimplify").scene;
4785
+ }
4786
+ } else if (kind === "pretty") {
4787
+ const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
4788
+ const placed = placeUnsysCanvasPrettyReply(live, selected, {
4789
+ text,
4790
+ elements: input.payload.elements
4791
+ });
4792
+ if (placed.placed) next = placed.scene;
4793
+ else if (text || normalizeExtraSkeletons(input.payload.elements).length) {
4794
+ next = merge(text);
4795
+ }
4796
+ } else if (kind === "concepts") {
4797
+ const labels = unsysCanvasConceptLabels(source, {
4798
+ text: input.payload.text,
4799
+ elements: input.payload.elements
4800
+ });
4801
+ next = fanUnsysCanvasLabeledNodes(live, selected, labels, "ileConcepts").scene;
4802
+ } else if (kind === "suggest-insight") {
4803
+ next = applyUnsysCanvasSuggestInsight(live, selected, source);
4804
+ } else if (kind === "declutter" || kind === "clear-overlaps") {
4805
+ next = applyUnsysCanvasPositionEdits(live, selected, layoutReply);
4806
+ } else {
4807
+ next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
4808
+ }
4809
+ if (unsysCanvasSceneVisiblyChanged(live, next)) return withUnsysCanvasAutoLayout(next);
4810
+ const recoverable = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
4811
+ if (recoverable || normalizeExtraSkeletons(input.payload.elements).length) {
4812
+ const recovered = merge(recoverable);
4813
+ if (unsysCanvasSceneVisiblyChanged(live, recovered)) return withUnsysCanvasAutoLayout(recovered);
4814
+ }
4815
+ return applyUnsysCanvasCommandErrorNotice({
4816
+ live,
4817
+ message: formatUnsysCanvasUnparseableReply(kind),
4818
+ fallbackOrigin: input.fallbackOrigin,
4819
+ reserved: input.reserved
4820
+ });
4821
+ }
4822
+ function applyUnsysCanvasPositionEdits(scene, selectedElements, reply) {
4823
+ const current = serializeUnsysCanvasScene(scene);
4824
+ const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
4825
+ if (!liveSelected.length) return current;
4826
+ const edits = parseUnsysCanvasLayoutEdits(reply);
4827
+ if (!edits.length) return current;
4828
+ const selectedIds2 = new Set(liveSelected.map((el) => el.id));
4829
+ const matchById = edits.some((edit) => edit.id && selectedIds2.has(edit.id));
4830
+ let ordinal = 0;
4831
+ return {
4832
+ ...current,
4833
+ elements: current.elements.map((el) => {
4834
+ if (!selectedIds2.has(el.id) || el.isDeleted) return el;
4835
+ const edit = unsysCanvasEditForElement(edits, el, ordinal, matchById);
4836
+ ordinal += 1;
4837
+ if (!edit || edit.x == null && edit.y == null) return el;
4838
+ return {
4839
+ ...el,
4840
+ x: edit.x == null ? el.x : edit.x,
4841
+ y: edit.y == null ? el.y : edit.y,
4842
+ version: (Number(el.version) || 1) + 1
4843
+ };
4844
+ })
4845
+ };
4846
+ }
4847
+ function unsysCanvasAddedElementIds(before, after) {
4848
+ const seen = /* @__PURE__ */ new Set();
4849
+ for (const el of before?.elements ?? []) {
4850
+ const id = String(el?.id || "").trim();
4851
+ if (id) seen.add(id);
4852
+ }
4853
+ const ids = [];
4854
+ for (const el of after?.elements ?? []) {
4855
+ const id = String(el?.id || "").trim();
4856
+ if (!id || el?.isDeleted || seen.has(id)) continue;
4857
+ ids.push(id);
4858
+ }
4859
+ return ids;
4860
+ }
4861
+
4862
+ // src/lib/work-canvas/command-registry.ts
4863
+ var UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT = [
4864
+ "You sit beside the learner on a work canvas. Speak in complete, unhurried sentences. Be eloquent and plain.",
4865
+ "Answer the topic directly. Never mention canvas commands, origin, or placement.",
4866
+ "Never mention the host product, event names, or platform jargon.",
4867
+ "Write mathematics as LaTeX: $...$ inline and $$...$$ on its own line.",
4868
+ 'Reply as JSON with a "text" field. Do not put JSON or code fences inside "text".'
4869
+ ].join(" ");
4870
+ var UNSYS_CANVAS_MODEL_COMMAND_IDS = [
4871
+ "ask",
4872
+ "draw",
4873
+ "simplify",
4874
+ "concepts",
4875
+ "check",
4876
+ "selective-compress",
4877
+ "refactor",
4878
+ "suggest-insight",
4879
+ "clear-overlaps",
4880
+ "declutter"
4881
+ ];
4882
+ var CONTEXT_TEXT_MAX = 2e3;
4883
+ var CONTEXT_PROMPT_MAX = 4e3;
4884
+ var CONTEXT_SELECTED_MAX = 64;
4885
+ var CONTEXT_LIVE_MAX = 48;
4886
+ var CONTEXT_ID_MAX = 80;
4887
+ var ELEMENT_TYPES = /* @__PURE__ */ new Set([
4888
+ "text",
4889
+ "freedraw",
4890
+ "rectangle",
4891
+ "diamond",
4892
+ "ellipse",
4893
+ "arrow",
4894
+ "line",
4895
+ "image",
4896
+ "frame",
4897
+ "embeddable"
4898
+ ]);
4899
+ function finiteNumber(value) {
4900
+ const n = Number(value);
4901
+ return Number.isFinite(n) ? n : 0;
4902
+ }
4903
+ function clipText(value, max) {
4904
+ return String(value ?? "").replace(/\s+/g, " ").trim().slice(0, max);
4905
+ }
4906
+ function compactUnsysCanvasContextElement(el) {
4907
+ if (!el || typeof el !== "object") return null;
4908
+ const id = String(el.id || "").trim().slice(0, CONTEXT_ID_MAX);
4909
+ const type = String(el.type || "").trim().slice(0, 32);
4910
+ if (!id || !type || !ELEMENT_TYPES.has(type)) return null;
4911
+ const text = clipText(
4912
+ "originalText" in el ? el.originalText || el.text : el.text,
4913
+ CONTEXT_TEXT_MAX
4914
+ );
4915
+ const compact = {
4916
+ id,
4917
+ type,
4918
+ x: finiteNumber(el.x),
4919
+ y: finiteNumber(el.y)
4920
+ };
4921
+ if (el.width != null) compact.width = finiteNumber(el.width);
4922
+ if (el.height != null) compact.height = finiteNumber(el.height);
4923
+ if (text) compact.text = text;
4924
+ return compact;
4925
+ }
4926
+ function compactList(elements, max) {
4927
+ const out = [];
4928
+ for (const item of elements ?? []) {
4929
+ const compact = compactUnsysCanvasContextElement(item);
4930
+ if (!compact) continue;
4931
+ out.push(compact);
4932
+ if (out.length >= max) break;
4933
+ }
4934
+ return out;
4935
+ }
4936
+ function asSceneFromContext(context) {
4937
+ const live = context.liveElements?.length ? context.liveElements : context.selectedElements;
4938
+ return {
4939
+ elements: live,
4940
+ appState: {},
4941
+ files: {}
4942
+ };
4943
+ }
4944
+ function asSelectedFromContext(context) {
4945
+ return context.selectedElements;
4946
+ }
4947
+ function extractUnsysCanvasCommandContext(input) {
4948
+ const scene = input.scene ?? { elements: [], appState: {}, files: {} };
4949
+ const selected = expandUnsysCanvasCommandSelection(scene, input.selectedElements);
4950
+ const payload = {
4951
+ selectedElements: compactList(selected, CONTEXT_SELECTED_MAX)
4952
+ };
4953
+ if (unsysCanvasXaiNeedsBoardContext(input.commandId)) {
4954
+ payload.liveElements = compactList(
4955
+ (scene.elements ?? []).filter((el) => el && !el.isDeleted),
4956
+ CONTEXT_LIVE_MAX
4957
+ );
4958
+ }
4959
+ const prompt = clipText(input.prompt, CONTEXT_PROMPT_MAX);
4960
+ if (prompt) payload.prompt = prompt;
4961
+ if (input.workspace) payload.workspace = input.workspace;
4962
+ return payload;
4963
+ }
4964
+ function defaultParse(raw) {
4965
+ const parsed = parseUnsysCanvasAskReply(raw);
4966
+ const turn = parseUnsysCanvasCanvasTurn(raw);
4967
+ return {
4968
+ text: parsed.message,
4969
+ elements: parsed.canvasElements,
4970
+ origin: turn.origin ?? null,
4971
+ raw: parsed.raw
4972
+ };
4973
+ }
4974
+ function defaultBuildPrompt(commandId, context) {
4975
+ const kind = commandId;
4976
+ const scene = asSceneFromContext(context);
4977
+ const selected = asSelectedFromContext(context);
4978
+ const userText = [
4979
+ buildUnsysCanvasCommandUserMessage({
4980
+ kind,
4981
+ prompt: context.prompt,
4982
+ selectedElements: selected,
4983
+ workspace: context.workspace
4984
+ }),
4985
+ unsysCanvasXaiNeedsBoardContext(kind) ? unsysCanvasTurnContextMessage(scene, {
4986
+ boardLabel: context.boardLabel,
4987
+ workspace: context.workspace
4988
+ }) : ""
4989
+ ].filter(Boolean).join("\n\n");
4990
+ return {
4991
+ messages: [
4992
+ { role: "system", content: `${UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT} ${unsysCanvasXaiToolsInstruction()}` },
4993
+ { role: "user", content: userText }
4994
+ ],
4995
+ responseFormat: "json",
4996
+ maxTokens: unsysCanvasXaiMaxTokens(kind),
4997
+ timeoutMs: unsysCanvasXaiFetchTimeout(kind)
4998
+ };
4999
+ }
5000
+ var MODEL_KIND_LABEL2 = {
5001
+ ask: "Ask",
5002
+ check: "Check",
5003
+ "selective-compress": "Compress",
5004
+ "suggest-insight": "Suggest insight",
5005
+ "clear-overlaps": "Clear overlaps",
5006
+ declutter: "Declutter"
5007
+ };
5008
+ function hiddenModelDef(id) {
5009
+ return {
5010
+ id,
5011
+ label: MODEL_KIND_LABEL2[id] ?? id,
5012
+ tooltip: MODEL_KIND_LABEL2[id] ?? id,
5013
+ shortcut: "",
5014
+ needsSelection: id !== "ask",
5015
+ boardOnly: false,
5016
+ replacesSelection: id === "refactor" || id === "selective-compress",
5017
+ catalog: false,
5018
+ needsModel: true,
5019
+ placement: id === "refactor" || id === "selective-compress" ? "replace" : "beside",
5020
+ extractContext: (input) => extractUnsysCanvasCommandContext({
5021
+ commandId: id,
5022
+ scene: input.scene,
5023
+ selectedElements: input.selectedElements,
5024
+ prompt: input.prompt,
5025
+ workspace: input.workspace
5026
+ }),
5027
+ buildPrompt: (context) => defaultBuildPrompt(id, context),
5028
+ parseResponse: defaultParse
5029
+ };
5030
+ }
5031
+ function catalogDef(command) {
5032
+ const needsModel = command.id !== "breakdown";
5033
+ return {
5034
+ ...command,
5035
+ catalog: true,
5036
+ needsModel,
5037
+ placement: command.replacesSelection ? "replace" : "beside",
5038
+ extractContext: (input) => extractUnsysCanvasCommandContext({
5039
+ commandId: command.id,
5040
+ scene: input.scene,
5041
+ selectedElements: input.selectedElements,
5042
+ prompt: input.prompt,
5043
+ workspace: input.workspace
5044
+ }),
5045
+ buildPrompt: needsModel ? (context) => defaultBuildPrompt(command.id, context) : void 0,
5046
+ parseResponse: defaultParse
5047
+ };
5048
+ }
5049
+ var BUILTIN_BY_ID = /* @__PURE__ */ new Map();
5050
+ for (const command of UNSYS_CANVAS_COMMANDS) {
5051
+ BUILTIN_BY_ID.set(command.id, catalogDef(command));
5052
+ }
5053
+ for (const id of UNSYS_CANVAS_MODEL_COMMAND_IDS) {
5054
+ if (!BUILTIN_BY_ID.has(id)) BUILTIN_BY_ID.set(id, hiddenModelDef(id));
5055
+ }
5056
+ function extraToDefinition(extra) {
5057
+ const id = String(extra.id || "").trim();
5058
+ const needsModel = Boolean(extra.buildPrompt) || extra.needsModel === true;
5059
+ return {
5060
+ id,
5061
+ label: extra.label,
5062
+ tooltip: extra.tooltip ?? extra.label,
5063
+ shortcut: extra.shortcut ?? "",
5064
+ needsSelection: extra.needsSelection ?? false,
5065
+ boardOnly: false,
5066
+ replacesSelection: false,
5067
+ slash: extra.slash,
5068
+ run: extra.run,
5069
+ catalog: extra.catalog !== false,
5070
+ needsModel,
5071
+ placement: extra.placement ?? "beside",
5072
+ gesture: extra.gesture,
5073
+ gestureHint: extra.gestureHint,
5074
+ extractContext: extra.extractContext ?? ((input) => extractUnsysCanvasCommandContext({
5075
+ commandId: id,
5076
+ scene: input.scene,
5077
+ selectedElements: input.selectedElements,
5078
+ prompt: input.prompt,
5079
+ workspace: input.workspace
5080
+ })),
5081
+ buildPrompt: extra.buildPrompt,
5082
+ parseResponse: extra.parseResponse ?? defaultParse
5083
+ };
5084
+ }
5085
+ function listUnsysCanvasCommandDefinitions(extras = []) {
5086
+ const out = [...BUILTIN_BY_ID.values()];
5087
+ const seen = new Set(out.map((command) => command.id));
5088
+ for (const extra of extras) {
5089
+ const id = String(extra?.id || "").trim();
5090
+ if (!id || seen.has(id)) continue;
5091
+ seen.add(id);
5092
+ out.push(extraToDefinition(extra));
5093
+ }
5094
+ return out;
5095
+ }
5096
+ function getUnsysCanvasCommand(id, extras = []) {
5097
+ const key = String(id || "").trim();
5098
+ if (!key) return null;
5099
+ const extra = extras.find((command) => String(command?.id || "").trim() === key);
5100
+ if (extra) return extraToDefinition(extra);
5101
+ return BUILTIN_BY_ID.get(key) ?? null;
5102
+ }
5103
+ function isUnsysCanvasKnownCommandId(id, extras = []) {
5104
+ return getUnsysCanvasCommand(id, extras) != null;
5105
+ }
5106
+ function buildUnsysCanvasCommandPrompt(commandId, context, extras = []) {
5107
+ const command = getUnsysCanvasCommand(commandId, extras);
5108
+ if (!command) {
5109
+ throw new Error(`Unknown canvas command: ${commandId}`);
5110
+ }
5111
+ if (command.buildPrompt) return command.buildPrompt(context);
5112
+ return defaultBuildPrompt(commandId, context);
5113
+ }
5114
+ function parseUnsysCanvasCommandResponse(commandId, raw, extras = []) {
5115
+ const command = getUnsysCanvasCommand(commandId, extras);
5116
+ const parse = command?.parseResponse ?? defaultParse;
5117
+ return parse(raw);
5118
+ }
5119
+ function unsysCanvasCommandPlacement(id) {
5120
+ return String(id || "").trim() === "refactor" ? "replace" : "beside";
5121
+ }
5122
+ function unsysCanvasCommandEventInputs(input) {
5123
+ const selectedElementIds = (input.selectedElements ?? []).map((el) => String(el?.id || "").trim()).filter(Boolean);
5124
+ const prompt = String(input.prompt || "").trim();
5125
+ return prompt ? { selectedElementIds, prompt } : { selectedElementIds };
5126
+ }
5127
+ function unsysCanvasGestureCommandId(gesture) {
5128
+ const kind = String(gesture || "").trim();
5129
+ if (!kind) return null;
5130
+ for (const command of UNSYS_CANVAS_COMMANDS) {
5131
+ if (command.gesture === kind) return command.id;
5132
+ }
5133
+ return null;
5134
+ }
5135
+
5136
+ // src/lib/work-canvas/command-model.ts
5137
+ var INJECTION_KEYS = /* @__PURE__ */ new Set([
5138
+ "messages",
5139
+ "system",
5140
+ "user",
5141
+ "prompt",
5142
+ "thought",
5143
+ "instructions",
5144
+ "systemPrompt"
5145
+ ]);
5146
+ function asRecord2(value) {
5147
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
5148
+ return value;
5149
+ }
5150
+ function validateContext(raw, commandId) {
5151
+ const rec = asRecord2(raw);
5152
+ if (!rec) return { ok: false, error: "context is required" };
5153
+ for (const key of Object.keys(rec)) {
5154
+ if (INJECTION_KEYS.has(key) && key !== "prompt") {
5155
+ return { ok: false, error: "context contains disallowed fields" };
5156
+ }
5157
+ }
5158
+ if (rec.commandId != null && String(rec.commandId).trim() !== commandId) {
5159
+ return { ok: false, error: "context.commandId does not match commandId" };
5160
+ }
5161
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements.map(compactUnsysCanvasContextElement).filter(Boolean) : [];
5162
+ const live = Array.isArray(rec.liveElements) ? rec.liveElements.map(compactUnsysCanvasContextElement).filter(Boolean) : void 0;
5163
+ const prompt = typeof rec.prompt === "string" ? rec.prompt.replace(/\s+/g, " ").trim().slice(0, 4e3) : "";
5164
+ const boardLabel = typeof rec.boardLabel === "string" ? rec.boardLabel.trim().slice(0, 80) : void 0;
5165
+ const workspace = rec.workspace && typeof rec.workspace === "object" ? rec.workspace : void 0;
5166
+ const context = {
5167
+ selectedElements: selected
5168
+ };
5169
+ if (live?.length) context.liveElements = live;
5170
+ if (prompt) context.prompt = prompt;
5171
+ if (boardLabel) context.boardLabel = boardLabel;
5172
+ if (workspace) context.workspace = workspace;
5173
+ return { ok: true, context };
5174
+ }
5175
+ function parseUnsysCanvasModelClientBody(body, extras = []) {
5176
+ const rec = asRecord2(body);
5177
+ if (!rec) return { ok: false, status: 400, error: "JSON object required" };
5178
+ for (const key of ["messages", "system", "systemPrompt", "instructions", "user"]) {
5179
+ if (key in rec) {
5180
+ return { ok: false, status: 400, error: "Only commandId and context are allowed" };
5181
+ }
5182
+ }
5183
+ const commandId = String(rec.commandId || rec.canvasAskKind || "").trim();
5184
+ if (!commandId) return { ok: false, status: 400, error: "commandId is required" };
5185
+ if (!isUnsysCanvasKnownCommandId(commandId, extras)) {
5186
+ return { ok: false, status: 400, error: `Unknown command id: ${commandId}` };
5187
+ }
5188
+ const command = getUnsysCanvasCommand(commandId, extras);
5189
+ if (!command?.needsModel && !command?.buildPrompt) {
5190
+ return { ok: false, status: 400, error: `Command does not use a model: ${commandId}` };
5191
+ }
5192
+ let contextRaw = rec.context;
5193
+ if (!contextRaw) {
5194
+ contextRaw = {
5195
+ selectedElements: rec.selectedElements,
5196
+ liveElements: rec.liveElements,
5197
+ prompt: rec.thought ?? rec.prompt
5198
+ };
5199
+ }
5200
+ const context = validateContext(contextRaw, commandId);
5201
+ if (!context.ok) return { ok: false, status: 400, error: context.error };
5202
+ return { ok: true, commandId, context: context.context };
5203
+ }
5204
+ function buildUnsysCanvasModelRequest(input) {
5205
+ const extras = input.extras ?? [];
5206
+ const command = getUnsysCanvasCommand(input.commandId, extras);
5207
+ if (!command) {
5208
+ throw new Error(`Unknown canvas command: ${input.commandId}`);
5209
+ }
5210
+ const context = input.context ?? extractUnsysCanvasCommandContext({
5211
+ commandId: input.commandId,
5212
+ scene: input.scene,
5213
+ selectedElements: input.selectedElements,
5214
+ prompt: input.prompt,
5215
+ workspace: input.workspace
5216
+ });
5217
+ const built = buildUnsysCanvasCommandPrompt(input.commandId, context, extras);
5218
+ return {
5219
+ commandId: input.commandId,
5220
+ messages: built.messages,
5221
+ responseFormat: built.responseFormat,
5222
+ jsonSchema: built.jsonSchema,
5223
+ maxTokens: built.maxTokens,
5224
+ timeoutMs: built.timeoutMs,
5225
+ signal: input.signal,
5226
+ context
5227
+ };
5228
+ }
5229
+ async function handleCanvasModelRequest(body, options) {
5230
+ const parsed = parseUnsysCanvasModelClientBody(body, options.extras);
5231
+ if (!parsed.ok) return parsed;
5232
+ try {
5233
+ const request = buildUnsysCanvasModelRequest({
5234
+ commandId: parsed.commandId,
5235
+ context: parsed.context,
5236
+ extras: options.extras,
5237
+ signal: options.signal
5238
+ });
5239
+ const result = await options.runModel(request);
5240
+ const text = String(result?.text ?? "");
5241
+ const reply = parseUnsysCanvasCommandResponse(parsed.commandId, text, options.extras);
5242
+ return { ok: true, ...reply };
5243
+ } catch (error) {
5244
+ const message = error instanceof Error ? error.message : "Canvas model failed";
5245
+ return { ok: false, status: 500, error: message };
5246
+ }
5247
+ }
5248
+ async function handleCanvasModelHttpRequest(req, options) {
5249
+ const body = await req.json().catch(() => null);
5250
+ const result = await handleCanvasModelRequest(body, {
5251
+ runModel: options.runModel,
5252
+ extras: options.extras,
5253
+ signal: req.signal
5254
+ });
5255
+ if (!result.ok) {
5256
+ return Response.json(
5257
+ { error: { message: result.error } },
5258
+ { status: result.status }
5259
+ );
5260
+ }
5261
+ return Response.json({
5262
+ message: result.text,
5263
+ canvasElements: result.elements,
5264
+ raw: result.raw
5265
+ });
5266
+ }
5267
+ function choiceContent(data) {
5268
+ const choices = Array.isArray(data.choices) ? data.choices : [];
5269
+ const first = choices[0];
5270
+ if (!first || typeof first !== "object") return "";
5271
+ const message = first.message;
5272
+ const content = message?.content;
5273
+ if (typeof content === "string") return content;
5274
+ if (Array.isArray(content)) {
5275
+ return content.map((part) => part && typeof part === "object" && "text" in part ? String(part.text || "") : "").filter(Boolean).join("\n");
5276
+ }
5277
+ return "";
5278
+ }
5279
+ function modelSendsReasoningEffort(model) {
5280
+ const id = model.toLowerCase();
5281
+ if (!id || id.includes("non-reasoning")) return false;
5282
+ return /^grok-4\.(5|6|7)/.test(id) || id.includes("grok-4.20") && id.includes("reasoning");
5283
+ }
5284
+ function createUnsysCanvasXaiBrowserRunner(options) {
5285
+ const fetchImpl = options.fetch ?? fetch;
5286
+ return async (request) => {
5287
+ const apiKey = String(await options.getApiKey() || "").trim();
5288
+ if (!apiKey) {
5289
+ throw new Error("No xAI API key.");
5290
+ }
5291
+ const baseURL = String(await options.getBaseUrl?.() || "").replace(/\/+$/, "") || "https://api.x.ai/v1";
5292
+ const model = typeof options.model === "function" ? options.model(request.commandId) : options.model || "grok-4.7";
5293
+ const timeout = request.timeoutMs || 6e4;
5294
+ const signal = request.signal ?? AbortSignal.timeout(timeout);
5295
+ const body = {
5296
+ model,
5297
+ messages: request.messages,
5298
+ max_tokens: request.maxTokens,
5299
+ temperature: 0.55
5300
+ };
5301
+ if (request.responseFormat === "json") {
5302
+ body.response_format = { type: "json_object" };
5303
+ } else if (request.responseFormat === "json_schema" && request.jsonSchema) {
5304
+ body.response_format = { type: "json_schema", json_schema: request.jsonSchema };
5305
+ }
5306
+ if (modelSendsReasoningEffort(model)) {
5307
+ body.reasoning_effort = options.reasoningEffort ?? "low";
5308
+ }
5309
+ const response = await fetchImpl(`${baseURL}/chat/completions`, {
5310
+ method: "POST",
5311
+ headers: {
5312
+ Authorization: `Bearer ${apiKey}`,
5313
+ "Content-Type": "application/json"
5314
+ },
5315
+ body: JSON.stringify(body),
5316
+ signal
5317
+ });
5318
+ const data = await response.json().catch(() => ({}));
5319
+ if (!response.ok) {
5320
+ const err = data.error;
5321
+ const message = typeof err === "string" ? err : err && typeof err === "object" && "message" in err ? String(err.message || "") : "";
5322
+ const apiName = /x\.ai/i.test(baseURL) ? "xAI" : "model";
5323
+ throw new Error(
5324
+ formatUnsysCanvasApiError({
5325
+ apiName,
5326
+ status: response.status,
5327
+ reason: message.trim(),
5328
+ baseUrl: baseURL
5329
+ })
5330
+ );
5331
+ }
5332
+ const text = choiceContent(data).trim();
5333
+ if (!text) throw new Error("Canvas chat returned an empty reply.");
5334
+ return { text };
5335
+ };
5336
+ }
5337
+ function createUnsysCanvasModelProxyRunner(options) {
5338
+ const fetchImpl = options.fetch ?? fetch;
5339
+ return async (request) => {
5340
+ const headers = {
5341
+ "Content-Type": "application/json",
5342
+ ...options.headers ? await options.headers() : {}
5343
+ };
5344
+ const response = await fetchImpl(options.url, {
5345
+ method: "POST",
5346
+ headers,
5347
+ body: JSON.stringify({
5348
+ commandId: request.commandId,
5349
+ context: request.context
5350
+ }),
5351
+ signal: request.signal ?? AbortSignal.timeout(request.timeoutMs || 6e4)
5352
+ });
5353
+ const data = await response.json().catch(() => ({}));
5354
+ if (!response.ok) {
5355
+ const err = asRecord2(data.error);
5356
+ const message = err && typeof err.message === "string" && err.message || (typeof data.error === "string" ? data.error : "") || `the model API returned ${response.status}`;
5357
+ throw new Error(message);
5358
+ }
5359
+ const raw = typeof data.raw === "string" && data.raw.trim() ? data.raw : typeof data.message === "string" ? data.message : "";
5360
+ if (!raw.trim()) throw new Error("Canvas chat returned an empty reply.");
5361
+ return { text: raw };
5362
+ };
5363
+ }
5364
+ async function runUnsysCanvasModelAsk(runModel, input) {
5365
+ const request = buildUnsysCanvasModelRequest(input);
5366
+ const result = await runModel(request);
5367
+ return parseUnsysCanvasCommandResponse(input.commandId, result.text, input.extras);
5368
+ }
5369
+
5370
+ // src/lib/events.ts
5371
+ var UNSYS_CANVAS_EVENT_TYPES = [
5372
+ "element:added",
5373
+ "element:updated",
5374
+ "element:deleted",
5375
+ "element:moved",
5376
+ "element:resized",
5377
+ "text:edited",
5378
+ "selection:changed",
5379
+ "tool:changed",
5380
+ "viewport:changed",
5381
+ "command:run",
5382
+ "command:complete",
5383
+ "prompt:submit",
5384
+ "dictate:start",
5385
+ "dictate:stop",
5386
+ "dictate:text",
5387
+ "laser:gesture",
5388
+ "latex:render",
5389
+ "undo",
5390
+ "redo"
5391
+ ];
5392
+ var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
5393
+ var HIGH_FREQ = /* @__PURE__ */ new Set([
5394
+ "viewport:changed",
5395
+ "element:moved",
5396
+ "element:resized",
5397
+ "element:updated",
5398
+ "text:edited"
5399
+ ]);
5400
+ function asRecord3(value) {
5401
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
5402
+ return value;
5403
+ }
5404
+ function elementMap(elements) {
5405
+ const map = /* @__PURE__ */ new Map();
5406
+ for (const el of elements) {
5407
+ if (el && typeof el.id === "string") map.set(el.id, el);
5408
+ }
5409
+ return map;
5410
+ }
5411
+ function changedProps(prev, next) {
5412
+ const changed = {};
5413
+ const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
5414
+ for (const key of keys) {
5415
+ if (SKIP_KEYS.has(key)) continue;
5416
+ const from = prev?.[key];
5417
+ const to = next[key];
5418
+ if (JSON.stringify(from) !== JSON.stringify(to)) {
5419
+ changed[key] = { from, to };
5420
+ }
5421
+ }
5422
+ return changed;
5423
+ }
5424
+ function selectedIds(appState) {
5425
+ const raw = asRecord3(appState.selectedElementIds);
5426
+ return Object.keys(raw).filter((id) => raw[id]);
5427
+ }
5428
+ function zoomValue(appState) {
5429
+ const zoom = appState.zoom;
5430
+ if (zoom && typeof zoom === "object" && "value" in zoom) {
5431
+ return Number(zoom.value) || 1;
5432
+ }
5433
+ return Number(zoom) || 1;
5434
+ }
5435
+ function toolName(appState) {
5436
+ const tool = appState.activeTool;
5437
+ if (typeof tool === "string") return tool;
5438
+ if (tool && typeof tool === "object" && "type" in tool) {
5439
+ return String(tool.type || "") || null;
5440
+ }
5441
+ return null;
5442
+ }
5443
+ function snapshot(scene) {
5444
+ const rec = asRecord3(scene);
5445
+ const elements = Array.isArray(rec.elements) ? rec.elements : [];
5446
+ return {
5447
+ elements,
5448
+ appState: asRecord3(rec.appState),
5449
+ files: asRecord3(rec.files)
5450
+ };
5451
+ }
5452
+ function eventKey(event) {
5453
+ const id = typeof event.payload.id === "string" ? event.payload.id : "";
5454
+ return `${event.type}:${id}`;
5455
+ }
5456
+ function mergePayload(prev, next) {
5457
+ const merged = { ...prev, ...next };
5458
+ if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
5459
+ if ("to" in next) merged.to = next.to;
5460
+ if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
5461
+ const a = prev.changed;
5462
+ const b = next.changed;
5463
+ const changed = { ...a };
5464
+ for (const [key, value] of Object.entries(b)) {
5465
+ const earlier = a[key];
5466
+ changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
5467
+ }
5468
+ merged.changed = changed;
5469
+ }
5470
+ return merged;
5471
+ }
5472
+ var UnsysCanvasEventCollector = class {
5473
+ constructor(options) {
5474
+ this.seq = 0;
5475
+ this.prev = null;
5476
+ this.buffer = [];
5477
+ this.lastFlush = 0;
5478
+ this.batchMs = options?.batchMs ?? 0;
5479
+ }
5480
+ reset(scene) {
5481
+ this.prev = snapshot(scene);
5482
+ this.seq = 0;
5483
+ this.buffer = [];
5484
+ this.lastFlush = 0;
5485
+ }
5486
+ syncWithoutEmit(scene) {
5487
+ this.prev = snapshot(scene);
5488
+ }
5489
+ push(type, payload) {
5490
+ this.seq += 1;
5491
+ return { seq: this.seq, ts: Date.now(), type, payload };
5492
+ }
5493
+ observeScene(scene, _opts) {
5494
+ const next = snapshot(scene);
5495
+ const prev = this.prev ?? { elements: [], appState: {}};
5496
+ const events = [];
5497
+ const prevEls = elementMap(prev.elements);
5498
+ const nextEls = elementMap(next.elements);
5499
+ for (const [id, el] of nextEls) {
5500
+ const before = prevEls.get(id);
5501
+ const deleted = Boolean(el.isDeleted);
5502
+ const wasDeleted = Boolean(before?.isDeleted);
5503
+ if (!before || wasDeleted && !deleted) {
5504
+ if (!deleted) {
5505
+ events.push(
5506
+ this.push("element:added", {
5507
+ id,
5508
+ type: el.type,
5509
+ element: el
5510
+ })
5511
+ );
5512
+ }
5513
+ continue;
5514
+ }
5515
+ if (!wasDeleted && deleted) {
5516
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
5517
+ continue;
5518
+ }
5519
+ if (deleted) continue;
5520
+ const changed = changedProps(before, el);
5521
+ if (!Object.keys(changed).length) continue;
5522
+ events.push(
5523
+ this.push("element:updated", {
5524
+ id,
5525
+ type: el.type,
5526
+ changed
5527
+ })
5528
+ );
5529
+ if ("x" in changed || "y" in changed) {
5530
+ events.push(
5531
+ this.push("element:moved", {
5532
+ id,
5533
+ type: el.type,
5534
+ from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
5535
+ to: { x: el.x, y: el.y }
5536
+ })
5537
+ );
5538
+ }
5539
+ if ("width" in changed || "height" in changed) {
5540
+ events.push(
5541
+ this.push("element:resized", {
5542
+ id,
5543
+ type: el.type,
5544
+ from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
5545
+ to: { width: el.width, height: el.height }
5546
+ })
5547
+ );
5548
+ }
5549
+ if ("text" in changed || "originalText" in changed) {
5550
+ events.push(
5551
+ this.push("text:edited", {
5552
+ id,
5553
+ type: el.type,
5554
+ from: changed.text?.from ?? changed.originalText?.from ?? before.text,
5555
+ to: el.text ?? el.originalText
5556
+ })
5557
+ );
5558
+ }
5559
+ }
5560
+ for (const [id, el] of prevEls) {
5561
+ if (nextEls.has(id)) continue;
5562
+ if (el.isDeleted) continue;
5563
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
4521
5564
  }
4522
- }
4523
- return false;
4524
- }
4525
- function unsysCanvasAskFallback(kind) {
4526
- if (!kind || kind === "ask") return "Learn more failed. Try again.";
4527
- return `${kind} failed. Try again.`;
4528
- }
4529
- function applyUnsysCanvasAskReply(input) {
4530
- const live = serializeUnsysCanvasScene(input.live);
4531
- const selected = expandUnsysCanvasCommandSelection(live, input.selectedElements);
4532
- const kind = input.kind ?? null;
4533
- const noteLabel = unsysCanvasNoteLabel(kind);
4534
- const source = kind && kind !== "ask" ? String(input.payload.raw || "") : String(input.payload.text || "");
4535
- const layoutReply = unsysCanvasLayoutReply(input.payload.raw, input.payload.elements);
4536
- const merge = (text, extra) => mergeUnsysCanvasTurnOntoLiveWorkCanvas(
4537
- live,
4538
- {
4539
- text,
4540
- elements: input.payload.elements,
4541
- turnId: input.payload.turnId,
4542
- origin: input.payload.origin,
4543
- label: noteLabel
4544
- },
4545
- {
4546
- fallbackOrigin: input.fallbackOrigin,
4547
- reserved: input.reserved
5565
+ const prevSel = selectedIds(prev.appState);
5566
+ const nextSel = selectedIds(next.appState);
5567
+ if (prevSel.join(",") !== nextSel.join(",")) {
5568
+ events.push(this.push("selection:changed", { from: prevSel, to: nextSel }));
4548
5569
  }
4549
- );
4550
- let next = live;
4551
- if (kind === "selective-compress") {
4552
- next = compressUnsysCanvasSelection(live, selected, source);
4553
- } else if (kind === "refactor") {
4554
- next = replaceUnsysCanvasSelection(live, selected, {
4555
- text: input.payload.text,
4556
- elements: input.payload.elements,
4557
- turnId: input.payload.turnId,
4558
- label: noteLabel
4559
- });
4560
- } else if (kind === "simplify") {
4561
- const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
4562
- if (text) {
4563
- next = fanUnsysCanvasLabeledNodes(live, selected, [text], "ileSimplify").scene;
5570
+ const prevTool = toolName(prev.appState);
5571
+ const nextTool = toolName(next.appState);
5572
+ if (prevTool !== nextTool) {
5573
+ events.push(this.push("tool:changed", { from: prevTool, to: nextTool }));
4564
5574
  }
4565
- } else if (kind === "concepts") {
4566
- const labels = unsysCanvasConceptLabels(source, {
4567
- text: input.payload.text,
4568
- elements: input.payload.elements
4569
- });
4570
- next = fanUnsysCanvasLabeledNodes(live, selected, labels, "ileConcepts").scene;
4571
- } else if (kind === "suggest-insight") {
4572
- next = applyUnsysCanvasSuggestInsight(live, selected, source);
4573
- } else if (kind === "declutter" || kind === "clear-overlaps") {
4574
- next = applyUnsysCanvasPositionEdits(live, selected, layoutReply);
4575
- } else {
4576
- next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
5575
+ const prevView = {
5576
+ zoom: zoomValue(prev.appState),
5577
+ scrollX: Number(prev.appState.scrollX) || 0,
5578
+ scrollY: Number(prev.appState.scrollY) || 0
5579
+ };
5580
+ const nextView = {
5581
+ zoom: zoomValue(next.appState),
5582
+ scrollX: Number(next.appState.scrollX) || 0,
5583
+ scrollY: Number(next.appState.scrollY) || 0
5584
+ };
5585
+ if (prevView.zoom !== nextView.zoom || prevView.scrollX !== nextView.scrollX || prevView.scrollY !== nextView.scrollY) {
5586
+ events.push(this.push("viewport:changed", { from: prevView, to: nextView }));
5587
+ }
5588
+ this.prev = next;
5589
+ return this.batch(events);
4577
5590
  }
4578
- if (unsysCanvasSceneVisiblyChanged(live, next)) return withUnsysCanvasAutoLayout(next);
4579
- const fallback = stripLearnerFacingWrappers(String(input.payload.text || "").trim()) || unsysCanvasAskFallback(kind);
4580
- return withUnsysCanvasAutoLayout(merge(fallback));
4581
- }
4582
- function applyUnsysCanvasPositionEdits(scene, selectedElements, reply) {
4583
- const current = serializeUnsysCanvasScene(scene);
4584
- const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
4585
- if (!liveSelected.length) return current;
4586
- const edits = parseUnsysCanvasLayoutEdits(reply);
4587
- if (!edits.length) return current;
4588
- const selectedIds2 = new Set(liveSelected.map((el) => el.id));
4589
- const matchById = edits.some((edit) => edit.id && selectedIds2.has(edit.id));
4590
- let ordinal = 0;
4591
- return {
4592
- ...current,
4593
- elements: current.elements.map((el) => {
4594
- if (!selectedIds2.has(el.id) || el.isDeleted) return el;
4595
- const edit = unsysCanvasEditForElement(edits, el, ordinal, matchById);
4596
- ordinal += 1;
4597
- if (!edit || edit.x == null && edit.y == null) return el;
4598
- return {
4599
- ...el,
4600
- x: edit.x == null ? el.x : edit.x,
4601
- y: edit.y == null ? el.y : edit.y,
4602
- version: (Number(el.version) || 1) + 1
4603
- };
4604
- })
4605
- };
4606
- }
4607
- function unsysCanvasAddedElementIds(before, after) {
4608
- const seen = /* @__PURE__ */ new Set();
4609
- for (const el of before?.elements ?? []) {
4610
- const id = String(el?.id || "").trim();
4611
- if (id) seen.add(id);
5591
+ command(id, meta) {
5592
+ const rec = asRecord3(meta);
5593
+ const inputs = asRecord3(rec.inputs);
5594
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements : [];
5595
+ const selectedElementIds = Array.isArray(inputs.selectedElementIds) ? inputs.selectedElementIds : selected.map((el) => el && typeof el === "object" && "id" in el ? String(el.id || "") : "").filter(Boolean);
5596
+ const prompt = typeof inputs.prompt === "string" ? inputs.prompt : typeof rec.prompt === "string" ? rec.prompt : void 0;
5597
+ const eventInputs = prompt ? { selectedElementIds, prompt } : { selectedElementIds };
5598
+ return [
5599
+ this.push("command:run", {
5600
+ id: id ?? null,
5601
+ args: rec,
5602
+ inputs: eventInputs,
5603
+ outputs: rec.outputs ?? null
5604
+ })
5605
+ ];
4612
5606
  }
4613
- const ids = [];
4614
- for (const el of after?.elements ?? []) {
4615
- const id = String(el?.id || "").trim();
4616
- if (!id || el?.isDeleted || seen.has(id)) continue;
4617
- ids.push(id);
5607
+ commandComplete(id, meta) {
5608
+ const rec = asRecord3(meta);
5609
+ return [
5610
+ this.push("command:complete", {
5611
+ id: id ?? null,
5612
+ inputs: rec.inputs ?? {},
5613
+ outputs: rec.outputs ?? {}
5614
+ })
5615
+ ];
4618
5616
  }
4619
- return ids;
5617
+ dictate(meta) {
5618
+ const rec = asRecord3(meta);
5619
+ const type = rec.phase === "start" ? "dictate:start" : rec.phase === "stop" ? "dictate:stop" : "dictate:text";
5620
+ return [this.push(type, rec)];
5621
+ }
5622
+ prompt(text, meta) {
5623
+ return [this.push("prompt:submit", { text: text ?? "", ...asRecord3(meta) })];
5624
+ }
5625
+ laser(meta) {
5626
+ return [this.push("laser:gesture", asRecord3(meta))];
5627
+ }
5628
+ latex(meta) {
5629
+ return [this.push("latex:render", asRecord3(meta))];
5630
+ }
5631
+ history(kind, meta) {
5632
+ return [this.push(kind, asRecord3(meta))];
5633
+ }
5634
+ markGestureBusy(_busy) {
5635
+ }
5636
+ batch(incoming) {
5637
+ const now = Date.now();
5638
+ if (!this.buffer.length) this.lastFlush = now;
5639
+ for (const event of incoming) {
5640
+ const last = this.buffer[this.buffer.length - 1];
5641
+ if (last && HIGH_FREQ.has(event.type) && eventKey(last) === eventKey(event)) {
5642
+ this.buffer[this.buffer.length - 1] = {
5643
+ ...event,
5644
+ seq: last.seq,
5645
+ ts: last.ts,
5646
+ payload: mergePayload(last.payload, event.payload)
5647
+ };
5648
+ } else {
5649
+ this.buffer.push(event);
5650
+ }
5651
+ }
5652
+ if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
5653
+ return [];
5654
+ }
5655
+ const flushed = this.buffer;
5656
+ this.buffer = [];
5657
+ this.lastFlush = now;
5658
+ return flushed;
5659
+ }
5660
+ flush() {
5661
+ const flushed = this.buffer;
5662
+ this.buffer = [];
5663
+ this.lastFlush = Date.now();
5664
+ return flushed;
5665
+ }
5666
+ };
5667
+ function unsysCanvasGestureBusy(_opts) {
5668
+ return false;
4620
5669
  }
4621
5670
 
4622
5671
  // src/lib/work-canvas/work-canvas-laser-gestures.ts
@@ -4624,7 +5673,45 @@ var LASER_DOUBLE_LINE_MS = 650;
4624
5673
  var LASER_TARGET_PAD = 36;
4625
5674
  var UNSYS_CANVAS_POINTER_LABEL = "pointer";
4626
5675
  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.";
5676
+ 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.";
5677
+ var UNSYS_CANVAS_LASER_GESTURES = [
5678
+ {
5679
+ command: "simplify",
5680
+ label: "Simplify",
5681
+ gesture: "Question mark",
5682
+ hint: "Draw a question mark over a mark."
5683
+ },
5684
+ {
5685
+ command: "concepts",
5686
+ label: "Concepts",
5687
+ gesture: "Line",
5688
+ hint: "Draw a line from a mark into empty space."
5689
+ },
5690
+ {
5691
+ command: "breakdown",
5692
+ label: "Subdivide",
5693
+ gesture: "Two lines",
5694
+ hint: "Draw two quick lines from a mark into empty space."
5695
+ },
5696
+ {
5697
+ command: "draw",
5698
+ label: "Do/run",
5699
+ gesture: "Loop",
5700
+ hint: "Draw a circle or loop over a mark."
5701
+ },
5702
+ {
5703
+ command: "refactor",
5704
+ label: "Refactor",
5705
+ gesture: "Zigzag",
5706
+ hint: "Draw a zigzag over a mark."
5707
+ },
5708
+ {
5709
+ command: "pretty",
5710
+ label: "Pretty",
5711
+ gesture: "Check mark",
5712
+ hint: "Draw a check mark over a mark."
5713
+ }
5714
+ ];
4628
5715
  function unsysCanvasPointerToolActive(activeTool) {
4629
5716
  if (typeof activeTool === "string") return activeTool.trim().toLowerCase() === "laser";
4630
5717
  if (activeTool && typeof activeTool === "object" && !Array.isArray(activeTool)) {
@@ -4710,6 +5797,29 @@ function resample(points, count) {
4710
5797
  if (out.length < count) out.push(live[live.length - 1]);
4711
5798
  return out;
4712
5799
  }
5800
+ function axisReversals(samples, axis) {
5801
+ let prevSign = 0;
5802
+ let reversals = 0;
5803
+ for (let i = 1; i < samples.length; i += 1) {
5804
+ const delta = samples[i][axis] - samples[i - 1][axis];
5805
+ if (Math.abs(delta) < 2) continue;
5806
+ const sign = delta > 0 ? 1 : -1;
5807
+ if (prevSign && sign !== prevSign) reversals += 1;
5808
+ prevSign = sign;
5809
+ }
5810
+ return reversals;
5811
+ }
5812
+ function valleyIndex(samples) {
5813
+ let best = 0;
5814
+ let y = -Infinity;
5815
+ for (let i = 0; i < samples.length; i += 1) {
5816
+ if (samples[i].y > y) {
5817
+ y = samples[i].y;
5818
+ best = i;
5819
+ }
5820
+ }
5821
+ return best;
5822
+ }
4713
5823
  function classifyLaserStroke(points) {
4714
5824
  const samples = resample(points, 24);
4715
5825
  if (samples.length < 6) return "unknown";
@@ -4727,6 +5837,20 @@ function classifyLaserStroke(points) {
4727
5837
  const startY = (start.y - box.minY) / height;
4728
5838
  const endY = (end.y - box.minY) / height;
4729
5839
  const aspect = height / width;
5840
+ const diag = Math.hypot(width, height);
5841
+ const closed = diag > 0 && span / diag <= 0.42;
5842
+ if (closed && turns >= 4.2 && aspect >= 0.45 && aspect <= 2.2 && length >= diag * 1.55) {
5843
+ return "loop";
5844
+ }
5845
+ const valleyAt = valleyIndex(samples);
5846
+ const valleyT = valleyAt / Math.max(1, samples.length - 1);
5847
+ const valleyRel = (samples[valleyAt].y - box.minY) / height;
5848
+ 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;
5849
+ if (check) return "check";
5850
+ const reversals = Math.max(axisReversals(samples, "x"), axisReversals(samples, "y"));
5851
+ if (!closed && reversals >= 2 && turns >= 2.4 && straightness < 0.72 && span / diag >= 0.28) {
5852
+ return "zigzag";
5853
+ }
4730
5854
  const first = samples.slice(0, Math.max(4, Math.floor(samples.length * 0.45)));
4731
5855
  const last = samples.slice(Math.floor(samples.length * 0.65));
4732
5856
  const meanX = (pts) => pts.reduce((s, p) => s + p.x, 0) / Math.max(1, pts.length);
@@ -4825,12 +5949,13 @@ function finishLaserStroke(input) {
4825
5949
  if (kind === "unknown") {
4826
5950
  return { session: pendingDue.session, fire: pendingDue.fire, waitMs: null };
4827
5951
  }
4828
- if (kind === "question-mark") {
5952
+ if (kind === "question-mark" || kind === "loop" || kind === "zigzag" || kind === "check") {
4829
5953
  const target2 = targetForQuestion(input.elements, input.stroke);
4830
5954
  if (!target2) return { session: pendingDue.session, fire: pendingDue.fire, waitMs: null };
5955
+ const command = kind === "question-mark" ? "simplify" : kind === "loop" ? "draw" : kind === "zigzag" ? "refactor" : "pretty";
4831
5956
  return {
4832
5957
  session: { pending: null },
4833
- fire: { command: "simplify", targetId: target2.id },
5958
+ fire: { command, targetId: target2.id },
4834
5959
  waitMs: null
4835
5960
  };
4836
5961
  }
@@ -4888,6 +6013,17 @@ function openCanvasScene(scene, scrollToContent, chrome) {
4888
6013
  return scrollToContent ? unsysCanvasWithScrollToContent(next) : next;
4889
6014
  }
4890
6015
 
6016
+ // src/lib/require-onask.ts
6017
+ function assertOnAsk(onAsk) {
6018
+ if (typeof onAsk !== "function") {
6019
+ throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
6020
+ }
6021
+ }
6022
+ function assertCanvasModel(input) {
6023
+ if (typeof input.runModel === "function" || typeof input.onAsk === "function") return;
6024
+ throw new Error("UnsysCanvas requires a runModel or onAsk handler; the package does not call any LLM.");
6025
+ }
6026
+
4891
6027
  // src/components/excalidraw-canvas/excalidraw-api.ts
4892
6028
  function liveSceneElements(api) {
4893
6029
  if (!api) return [];
@@ -5866,6 +7002,20 @@ function useWorkCanvasCommands(input) {
5866
7002
  appState: api.getAppState() ?? {},
5867
7003
  files: api.getFiles() ?? {}
5868
7004
  });
7005
+ emitCanvasEventsRef.current(
7006
+ canvasEventCollectorRef.current.commandComplete(askInput.kind ?? "ask", {
7007
+ inputs: unsysCanvasCommandEventInputs({
7008
+ commandId: String(askInput.kind || "ask"),
7009
+ selectedElements: askInput.selectedElements,
7010
+ prompt: askInput.prompt
7011
+ }),
7012
+ outputs: {
7013
+ ok: true,
7014
+ text: payload.text,
7015
+ addedElementIds: [...addedIds]
7016
+ }
7017
+ })
7018
+ );
5869
7019
  };
5870
7020
  try {
5871
7021
  const scene = liveWorkCanvasScene(api);
@@ -5889,9 +7039,51 @@ function useWorkCanvasCommands(input) {
5889
7039
  "[ExcalidrawCanvas] Ask XAI failed:",
5890
7040
  err instanceof Error ? err.message : String(err)
5891
7041
  );
5892
- const fallback = unsysCanvasAskFallback(askInput.kind);
7042
+ const message = formatUnsysCanvasCommandError(err, { commandId: askInput.kind });
5893
7043
  await enqueueCanvasAskApply(() => {
5894
- applyReply({ text: fallback });
7044
+ const live = liveWorkCanvasScene(api);
7045
+ const liveChip = thinkingChipsRef.current.find((chip) => chip.turnId === turnId);
7046
+ const placeAt = liveChip ? { x: liveChip.x, y: liveChip.y } : origin;
7047
+ const next = applyUnsysCanvasCommandErrorNotice({
7048
+ live,
7049
+ message,
7050
+ fallbackOrigin: placeAt,
7051
+ reserved: reservedThinkingOrigins(turnId)
7052
+ });
7053
+ const addedIds = new Set(unsysCanvasAddedElementIds(live, next));
7054
+ const added = next.elements.filter((el) => addedIds.has(el.id) && !el.isDeleted);
7055
+ const reveal = unsysCanvasRevealScroll(added, api.getAppState() ?? live.appState);
7056
+ commitScene(
7057
+ api,
7058
+ {
7059
+ elements: next.elements,
7060
+ appState: {
7061
+ selectedElementIds: Object.fromEntries(added.map((el) => [el.id, true])),
7062
+ ...reveal ?? {}
7063
+ },
7064
+ ...next.files ? { files: next.files } : {}
7065
+ },
7066
+ { applyingRemote: applyingRemoteRef }
7067
+ );
7068
+ canvasEventCollectorRef.current.syncWithoutEmit({
7069
+ elements: next.elements,
7070
+ appState: api.getAppState() ?? {},
7071
+ files: api.getFiles() ?? {}
7072
+ });
7073
+ emitCanvasEventsRef.current(
7074
+ canvasEventCollectorRef.current.commandComplete(askInput.kind ?? "ask", {
7075
+ inputs: unsysCanvasCommandEventInputs({
7076
+ commandId: String(askInput.kind || "ask"),
7077
+ selectedElements: askInput.selectedElements,
7078
+ prompt: askInput.prompt
7079
+ }),
7080
+ outputs: {
7081
+ ok: false,
7082
+ text: message,
7083
+ addedElementIds: [...addedIds]
7084
+ }
7085
+ })
7086
+ );
5895
7087
  });
5896
7088
  return false;
5897
7089
  } finally {
@@ -5933,7 +7125,12 @@ function useWorkCanvasCommands(input) {
5933
7125
  if (extra?.run) {
5934
7126
  const live2 = liveWorkCanvasScene(api);
5935
7127
  emitCanvasEventsRef.current(
5936
- canvasEventCollectorRef.current.command(action, { extra: true, selectedElements: selected })
7128
+ canvasEventCollectorRef.current.command(action, {
7129
+ extra: true,
7130
+ selectedElements: selected,
7131
+ inputs: unsysCanvasCommandEventInputs({ selectedElements: selected }),
7132
+ outputs: { local: true }
7133
+ })
5937
7134
  );
5938
7135
  void extra.run({ selectedElements: selected, scene: live2 });
5939
7136
  return;
@@ -5946,9 +7143,19 @@ function useWorkCanvasCommands(input) {
5946
7143
  scene: live,
5947
7144
  selectedElements: selected});
5948
7145
  const emitCommand = (commandId, prompt) => {
7146
+ const inputs = unsysCanvasCommandEventInputs({
7147
+ selectedElements: outcome.selected,
7148
+ prompt
7149
+ });
5949
7150
  const powEvents = canvasEventCollectorRef.current.command(commandId, {
5950
7151
  prompt,
5951
- selectedElements: outcome.selected
7152
+ selectedElements: outcome.selected,
7153
+ inputs,
7154
+ outputs: {
7155
+ askKind: outcome.ask?.kind ?? null,
7156
+ local: !outcome.ask,
7157
+ notice: outcome.notice
7158
+ }
5952
7159
  });
5953
7160
  emitCanvasEventsRef.current(powEvents);
5954
7161
  };
@@ -6341,85 +7548,921 @@ function WorkCanvasLatexLayer({
6341
7548
  mount
6342
7549
  );
6343
7550
  }
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";
7551
+ var LASER_ICON = /* @__PURE__ */ jsxs("svg", { "aria-hidden": "true", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [
7552
+ /* @__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" }),
7553
+ /* @__PURE__ */ jsx("path", { d: "m14.2 14.2 3.3 3.3M11 11.6l2 2M6.2 6.2l3 3" })
7554
+ ] });
7555
+ function UnsysLaserToolbarSlot({
7556
+ hostRef,
7557
+ apiRef,
7558
+ active,
7559
+ onToggle
7560
+ }) {
7561
+ const [slot, setSlot] = useState(null);
7562
+ useLayoutEffect(() => {
7563
+ const host = hostRef.current;
7564
+ if (!host) return;
7565
+ let node = host.querySelector("[data-unsys-canvas-toolbar-laser-slot]");
7566
+ const place = () => {
7567
+ const toolbar = host.querySelector(".App-toolbar");
7568
+ if (!toolbar) return;
7569
+ if (!node) {
7570
+ node = document.createElement("div");
7571
+ node.setAttribute("data-unsys-canvas-toolbar-laser-slot", "");
7572
+ node.style.display = "contents";
7573
+ }
7574
+ const divider = toolbar.querySelector(".App-toolbar__divider");
7575
+ if (divider && node.nextSibling !== divider && node.parentElement !== toolbar) {
7576
+ toolbar.insertBefore(node, divider);
7577
+ } else if (!node.parentElement) {
7578
+ toolbar.appendChild(node);
7579
+ }
7580
+ setSlot((prev) => prev === node ? prev : node);
7581
+ };
7582
+ place();
7583
+ let raf = 0;
7584
+ const schedule = () => {
7585
+ if (raf) return;
7586
+ raf = window.requestAnimationFrame(() => {
7587
+ raf = 0;
7588
+ place();
7589
+ });
7590
+ };
7591
+ let observed = null;
7592
+ const observer = new MutationObserver(() => {
7593
+ schedule();
7594
+ attach();
7595
+ });
7596
+ const attach = () => {
7597
+ const toolbar = host.querySelector(".App-toolbar");
7598
+ const target = toolbar ?? host;
7599
+ if (observed === target) return;
7600
+ observer.disconnect();
7601
+ observed = target;
7602
+ observer.observe(target, {
7603
+ childList: true,
7604
+ subtree: target === host
7605
+ });
7606
+ };
7607
+ attach();
7608
+ return () => {
7609
+ observer.disconnect();
7610
+ if (raf) window.cancelAnimationFrame(raf);
7611
+ node?.remove();
7612
+ };
7613
+ }, [hostRef]);
7614
+ if (!slot) return null;
7615
+ return createPortal(
7616
+ /* @__PURE__ */ jsx(
7617
+ "button",
7618
+ {
7619
+ type: "button",
7620
+ "data-unsys-canvas-toolbar-laser": true,
7621
+ className: `ToolIcon ToolIcon_type_toggle${active ? " ToolIcon--checked" : ""}`,
7622
+ title: "Laser pointer \u2014 K",
7623
+ "aria-label": "Laser pointer",
7624
+ "aria-pressed": active ? "true" : "false",
7625
+ onClick: () => onToggle ? onToggle() : setLiveActiveTool(apiRef.current, { type: "laser" }),
7626
+ children: /* @__PURE__ */ jsx("div", { className: "ToolIcon__icon", children: LASER_ICON })
7627
+ }
7628
+ ),
7629
+ slot
7630
+ );
7631
+ }
7632
+
7633
+ // src/lib/work-canvas/work-canvas-url.ts
7634
+ var UNSYS_CANVAS_HASH_PREFIX = "tc1.";
7635
+ var UNSYS_CANVAS_MAX_HASH_LENGTH = 75e4;
7636
+ function unsysCanvasUrlSnapshot(scene) {
7637
+ const serialized = serializeUnsysCanvasScene(scene);
7638
+ const elements = serialized.elements.filter((el) => el && !el.isDeleted);
7639
+ const usedFileIds = new Set(
7640
+ elements.map((el) => typeof el.fileId === "string" ? el.fileId : "").filter(Boolean)
7641
+ );
7642
+ const files = {};
7643
+ for (const [id, file] of Object.entries(serialized.files || {})) {
7644
+ if (usedFileIds.has(id)) files[id] = file;
7645
+ }
7646
+ return {
7647
+ elements,
7648
+ appState: serialized.appState,
7649
+ files
7650
+ };
7651
+ }
7652
+ async function encodeUnsysCanvasHash(scene, options) {
7653
+ const maxHashLength = options?.maxHashLength ?? UNSYS_CANVAS_MAX_HASH_LENGTH;
7654
+ const snapshot2 = unsysCanvasUrlSnapshot(scene);
7655
+ if (!unsysCanvasHasLiveElements(snapshot2)) {
7656
+ return { kind: "empty", hash: "" };
7657
+ }
7658
+ const withFiles = await hashFromPayload({
7659
+ v: 1,
7660
+ elements: snapshot2.elements,
7661
+ appState: snapshot2.appState,
7662
+ files: Object.keys(snapshot2.files).length ? snapshot2.files : void 0
7663
+ });
7664
+ if (withFiles && withFiles.length <= maxHashLength) {
7665
+ return { kind: "ok", hash: withFiles };
7666
+ }
7667
+ const withoutFiles = await hashFromPayload({
7668
+ v: 1,
7669
+ elements: snapshot2.elements,
7670
+ appState: snapshot2.appState
7671
+ });
7672
+ if (withoutFiles && withoutFiles.length <= maxHashLength) {
7673
+ return { kind: "omitted-files", hash: withoutFiles };
7674
+ }
7675
+ return { kind: "too-large", hash: "" };
7676
+ }
7677
+ async function decodeUnsysCanvasHash(hash) {
7678
+ const payload = hashPayload(hash);
7679
+ if (!payload) return null;
7680
+ try {
7681
+ const bytes = await gunzipBytes(base64UrlToBytes(payload));
7682
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
7683
+ return sceneFromPayload(parsed);
7684
+ } catch {
7685
+ return null;
7686
+ }
7687
+ }
7688
+ async function readUnsysCanvasHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
7689
+ return decodeUnsysCanvasHash(hash);
7690
+ }
7691
+ function replaceUnsysCanvasLocationHash(hash) {
7692
+ if (typeof window === "undefined") return;
7693
+ const next = normalizeHash(hash);
7694
+ const current = window.location.hash || "";
7695
+ if (current === next) return;
7696
+ const url = `${window.location.pathname}${window.location.search}${next}`;
7697
+ window.history.replaceState(window.history.state, "", url);
7698
+ }
7699
+ function hashPayload(hash) {
7700
+ const raw = String(hash || "").trim();
7701
+ const body = raw.startsWith("#") ? raw.slice(1) : raw;
7702
+ if (!body.startsWith(UNSYS_CANVAS_HASH_PREFIX)) return null;
7703
+ const payload = body.slice(UNSYS_CANVAS_HASH_PREFIX.length);
7704
+ return payload || null;
7705
+ }
7706
+ function normalizeHash(hash) {
7707
+ if (!hash) return "";
7708
+ return hash.startsWith("#") ? hash : `#${hash}`;
7709
+ }
7710
+ async function hashFromPayload(payload) {
7711
+ try {
7712
+ const json = JSON.stringify(payload);
7713
+ const compressed = await gzipBytes(new TextEncoder().encode(json));
7714
+ return `#${UNSYS_CANVAS_HASH_PREFIX}${bytesToBase64Url(compressed)}`;
7715
+ } catch {
7716
+ return null;
7717
+ }
7718
+ }
7719
+ function sceneFromPayload(parsed) {
7720
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
7721
+ const rec = parsed;
7722
+ if (rec.v !== 1) return null;
7723
+ if (!Array.isArray(rec.elements)) return null;
7724
+ return serializeUnsysCanvasScene({
7725
+ elements: rec.elements,
7726
+ appState: rec.appState,
7727
+ files: rec.files
7728
+ });
7729
+ }
7730
+ async function gzipBytes(bytes) {
7731
+ const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(new CompressionStream("gzip"));
7732
+ return new Uint8Array(await new Response(stream).arrayBuffer());
7733
+ }
7734
+ async function gunzipBytes(bytes) {
7735
+ const stream = new Blob([toArrayBuffer(bytes)]).stream().pipeThrough(
7736
+ new DecompressionStream("gzip")
7737
+ );
7738
+ return new Uint8Array(await new Response(stream).arrayBuffer());
7739
+ }
7740
+ function toArrayBuffer(bytes) {
7741
+ const copy = new Uint8Array(bytes.byteLength);
7742
+ copy.set(bytes);
7743
+ return copy.buffer;
7744
+ }
7745
+ function bytesToBase64Url(bytes) {
7746
+ const chunk = 8192;
7747
+ let binary = "";
7748
+ for (let i = 0; i < bytes.length; i += chunk) {
7749
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
7750
+ }
7751
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
7752
+ }
7753
+ function base64UrlToBytes(value) {
7754
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");
7755
+ const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
7756
+ const binary = atob(padded + pad);
7757
+ const bytes = new Uint8Array(binary.length);
7758
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
7759
+ return bytes;
7760
+ }
7761
+
7762
+ // src/lib/collaboration/collab-url.ts
7763
+ var UNSYS_CANVAS_COLLAB_HASH_PREFIX = "uc1.";
7764
+ var ROOM_ID_BYTES = 12;
7765
+ var KEY_BYTES = 32;
7766
+ function bytesToUnsysCanvasCollabB64(bytes) {
7767
+ const chunk = 8192;
7768
+ let binary = "";
7769
+ for (let i = 0; i < bytes.length; i += chunk) {
7770
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
7771
+ }
7772
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
7773
+ }
7774
+ function unsysCanvasCollabB64ToBytes(value) {
7775
+ const trimmed = String(value || "").trim();
7776
+ if (!trimmed || /[^A-Za-z0-9_-]/.test(trimmed)) return null;
7777
+ try {
7778
+ const padded = trimmed.replace(/-/g, "+").replace(/_/g, "/");
7779
+ const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
7780
+ const binary = atob(padded + pad);
7781
+ const bytes = new Uint8Array(binary.length);
7782
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
7783
+ return bytes;
7784
+ } catch {
7785
+ return null;
7786
+ }
7787
+ }
7788
+ function generateUnsysCanvasCollabRoomId() {
7789
+ const bytes = new Uint8Array(ROOM_ID_BYTES);
7790
+ crypto.getRandomValues(bytes);
7791
+ return bytesToUnsysCanvasCollabB64(bytes);
7792
+ }
7793
+ function generateUnsysCanvasCollabKey() {
7794
+ const bytes = new Uint8Array(KEY_BYTES);
7795
+ crypto.getRandomValues(bytes);
7796
+ return bytesToUnsysCanvasCollabB64(bytes);
7797
+ }
7798
+ function generateUnsysCanvasCollabRoom() {
7799
+ return {
7800
+ roomId: generateUnsysCanvasCollabRoomId(),
7801
+ key: generateUnsysCanvasCollabKey()
7802
+ };
7803
+ }
7804
+ function buildUnsysCanvasCollabHash(room) {
7805
+ const roomId = String(room.roomId || "").trim();
7806
+ const key = String(room.key || "").trim();
7807
+ if (!roomId || !key) return "";
7808
+ return `#${UNSYS_CANVAS_COLLAB_HASH_PREFIX}${roomId}.${key}`;
7809
+ }
7810
+ function parseUnsysCanvasCollabHash(hash) {
7811
+ const raw = String(hash || "").trim();
7812
+ const body = raw.startsWith("#") ? raw.slice(1) : raw;
7813
+ if (!body.startsWith(UNSYS_CANVAS_COLLAB_HASH_PREFIX)) return null;
7814
+ const rest = body.slice(UNSYS_CANVAS_COLLAB_HASH_PREFIX.length);
7815
+ const dot = rest.indexOf(".");
7816
+ if (dot <= 0 || dot === rest.length - 1) return null;
7817
+ const roomId = rest.slice(0, dot);
7818
+ const key = rest.slice(dot + 1);
7819
+ if (!unsysCanvasCollabB64ToBytes(roomId) || !unsysCanvasCollabB64ToBytes(key)) return null;
7820
+ const keyBytes = unsysCanvasCollabB64ToBytes(key);
7821
+ if (!keyBytes || keyBytes.byteLength < 16) return null;
7822
+ return { roomId, key };
7823
+ }
7824
+ function isUnsysCanvasCollabHash(hash) {
7825
+ return parseUnsysCanvasCollabHash(hash) !== null;
7826
+ }
7827
+ function readUnsysCanvasCollabHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
7828
+ return parseUnsysCanvasCollabHash(hash);
7829
+ }
7830
+ function replaceUnsysCanvasCollabLocationHash(room) {
7831
+ const next = buildUnsysCanvasCollabHash(room);
7832
+ replaceUnsysCanvasLocationHash(next);
7833
+ return next;
7834
+ }
7835
+ function buildUnsysCanvasCollabShareUrl(room, href = typeof window === "undefined" ? "" : window.location.href) {
7836
+ const url = String(href || "");
7837
+ const hash = buildUnsysCanvasCollabHash(room);
7838
+ const hashAt = url.indexOf("#");
7839
+ const base = hashAt >= 0 ? url.slice(0, hashAt) : url;
7840
+ return `${base}${hash}`;
7841
+ }
7842
+
7843
+ // src/lib/collaboration/collab-colors.ts
7844
+ var PALETTE = [
7845
+ { background: "#70b1ec", stroke: "#3b88c3" },
7846
+ { background: "#e8a838", stroke: "#c47c12" },
7847
+ { background: "#a987eb", stroke: "#7a5cc5" },
7848
+ { background: "#75c7c0", stroke: "#3a9e96" },
7849
+ { background: "#e86868", stroke: "#c24545" },
7850
+ { background: "#9dd655", stroke: "#6ea62e" }
7851
+ ];
7852
+ function unsysCanvasCollabColorForId(id) {
7853
+ let hash = 0;
7854
+ for (let i = 0; i < id.length; i += 1) hash = hash * 33 + id.charCodeAt(i) >>> 0;
7855
+ return PALETTE[hash % PALETTE.length];
7856
+ }
7857
+ function defaultUnsysCanvasCollabName(userId) {
7858
+ const tail = userId.replace(/[^A-Za-z0-9]/g, "").slice(-4).toUpperCase() || "BOARD";
7859
+ return `Guest-${tail}`;
7860
+ }
7861
+
7862
+ // src/lib/collaboration/collab-identity.ts
7863
+ var USER_ID_KEY = "unsys-canvas.collabUserId";
7864
+ var USER_NAME_KEY = "unsys-canvas.collabName";
7865
+ function randomId() {
7866
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
7867
+ return crypto.randomUUID();
7868
+ }
7869
+ const bytes = new Uint8Array(16);
7870
+ crypto.getRandomValues(bytes);
7871
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
7872
+ }
7873
+ function storageGet(storage, key) {
7874
+ try {
7875
+ return String(storage?.getItem(key) || "").trim();
7876
+ } catch {
7877
+ return "";
7878
+ }
7879
+ }
7880
+ function storageSet(storage, key, value) {
7881
+ try {
7882
+ if (!storage) return;
7883
+ if (value) storage.setItem(key, value);
7884
+ else storage.removeItem(key);
7885
+ } catch {
7886
+ }
7887
+ }
7888
+ function readUnsysCanvasCollabUserId(sessionStorageRef = typeof sessionStorage === "undefined" ? void 0 : sessionStorage) {
7889
+ const existing = storageGet(sessionStorageRef, USER_ID_KEY);
7890
+ if (existing) return existing;
7891
+ const id = randomId();
7892
+ storageSet(sessionStorageRef, USER_ID_KEY, id);
7893
+ return id;
7894
+ }
7895
+ function readUnsysCanvasCollabUsername(localStorageRef = typeof localStorage === "undefined" ? void 0 : localStorage) {
7896
+ return storageGet(localStorageRef, USER_NAME_KEY);
7897
+ }
7898
+ function writeUnsysCanvasCollabUsername(name, localStorageRef = typeof localStorage === "undefined" ? void 0 : localStorage) {
7899
+ storageSet(localStorageRef, USER_NAME_KEY, String(name || "").trim());
7900
+ }
7901
+ function resolveUnsysCanvasCollabUser(name) {
7902
+ const id = readUnsysCanvasCollabUserId();
7903
+ const resolved = String(name || readUnsysCanvasCollabUsername() || "").trim() || defaultUnsysCanvasCollabName(id);
7904
+ return {
7905
+ id,
7906
+ name: resolved,
7907
+ color: unsysCanvasCollabColorForId(id)
7908
+ };
7909
+ }
7910
+
7911
+ // src/lib/collaboration/collab-crypto.ts
7912
+ var IV_BYTES = 12;
7913
+ var MAGIC = 1;
7914
+ function subtle() {
7915
+ const api = globalThis.crypto?.subtle;
7916
+ if (!api) throw new Error("Web Crypto is required for board collaboration.");
7917
+ return api;
7918
+ }
7919
+ async function importUnsysCanvasCollabCryptoKey(keyB64) {
7920
+ const raw = unsysCanvasCollabB64ToBytes(keyB64);
7921
+ if (!raw || raw.byteLength < 16) throw new Error("Invalid collaboration key.");
7922
+ const material = raw.byteLength === 16 || raw.byteLength === 32 ? raw : raw.slice(0, 32);
7923
+ return subtle().importKey("raw", toBuffer(material), "AES-GCM", false, ["encrypt", "decrypt"]);
7924
+ }
7925
+ async function encryptUnsysCanvasCollabBytes(keyB64, plaintext) {
7926
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
7927
+ const iv = new Uint8Array(IV_BYTES);
7928
+ globalThis.crypto.getRandomValues(iv);
7929
+ const cipher = new Uint8Array(
7930
+ await subtle().encrypt({ name: "AES-GCM", iv }, cryptoKey, toBuffer(plaintext))
7931
+ );
7932
+ const packed = new Uint8Array(1 + iv.byteLength + cipher.byteLength);
7933
+ packed[0] = MAGIC;
7934
+ packed.set(iv, 1);
7935
+ packed.set(cipher, 1 + iv.byteLength);
7936
+ return packed;
7937
+ }
7938
+ async function decryptUnsysCanvasCollabBytes(keyB64, packed) {
7939
+ if (!packed.byteLength || packed[0] !== MAGIC) throw new Error("Unknown collaboration payload.");
7940
+ if (packed.byteLength < 1 + IV_BYTES + 16) throw new Error("Truncated collaboration payload.");
7941
+ const iv = packed.subarray(1, 1 + IV_BYTES);
7942
+ const cipher = packed.subarray(1 + IV_BYTES);
7943
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
7944
+ const plain = await subtle().decrypt({ name: "AES-GCM", iv: toBuffer(iv) }, cryptoKey, toBuffer(cipher));
7945
+ return new Uint8Array(plain);
7946
+ }
7947
+ async function encryptUnsysCanvasCollabJson(keyB64, value) {
7948
+ return encryptUnsysCanvasCollabBytes(keyB64, new TextEncoder().encode(JSON.stringify(value)));
7949
+ }
7950
+ async function decryptUnsysCanvasCollabJson(keyB64, packed) {
7951
+ const bytes = await decryptUnsysCanvasCollabBytes(keyB64, packed);
7952
+ return JSON.parse(new TextDecoder().decode(bytes));
7953
+ }
7954
+ function toBuffer(bytes) {
7955
+ const copy = new Uint8Array(bytes.byteLength);
7956
+ copy.set(bytes);
7957
+ return copy.buffer;
7958
+ }
7959
+
7960
+ // src/lib/collaboration/collab-reconcile.ts
7961
+ function versionOf(el) {
7962
+ return Number(el?.version) || 0;
7963
+ }
7964
+ function versionNonceOf(el) {
7965
+ return Number(el?.versionNonce) || 0;
7966
+ }
7967
+ function shouldDiscardRemoteUnsysCanvasElement(local, remote, editingIds) {
7968
+ if (editingIds?.has(remote.id)) return true;
7969
+ if (!local) return false;
7970
+ if (editingIds?.has(local.id)) return true;
7971
+ if (versionOf(local) > versionOf(remote)) return true;
7972
+ if (versionOf(local) === versionOf(remote) && versionNonceOf(local) < versionNonceOf(remote)) {
7973
+ return true;
7974
+ }
7975
+ return false;
7976
+ }
7977
+ function reconcileUnsysCanvasElements(local, remote, options) {
7978
+ const localList = Array.isArray(local) ? local.filter((el) => el && typeof el.id === "string") : [];
7979
+ const remoteList = Array.isArray(remote) ? remote.filter((el) => el && typeof el.id === "string") : [];
7980
+ const editingIds = options?.editingIds ? new Set(options.editingIds) : null;
7981
+ const localMap = new Map(localList.map((el) => [el.id, el]));
7982
+ const added = /* @__PURE__ */ new Set();
7983
+ const next = [];
7984
+ for (const remoteEl of remoteList) {
7985
+ const localEl = localMap.get(remoteEl.id);
7986
+ if (shouldDiscardRemoteUnsysCanvasElement(localEl, remoteEl, editingIds)) {
7987
+ if (localEl && !added.has(localEl.id)) {
7988
+ next.push(localEl);
7989
+ added.add(localEl.id);
6366
7990
  }
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);
7991
+ continue;
7992
+ }
7993
+ next.push(remoteEl);
7994
+ added.add(remoteEl.id);
7995
+ }
7996
+ for (const localEl of localList) {
7997
+ if (added.has(localEl.id)) continue;
7998
+ next.push(localEl);
7999
+ added.add(localEl.id);
8000
+ }
8001
+ return next;
8002
+ }
8003
+ function reconcileUnsysCanvasFiles(local, remote) {
8004
+ return { ...local ?? {}, ...remote ?? {} };
8005
+ }
8006
+ function unsysCanvasEditingElementIds(appState) {
8007
+ if (!appState) return [];
8008
+ const ids = [];
8009
+ for (const key of [
8010
+ "editingTextElement",
8011
+ "editingElement",
8012
+ "resizingElement",
8013
+ "newElement",
8014
+ "draggingElement"
8015
+ ]) {
8016
+ const value = appState[key];
8017
+ if (value && typeof value === "object" && typeof value.id === "string") {
8018
+ ids.push(value.id);
8019
+ }
8020
+ }
8021
+ return ids;
8022
+ }
8023
+ function reconcileUnsysCanvasScene(local, remote, options) {
8024
+ return {
8025
+ elements: reconcileUnsysCanvasElements(local?.elements, remote?.elements, options),
8026
+ files: reconcileUnsysCanvasFiles(local?.files, remote?.files ?? {})
8027
+ };
8028
+ }
8029
+
8030
+ // src/lib/collaboration/collab-session.ts
8031
+ function isPlainMessage(value) {
8032
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
8033
+ const rec = value;
8034
+ if (rec.v !== 1 || typeof rec.from !== "string" || !rec.from) return false;
8035
+ if (rec.type !== "hello" && rec.type !== "scene" && rec.type !== "pointer") return false;
8036
+ return true;
8037
+ }
8038
+ function collaboratorFromUser(user, extra) {
8039
+ return {
8040
+ id: user.id,
8041
+ username: user.name,
8042
+ color: user.color,
8043
+ userState: "active",
8044
+ ...extra
8045
+ };
8046
+ }
8047
+ var UnsysCanvasCollabSession = class {
8048
+ constructor(options) {
8049
+ this.socket = null;
8050
+ this.collaborators = /* @__PURE__ */ new Map();
8051
+ this.closed = false;
8052
+ this.roomId = options.roomId;
8053
+ this.key = options.key;
8054
+ this.user = options.user;
8055
+ this.transport = options.transport;
8056
+ this.handlers = options.handlers ?? {};
8057
+ this.getLocalScene = options.getLocalScene;
8058
+ this.getEditingIds = options.getEditingIds;
8059
+ }
8060
+ start() {
8061
+ if (this.socket || this.closed) return;
8062
+ this.socket = this.transport.open(this.roomId, {
8063
+ onOpen: () => {
8064
+ void this.sendHello();
8065
+ this.handlers.onOpen?.();
8066
+ },
8067
+ onMessage: (bytes) => {
8068
+ void this.handleBytes(bytes);
8069
+ },
8070
+ onClose: () => {
8071
+ this.handlers.onClose?.();
8072
+ },
8073
+ onError: (error) => {
8074
+ this.handlers.onError?.(error);
6372
8075
  }
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();
8076
+ });
8077
+ }
8078
+ close() {
8079
+ this.closed = true;
8080
+ this.socket?.close();
8081
+ this.socket = null;
8082
+ this.collaborators = /* @__PURE__ */ new Map();
8083
+ this.emitCollaborators();
8084
+ }
8085
+ async broadcastScene(scene) {
8086
+ await this.send({
8087
+ v: 1,
8088
+ from: this.user.id,
8089
+ type: "scene",
8090
+ user: this.user,
8091
+ scene: {
8092
+ elements: scene.elements ?? [],
8093
+ files: scene.files ?? {}
8094
+ }
8095
+ });
8096
+ }
8097
+ async broadcastPointer(pointer) {
8098
+ await this.send({
8099
+ v: 1,
8100
+ from: this.user.id,
8101
+ type: "pointer",
8102
+ user: this.user,
8103
+ pointer
8104
+ });
8105
+ }
8106
+ async sendHello() {
8107
+ await this.send({ v: 1, from: this.user.id, type: "hello", user: this.user });
8108
+ const scene = this.getLocalScene?.();
8109
+ if (scene?.elements?.length) await this.broadcastScene(scene);
8110
+ }
8111
+ async send(message) {
8112
+ if (!this.socket || this.closed) return;
8113
+ try {
8114
+ const packed = await encryptUnsysCanvasCollabJson(this.key, message);
8115
+ this.socket.send(packed);
8116
+ } catch (error) {
8117
+ this.handlers.onError?.(error);
8118
+ }
8119
+ }
8120
+ async handleBytes(bytes) {
8121
+ if (this.closed) return;
8122
+ let parsed;
8123
+ try {
8124
+ parsed = await decryptUnsysCanvasCollabJson(this.key, bytes);
8125
+ } catch {
8126
+ return;
8127
+ }
8128
+ if (!isPlainMessage(parsed) || parsed.from === this.user.id) return;
8129
+ this.touchCollaborator(parsed);
8130
+ if (parsed.type === "hello") {
8131
+ const scene = this.getLocalScene?.();
8132
+ if (scene) await this.broadcastScene(scene);
8133
+ return;
8134
+ }
8135
+ if (parsed.type === "pointer") {
8136
+ this.collaborators.set(
8137
+ parsed.from,
8138
+ collaboratorFromUser(parsed.user, {
8139
+ pointer: parsed.pointer.pointer,
8140
+ button: parsed.pointer.button,
8141
+ selectedElementIds: parsed.pointer.selectedElementIds
8142
+ })
8143
+ );
8144
+ this.emitCollaborators();
8145
+ return;
8146
+ }
8147
+ if (parsed.type === "scene") {
8148
+ const local = this.getLocalScene?.() ?? { elements: [], files: {} };
8149
+ const remote = {
8150
+ elements: parsed.scene.elements ?? [],
8151
+ files: parsed.scene.files ?? {}
8152
+ };
8153
+ const merged = reconcileUnsysCanvasScene(local, remote, {
8154
+ editingIds: this.getEditingIds?.() ?? null
6382
8155
  });
6383
- };
6384
- let observed = null;
6385
- const observer = new MutationObserver(() => {
6386
- schedule();
6387
- attach();
8156
+ this.handlers.onRemoteScene?.(merged, parsed.user);
8157
+ }
8158
+ }
8159
+ touchCollaborator(message) {
8160
+ const prev = this.collaborators.get(message.from);
8161
+ this.collaborators.set(message.from, {
8162
+ ...collaboratorFromUser(message.user),
8163
+ pointer: prev?.pointer,
8164
+ button: prev?.button,
8165
+ selectedElementIds: prev?.selectedElementIds
6388
8166
  });
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
8167
+ this.emitCollaborators();
8168
+ }
8169
+ emitCollaborators() {
8170
+ this.handlers.onCollaborators?.(new Map(this.collaborators));
8171
+ }
8172
+ };
8173
+
8174
+ // src/components/collaboration/use-work-canvas-collaboration.ts
8175
+ var SCENE_THROTTLE_MS = 80;
8176
+ var POINTER_THROTTLE_MS = 40;
8177
+ var TOAST_MS = 2200;
8178
+ async function copyText(text) {
8179
+ try {
8180
+ if (navigator.clipboard?.writeText) {
8181
+ await navigator.clipboard.writeText(text);
8182
+ return true;
8183
+ }
8184
+ } catch {
8185
+ }
8186
+ try {
8187
+ const field = document.createElement("textarea");
8188
+ field.value = text;
8189
+ field.setAttribute("readonly", "true");
8190
+ field.style.position = "fixed";
8191
+ field.style.left = "-9999px";
8192
+ document.body.appendChild(field);
8193
+ field.select();
8194
+ const ok = document.execCommand("copy");
8195
+ field.remove();
8196
+ return ok;
8197
+ } catch {
8198
+ return false;
8199
+ }
8200
+ }
8201
+ function useWorkCanvasCollaboration({
8202
+ enabled,
8203
+ adapter,
8204
+ getScene,
8205
+ getEditingIds,
8206
+ applyRemoteScene
8207
+ }) {
8208
+ const adapterRef = useRef(adapter);
8209
+ adapterRef.current = adapter;
8210
+ const getSceneRef = useRef(getScene);
8211
+ getSceneRef.current = getScene;
8212
+ const getEditingIdsRef = useRef(getEditingIds);
8213
+ getEditingIdsRef.current = getEditingIds;
8214
+ const applyRemoteSceneRef = useRef(applyRemoteScene);
8215
+ applyRemoteSceneRef.current = applyRemoteScene;
8216
+ const sessionRef = useRef(null);
8217
+ const roomRef = useRef(null);
8218
+ const lastPointerAtRef = useRef(0);
8219
+ const sceneTimerRef = useRef(null);
8220
+ const lastBroadcastSigRef = useRef("");
8221
+ const pendingInviteRef = useRef(false);
8222
+ const [collaborators, setCollaborators] = useState(
8223
+ () => /* @__PURE__ */ new Map()
8224
+ );
8225
+ const [isCollaborating, setIsCollaborating] = useState(false);
8226
+ const [toast, setToast] = useState(null);
8227
+ const [nameDraft, setNameDraft] = useState("");
8228
+ const [namePromptOpen, setNamePromptOpen] = useState(false);
8229
+ const showToast = useCallback((message) => {
8230
+ setToast(message);
8231
+ window.setTimeout(() => {
8232
+ setToast((current) => current === message ? null : current);
8233
+ }, TOAST_MS);
8234
+ }, []);
8235
+ const stopSession = useCallback(() => {
8236
+ if (sceneTimerRef.current) {
8237
+ window.clearTimeout(sceneTimerRef.current);
8238
+ sceneTimerRef.current = null;
8239
+ }
8240
+ sessionRef.current?.close();
8241
+ sessionRef.current = null;
8242
+ setCollaborators(/* @__PURE__ */ new Map());
8243
+ setIsCollaborating(false);
8244
+ }, []);
8245
+ const startSession = useCallback(
8246
+ (room, username) => {
8247
+ const transport = adapterRef.current;
8248
+ if (!transport) return false;
8249
+ stopSession();
8250
+ const user = resolveUnsysCanvasCollabUser(username);
8251
+ roomRef.current = room;
8252
+ const session = new UnsysCanvasCollabSession({
8253
+ roomId: room.roomId,
8254
+ key: room.key,
8255
+ user,
8256
+ transport,
8257
+ getLocalScene: () => {
8258
+ const scene = getSceneRef.current();
8259
+ if (!scene) return null;
8260
+ return { elements: scene.elements ?? [], files: scene.files ?? {} };
8261
+ },
8262
+ getEditingIds: () => getEditingIdsRef.current(),
8263
+ handlers: {
8264
+ onRemoteScene: (scene) => {
8265
+ lastBroadcastSigRef.current = unsysCanvasPersistSignature({
8266
+ elements: scene.elements,
8267
+ files: scene.files
8268
+ });
8269
+ applyRemoteSceneRef.current(scene);
8270
+ },
8271
+ onCollaborators: setCollaborators,
8272
+ onOpen: () => setIsCollaborating(true),
8273
+ onClose: () => setIsCollaborating(false)
8274
+ }
6398
8275
  });
8276
+ sessionRef.current = session;
8277
+ session.start();
8278
+ setIsCollaborating(true);
8279
+ return true;
8280
+ },
8281
+ [stopSession]
8282
+ );
8283
+ useEffect(() => {
8284
+ if (!enabled) {
8285
+ stopSession();
8286
+ return;
8287
+ }
8288
+ const room = parseUnsysCanvasCollabHash(
8289
+ typeof window === "undefined" ? "" : window.location.hash
8290
+ );
8291
+ if (!room) return;
8292
+ if (!adapterRef.current) return;
8293
+ startSession(room);
8294
+ return () => {
8295
+ stopSession();
6399
8296
  };
6400
- attach();
8297
+ }, [enabled, adapter, startSession, stopSession]);
8298
+ const broadcastScene = useCallback((scene) => {
8299
+ if (!sessionRef.current) return;
8300
+ const sig = unsysCanvasPersistSignature(scene);
8301
+ if (sig === lastBroadcastSigRef.current) return;
8302
+ lastBroadcastSigRef.current = sig;
8303
+ if (sceneTimerRef.current) window.clearTimeout(sceneTimerRef.current);
8304
+ sceneTimerRef.current = window.setTimeout(() => {
8305
+ sceneTimerRef.current = null;
8306
+ const live = getSceneRef.current();
8307
+ if (!live || !sessionRef.current) return;
8308
+ void sessionRef.current.broadcastScene({
8309
+ elements: live.elements ?? [],
8310
+ files: live.files ?? {}
8311
+ });
8312
+ }, SCENE_THROTTLE_MS);
8313
+ }, []);
8314
+ const broadcastPointer = useCallback((pointer) => {
8315
+ const session = sessionRef.current;
8316
+ if (!session) return;
8317
+ const now = Date.now();
8318
+ if (pointer.button === "up" || now - lastPointerAtRef.current >= POINTER_THROTTLE_MS) {
8319
+ lastPointerAtRef.current = now;
8320
+ void session.broadcastPointer(pointer);
8321
+ }
8322
+ }, []);
8323
+ const finishInvite = useCallback(async () => {
8324
+ const existing = roomRef.current ?? parseUnsysCanvasCollabHash(window.location.hash);
8325
+ const room = existing ?? generateUnsysCanvasCollabRoom();
8326
+ replaceUnsysCanvasCollabLocationHash(room);
8327
+ roomRef.current = room;
8328
+ if (!sessionRef.current) startSession(room);
8329
+ const share = buildUnsysCanvasCollabShareUrl(room);
8330
+ const copied = await copyText(share);
8331
+ showToast(copied ? "Link copied" : "Copy the URL from the address bar");
8332
+ }, [showToast, startSession]);
8333
+ const invite = useCallback(() => {
8334
+ if (!adapterRef.current) return;
8335
+ const stored = readUnsysCanvasCollabUsername();
8336
+ if (!stored) {
8337
+ pendingInviteRef.current = true;
8338
+ setNameDraft(resolveUnsysCanvasCollabUser().name);
8339
+ setNamePromptOpen(true);
8340
+ return;
8341
+ }
8342
+ void finishInvite();
8343
+ }, [finishInvite]);
8344
+ const confirmName = useCallback(() => {
8345
+ const name = nameDraft.trim() || resolveUnsysCanvasCollabUser().name;
8346
+ writeUnsysCanvasCollabUsername(name);
8347
+ setNamePromptOpen(false);
8348
+ const shouldInvite = pendingInviteRef.current;
8349
+ pendingInviteRef.current = false;
8350
+ const room = roomRef.current ?? parseUnsysCanvasCollabHash(window.location.hash);
8351
+ if (room && !sessionRef.current) startSession(room, name);
8352
+ if (shouldInvite) void finishInvite();
8353
+ }, [finishInvite, nameDraft, startSession]);
8354
+ const cancelName = useCallback(() => {
8355
+ pendingInviteRef.current = false;
8356
+ setNamePromptOpen(false);
8357
+ }, []);
8358
+ useEffect(() => {
6401
8359
  return () => {
6402
- observer.disconnect();
6403
- if (raf) window.cancelAnimationFrame(raf);
6404
- node?.remove();
8360
+ if (sceneTimerRef.current) window.clearTimeout(sceneTimerRef.current);
8361
+ sessionRef.current?.close();
6405
8362
  };
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
8363
+ }, []);
8364
+ return {
8365
+ collaborators,
8366
+ isCollaborating,
8367
+ toast,
8368
+ namePromptOpen,
8369
+ nameDraft,
8370
+ setNameDraft,
8371
+ invite,
8372
+ confirmName,
8373
+ cancelName,
8374
+ broadcastScene,
8375
+ broadcastPointer,
8376
+ canInvite: Boolean(adapter)
8377
+ };
8378
+ }
8379
+ function CanvasCollabToast({ message }) {
8380
+ if (!message) return null;
8381
+ return /* @__PURE__ */ jsx(
8382
+ "div",
8383
+ {
8384
+ "data-unsys-canvas-collab-toast": true,
8385
+ 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)]",
8386
+ role: "status",
8387
+ children: message
8388
+ }
8389
+ );
8390
+ }
8391
+ function CanvasInviteButton({
8392
+ disabled,
8393
+ hint,
8394
+ onClick
8395
+ }) {
8396
+ return /* @__PURE__ */ jsx(
8397
+ "button",
8398
+ {
8399
+ type: "button",
8400
+ "data-unsys-canvas-invite": true,
8401
+ "aria-label": "Invite",
8402
+ title: disabled ? hint || "Invite needs a collaboration relay." : "Copy a live board link",
8403
+ disabled,
8404
+ onClick,
8405
+ 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",
8406
+ children: "Invite"
8407
+ }
8408
+ );
8409
+ }
8410
+ function CanvasCollabNamePrompt({
8411
+ value,
8412
+ onChange,
8413
+ onSubmit,
8414
+ onCancel
8415
+ }) {
8416
+ return /* @__PURE__ */ jsx(
8417
+ "div",
8418
+ {
8419
+ "data-unsys-canvas-collab-name": true,
8420
+ className: "absolute inset-0 z-40 flex items-start justify-end bg-black/40 p-3",
8421
+ children: /* @__PURE__ */ jsxs(
8422
+ "form",
8423
+ {
8424
+ className: "w-72 border border-white/40 bg-black p-3 shadow-[0_12px_32px_rgba(0,0,0,0.5)]",
8425
+ onSubmit: (event) => {
8426
+ event.preventDefault();
8427
+ onSubmit();
8428
+ },
8429
+ children: [
8430
+ /* @__PURE__ */ jsxs("label", { className: "block font-mono text-[10px] uppercase tracking-[0.14em] text-white/70", children: [
8431
+ "Display name",
8432
+ /* @__PURE__ */ jsx(
8433
+ "input",
8434
+ {
8435
+ "data-unsys-canvas-collab-name-input": true,
8436
+ value,
8437
+ onChange: (event) => onChange(event.target.value),
8438
+ autoComplete: "nickname",
8439
+ className: "mt-2 w-full border border-white/30 bg-neutral-950 px-2 py-1.5 font-mono text-[12px] text-white"
8440
+ }
8441
+ )
8442
+ ] }),
8443
+ /* @__PURE__ */ jsxs("div", { className: "mt-3 flex justify-end gap-2", children: [
8444
+ /* @__PURE__ */ jsx(
8445
+ "button",
8446
+ {
8447
+ type: "button",
8448
+ className: "border border-white/30 px-2 py-1 font-mono text-[10px] uppercase tracking-wider text-white/70 hover:text-white",
8449
+ onClick: onCancel,
8450
+ children: "Cancel"
8451
+ }
8452
+ ),
8453
+ /* @__PURE__ */ jsx(
8454
+ "button",
8455
+ {
8456
+ type: "submit",
8457
+ 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",
8458
+ children: "Join"
8459
+ }
8460
+ )
8461
+ ] })
8462
+ ]
8463
+ }
8464
+ )
8465
+ }
6423
8466
  );
6424
8467
  }
6425
8468
 
@@ -6550,6 +8593,7 @@ function ExcalidrawCanvas({
6550
8593
  scrollAppliedElements = true,
6551
8594
  onEvent,
6552
8595
  onAsk,
8596
+ runModel,
6553
8597
  boardId = null,
6554
8598
  askBusy = false,
6555
8599
  onLearnerWaitChange,
@@ -6566,11 +8610,12 @@ function ExcalidrawCanvas({
6566
8610
  sidebarStyle: sidebarStyleProp,
6567
8611
  style: styleProp,
6568
8612
  liveCanvasChrome = false,
6569
- extraCommands = []
8613
+ extraCommands = [],
8614
+ collaboration = null,
8615
+ invite = false,
8616
+ inviteHint = null
6570
8617
  }) {
6571
- if (typeof onAsk !== "function") {
6572
- throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
6573
- }
8618
+ assertCanvasModel({ onAsk, runModel });
6574
8619
  const { t } = useI18n();
6575
8620
  const submitButtonLabel = submitLabel || t("whiteboard.submitBoard");
6576
8621
  const sidebarStyle = parseUnsysCanvasStyle(styleProp ?? sidebarStyleProp);
@@ -6585,7 +8630,10 @@ function ExcalidrawCanvas({
6585
8630
  const [canvasApiReady, setCanvasApiReady] = useState(false);
6586
8631
  const [commandText, setCommandText] = useState("");
6587
8632
  const [slashBarOpen, setSlashBarOpen] = useState(false);
8633
+ const [pickerPos, setPickerPos] = useState({ left: 24, top: 24 });
6588
8634
  const commandInputRef = useRef(null);
8635
+ const lastPointerHostRef = useRef({ x: 24, y: 24 });
8636
+ const pickerSelectedRef = useRef([]);
6589
8637
  const selectionWasActiveRef = useRef(false);
6590
8638
  const [askInFlight, setAskInFlight] = useState(0);
6591
8639
  const lastReplaceNonceRef = useRef(null);
@@ -6607,7 +8655,32 @@ function ExcalidrawCanvas({
6607
8655
  sessionBranchRef.current = null;
6608
8656
  const branchQuestions = openBranchQuestions(sessionBranchRef.current);
6609
8657
  const markQuestionsForBar = branchQuestions.length > 0 ? branchQuestions : markQuestions;
6610
- const onAskRef = useRef(onAsk);
8658
+ const extraCommandsRef = useRef(extraCommands);
8659
+ extraCommandsRef.current = extraCommands;
8660
+ const runModelRef = useRef(runModel);
8661
+ runModelRef.current = runModel;
8662
+ const hostAskRef = useRef(onAsk);
8663
+ hostAskRef.current = onAsk;
8664
+ const resolveAsk = useCallback(
8665
+ async (input) => {
8666
+ const model = runModelRef.current;
8667
+ if (model) {
8668
+ const commandId = input.kind && input.kind !== "ask" ? String(input.kind) : "ask";
8669
+ return runUnsysCanvasModelAsk(model, {
8670
+ commandId,
8671
+ scene: input.scene,
8672
+ selectedElements: input.selectedElements,
8673
+ prompt: input.prompt,
8674
+ extras: extraCommandsRef.current
8675
+ });
8676
+ }
8677
+ const ask = hostAskRef.current;
8678
+ if (!ask) throw new Error("UnsysCanvas requires a runModel or onAsk handler; the package does not call any LLM.");
8679
+ return ask(input);
8680
+ },
8681
+ []
8682
+ );
8683
+ const onAskRef = useRef(resolveAsk);
6611
8684
  const askInFlightRef = useRef(0);
6612
8685
  const applyingRemoteRef = useRef(false);
6613
8686
  const sceneDataRef = useRef(null);
@@ -6860,8 +8933,8 @@ function ExcalidrawCanvas({
6860
8933
  );
6861
8934
  }, [boardId]);
6862
8935
  useEffect(() => {
6863
- onAskRef.current = onAsk;
6864
- }, [onAsk]);
8936
+ onAskRef.current = resolveAsk;
8937
+ }, [resolveAsk]);
6865
8938
  const onLearnerWaitChangeRef = useRef(onLearnerWaitChange);
6866
8939
  useEffect(() => {
6867
8940
  onLearnerWaitChangeRef.current = onLearnerWaitChange;
@@ -6963,6 +9036,49 @@ function ExcalidrawCanvas({
6963
9036
  writeDictatedText,
6964
9037
  submitCommand
6965
9038
  } = commands;
9039
+ const applyRemoteCollabScene = useCallback(
9040
+ (remote) => {
9041
+ const api = excalidrawAPIRef.current;
9042
+ if (!api) return;
9043
+ commitScene(
9044
+ api,
9045
+ { elements: remote.elements, files: remote.files },
9046
+ { applyingRemote: applyingRemoteRef }
9047
+ );
9048
+ },
9049
+ []
9050
+ );
9051
+ const {
9052
+ collaborators,
9053
+ isCollaborating,
9054
+ toast,
9055
+ namePromptOpen,
9056
+ nameDraft,
9057
+ setNameDraft,
9058
+ invite: inviteToRoom,
9059
+ confirmName,
9060
+ cancelName,
9061
+ broadcastScene,
9062
+ broadcastPointer,
9063
+ canInvite
9064
+ } = useWorkCanvasCollaboration({
9065
+ enabled: Boolean(collaboration),
9066
+ adapter: collaboration,
9067
+ getScene: () => sceneDataRef.current,
9068
+ getEditingIds: () => unsysCanvasEditingElementIds(
9069
+ excalidrawAPIRef.current?.getAppState() ?? {}
9070
+ ),
9071
+ applyRemoteScene: applyRemoteCollabScene
9072
+ });
9073
+ useEffect(() => {
9074
+ const api = excalidrawAPIRef.current;
9075
+ if (!api) return;
9076
+ commitScene(
9077
+ api,
9078
+ { collaborators: isCollaborating ? collaborators : /* @__PURE__ */ new Map() },
9079
+ { applyingRemote: applyingRemoteRef }
9080
+ );
9081
+ }, [canvasApiReady, collaborators, isCollaborating]);
6966
9082
  const { onLaserPointerUpdate } = useWorkCanvasLaser({
6967
9083
  apiRef: excalidrawAPIRef,
6968
9084
  handleQuickActionRef,
@@ -6970,10 +9086,40 @@ function ExcalidrawCanvas({
6970
9086
  emitCanvasEventsRef.current(canvasEventCollectorRef.current.laser(payload));
6971
9087
  }
6972
9088
  });
9089
+ const openCommandPickerAt = useCallback(
9090
+ (pointer) => {
9091
+ const host = canvasHostRef.current;
9092
+ const viewport = {
9093
+ width: host?.clientWidth ?? 320,
9094
+ height: host?.clientHeight ?? 240
9095
+ };
9096
+ const selected = selectedCanvasElements();
9097
+ const selection = unsysCanvasSelectionHostRect(
9098
+ selected,
9099
+ excalidrawAPIRef.current?.getAppState?.() ?? {}
9100
+ );
9101
+ setPickerPos(
9102
+ placeUnsysCanvasCommandPicker({
9103
+ selection,
9104
+ pointer: pointer ?? lastPointerHostRef.current,
9105
+ viewport
9106
+ })
9107
+ );
9108
+ pickerSelectedRef.current = selected;
9109
+ setCommandText("");
9110
+ setSlashBarOpen(true);
9111
+ },
9112
+ [selectedCanvasElements]
9113
+ );
6973
9114
  useEffect(() => {
6974
9115
  const onKey = (event) => {
6975
9116
  const target = event.target;
6976
9117
  const typingInField = target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || Boolean(target?.isContentEditable);
9118
+ if (slashBarOpen && event.key === "Escape" && !typingInField) {
9119
+ event.preventDefault();
9120
+ setSlashBarOpen(false);
9121
+ return;
9122
+ }
6977
9123
  if (typingInField) return;
6978
9124
  const letter = unsysCanvasCommandShortcutKeyFromEvent(event);
6979
9125
  const key = String(event.key || "").toLowerCase();
@@ -6982,7 +9128,7 @@ function ExcalidrawCanvas({
6982
9128
  const kind = event.shiftKey ? "redo" : "undo";
6983
9129
  emitCanvasEventsRef.current(canvasEventCollectorRef.current.history(kind, { key }));
6984
9130
  }
6985
- if (letter) {
9131
+ if (letter && !slashBarOpen) {
6986
9132
  const command = unsysCanvasCommandByShortcut(letter, markModeRef.current, extraCommands);
6987
9133
  if (command) {
6988
9134
  event.preventDefault();
@@ -6998,12 +9144,17 @@ function ExcalidrawCanvas({
6998
9144
  return;
6999
9145
  }
7000
9146
  event.preventDefault();
7001
- setSlashBarOpen(true);
7002
- setCommandText((current) => current.startsWith("/") ? current : "/");
9147
+ openCommandPickerAt(lastPointerHostRef.current);
7003
9148
  };
7004
9149
  window.addEventListener("keydown", onKey);
7005
9150
  return () => window.removeEventListener("keydown", onKey);
7006
- }, [canvasSelectionActive, extraCommands, handleQuickActionRef]);
9151
+ }, [
9152
+ canvasSelectionActive,
9153
+ extraCommands,
9154
+ handleQuickActionRef,
9155
+ openCommandPickerAt,
9156
+ slashBarOpen
9157
+ ]);
7007
9158
  useEffect(() => {
7008
9159
  if (!unsysCanvasSlashBarOpen({
7009
9160
  selectionActive: canvasSelectionActive,
@@ -7156,6 +9307,7 @@ function ExcalidrawCanvas({
7156
9307
  gestureBusy: unsysCanvasGestureBusy()
7157
9308
  });
7158
9309
  emitCanvasEventsRef.current(powEvents);
9310
+ broadcastScene(sceneData);
7159
9311
  }
7160
9312
  if (scenePersistTimeoutRef.current) clearTimeout(scenePersistTimeoutRef.current);
7161
9313
  scenePersistTimeoutRef.current = setTimeout(() => {
@@ -7179,11 +9331,16 @@ function ExcalidrawCanvas({
7179
9331
  const laserOn = unsysCanvasPointerToolActive(appState.activeTool);
7180
9332
  setLaserToolActive((prev) => prev === laserOn ? prev : laserOn);
7181
9333
  },
7182
- [debouncedExportPNG, syncCanvasSelection, syncLatexOverlay, syncThinkingOverlay]
9334
+ [broadcastScene, debouncedExportPNG, syncCanvasSelection, syncLatexOverlay, syncThinkingOverlay]
7183
9335
  );
7184
9336
  const handlePointerUpdate = useCallback(
7185
9337
  (payload) => {
7186
9338
  onLaserPointerUpdate(payload);
9339
+ broadcastPointer({
9340
+ pointer: payload.pointer,
9341
+ button: payload.button,
9342
+ selectedElementIds: excalidrawAPIRef.current?.getAppState?.()?.selectedElementIds
9343
+ });
7187
9344
  const api = excalidrawAPIRef.current;
7188
9345
  if (payload.button === "down" && api) {
7189
9346
  syncCanvasSelection(api.getAppState?.() ?? {});
@@ -7203,7 +9360,7 @@ function ExcalidrawCanvas({
7203
9360
  emitCanvasEventsRef.current(powEvents);
7204
9361
  }
7205
9362
  },
7206
- [onLaserPointerUpdate, syncCanvasSelection]
9363
+ [broadcastPointer, onLaserPointerUpdate, syncCanvasSelection]
7207
9364
  );
7208
9365
  const handleSubmitBoard = useCallback(async () => {
7209
9366
  if (!onSubmitBoard || isSubmittingBoard || !canSubmitBoard) return;
@@ -7324,6 +9481,22 @@ function ExcalidrawCanvas({
7324
9481
  className: "relative min-h-0 flex-1",
7325
9482
  "data-unsys-canvas-host": true,
7326
9483
  style: { backgroundColor: sidebarStyle.canvas.background },
9484
+ onMouseMove: (event) => {
9485
+ const rect = event.currentTarget.getBoundingClientRect();
9486
+ lastPointerHostRef.current = {
9487
+ x: event.clientX - rect.left,
9488
+ y: event.clientY - rect.top
9489
+ };
9490
+ },
9491
+ onContextMenu: (event) => {
9492
+ if (!canvasSelectionActive) return;
9493
+ event.preventDefault();
9494
+ const rect = event.currentTarget.getBoundingClientRect();
9495
+ openCommandPickerAt({
9496
+ x: event.clientX - rect.left,
9497
+ y: event.clientY - rect.top
9498
+ });
9499
+ },
7327
9500
  children: [
7328
9501
  isLoaded && /* @__PURE__ */ jsx(UnsysExcalidrawErrorBoundary, { children: /* @__PURE__ */ jsx(
7329
9502
  UnsysExcalidrawMount,
@@ -7332,9 +9505,28 @@ function ExcalidrawCanvas({
7332
9505
  onChange: handleChange,
7333
9506
  onPointerUpdate: handlePointerUpdate,
7334
9507
  initialData: initialSceneDataRef.current,
7335
- viewModeEnabled
9508
+ viewModeEnabled,
9509
+ isCollaborating
7336
9510
  }
7337
9511
  ) }),
9512
+ invite ? /* @__PURE__ */ jsx(
9513
+ CanvasInviteButton,
9514
+ {
9515
+ disabled: !canInvite,
9516
+ hint: inviteHint,
9517
+ onClick: inviteToRoom
9518
+ }
9519
+ ) : null,
9520
+ /* @__PURE__ */ jsx(CanvasCollabToast, { message: toast }),
9521
+ namePromptOpen ? /* @__PURE__ */ jsx(
9522
+ CanvasCollabNamePrompt,
9523
+ {
9524
+ value: nameDraft,
9525
+ onChange: setNameDraft,
9526
+ onSubmit: confirmName,
9527
+ onCancel: cancelName
9528
+ }
9529
+ ) : null,
7338
9530
  /* @__PURE__ */ jsx(
7339
9531
  UnsysLaserToolbarSlot,
7340
9532
  {
@@ -7390,7 +9582,61 @@ function ExcalidrawCanvas({
7390
9582
  selectedMarkTexts: selectedCanvasElements().map((element) => element.text || "").filter((text) => text.trim()),
7391
9583
  markSpeech: dictateTranscript || ""
7392
9584
  }
7393
- )
9585
+ ),
9586
+ (() => {
9587
+ const selected = selectedCanvasElements();
9588
+ const hostRect = unsysCanvasSelectionHostRect(
9589
+ selected,
9590
+ excalidrawAPIRef.current?.getAppState?.() ?? {}
9591
+ );
9592
+ const hostViewport = {
9593
+ width: canvasHostRef.current?.clientWidth ?? 320,
9594
+ height: canvasHostRef.current?.clientHeight ?? 240
9595
+ };
9596
+ const affordancePos = hostRect ? placeUnsysCanvasCommandPickerAffordance({
9597
+ selection: hostRect,
9598
+ viewport: hostViewport
9599
+ }) : null;
9600
+ const pickerOpen = unsysCanvasSlashBarOpen({
9601
+ selectionActive: canvasSelectionActive,
9602
+ slashIntent: slashBarOpen
9603
+ });
9604
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
9605
+ /* @__PURE__ */ jsx(
9606
+ UnsysCanvasCommandPickerAffordance,
9607
+ {
9608
+ visible: canvasSelectionActive && !pickerOpen && Boolean(affordancePos),
9609
+ left: affordancePos?.left ?? 0,
9610
+ top: affordancePos?.top ?? 0,
9611
+ onOpen: () => openCommandPickerAt()
9612
+ }
9613
+ ),
9614
+ /* @__PURE__ */ jsx(
9615
+ UnsysCanvasCommandPicker,
9616
+ {
9617
+ open: pickerOpen,
9618
+ left: pickerPos.left,
9619
+ top: pickerPos.top,
9620
+ query: commandText,
9621
+ extras: extraCommands,
9622
+ onQueryChange: setCommandText,
9623
+ onClose: () => {
9624
+ setSlashBarOpen(false);
9625
+ setCommandText("");
9626
+ },
9627
+ onRun: (id) => {
9628
+ const selectedForRun = pickerSelectedRef.current;
9629
+ setSlashBarOpen(false);
9630
+ setCommandText("");
9631
+ handleQuickActionRef.current(
9632
+ id,
9633
+ selectedForRun.length ? selectedForRun : void 0
9634
+ );
9635
+ }
9636
+ }
9637
+ )
9638
+ ] });
9639
+ })()
7394
9640
  ]
7395
9641
  }
7396
9642
  )
@@ -7411,51 +9657,6 @@ function ExtraCommandsProvider({
7411
9657
  function useExtraCommands() {
7412
9658
  return useContext(ExtraCommandsContext);
7413
9659
  }
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
9660
  function dictateButtonClass(kind, square, wide, plate, iconOnly) {
7460
9661
  const pressed = kind === "idle" ? " aria-pressed:bg-white aria-pressed:text-neutral-950" : "";
7461
9662
  if (iconOnly) return `${UNSYS_CANVAS_COMMAND_STRIPE_CLASS}${pressed}`;
@@ -7701,12 +9902,30 @@ function CanvasCommandCheatsheet({
7701
9902
  /* @__PURE__ */ jsx("kbd", { "data-shortcut-alt": command.shortcut, className: "text-white/40", children: unsysCanvasCommandShortcutAltLabel(command.shortcut) })
7702
9903
  ] })
7703
9904
  ] }),
7704
- /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: command.tooltip })
9905
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: command.tooltip }),
9906
+ command.gestureHint ? /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[10px] leading-snug text-white/50", children: command.gestureHint }) : null
7705
9907
  ] })
7706
9908
  ]
7707
9909
  },
7708
9910
  command.id
7709
9911
  )),
9912
+ /* @__PURE__ */ jsxs(
9913
+ "li",
9914
+ {
9915
+ "data-unsys-canvas-command-cheatsheet-row": "picker",
9916
+ className: "flex items-start gap-2 border border-white/20 px-2 py-2",
9917
+ children: [
9918
+ /* @__PURE__ */ jsx(CommandMark, { id: "picker", label: UNSYS_CANVAS_COMMAND_PICKER_LABEL, className: "mt-0.5 h-4 w-4 shrink-0" }),
9919
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
9920
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
9921
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-[12px] font-semibold", children: UNSYS_CANVAS_COMMAND_PICKER_LABEL }),
9922
+ /* @__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 }) })
9923
+ ] }),
9924
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: UNSYS_CANVAS_COMMAND_PICKER_TOOLTIP })
9925
+ ] })
9926
+ ]
9927
+ }
9928
+ ),
7710
9929
  /* @__PURE__ */ jsxs(
7711
9930
  "li",
7712
9931
  {
@@ -7727,7 +9946,33 @@ function CanvasCommandCheatsheet({
7727
9946
  ]
7728
9947
  }
7729
9948
  )
7730
- ] })
9949
+ ] }),
9950
+ /* @__PURE__ */ jsx("h3", { className: "mb-2 mt-4 font-mono text-[11px] font-semibold uppercase tracking-[0.16em] text-white/80", children: "Pointer gestures" }),
9951
+ /* @__PURE__ */ jsx("ul", { className: "flex flex-col gap-2", children: UNSYS_CANVAS_LASER_GESTURES.map((row) => /* @__PURE__ */ jsxs(
9952
+ "li",
9953
+ {
9954
+ "data-unsys-canvas-command-cheatsheet-gesture": row.command,
9955
+ className: "flex items-start gap-2 border border-white/20 px-2 py-2",
9956
+ children: [
9957
+ /* @__PURE__ */ jsx(
9958
+ CommandMark,
9959
+ {
9960
+ id: row.command,
9961
+ label: row.label,
9962
+ className: "mt-0.5 h-4 w-4 shrink-0"
9963
+ }
9964
+ ),
9965
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
9966
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
9967
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-[12px] font-semibold", children: row.label }),
9968
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 font-mono text-[10px] text-white/55", children: row.gesture })
9969
+ ] }),
9970
+ /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[11px] leading-snug text-white/70", children: row.hint })
9971
+ ] })
9972
+ ]
9973
+ },
9974
+ row.command
9975
+ )) })
7731
9976
  ]
7732
9977
  }
7733
9978
  )
@@ -7736,7 +9981,7 @@ function CanvasCommandCheatsheet({
7736
9981
  }
7737
9982
 
7738
9983
  // 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.";
9984
+ 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
9985
  var SESSION_INSTRUCTIONS = {
7741
9986
  board: CANVAS_HELP
7742
9987
  };
@@ -7901,6 +10146,7 @@ function UnsysCanvas({
7901
10146
  onEvent,
7902
10147
  onCanvasEvents,
7903
10148
  onAsk,
10149
+ runModel,
7904
10150
  style,
7905
10151
  slots,
7906
10152
  commands,
@@ -7910,9 +10156,7 @@ function UnsysCanvas({
7910
10156
  className,
7911
10157
  ...boardProps
7912
10158
  }) {
7913
- if (typeof onAsk !== "function") {
7914
- throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
7915
- }
10159
+ assertCanvasModel({ onAsk, runModel });
7916
10160
  const resolvedStyle = parseUnsysCanvasStyle(style);
7917
10161
  const cssVars = unsysCanvasSidebarStyleCssVars(resolvedStyle);
7918
10162
  const hideRail = slots && "rail" in slots && slots.rail === null;
@@ -7977,6 +10221,7 @@ function UnsysCanvas({
7977
10221
  onSceneChange,
7978
10222
  onEvent: onEvent ?? onCanvasEvents,
7979
10223
  onAsk,
10224
+ runModel,
7980
10225
  style: resolvedStyle,
7981
10226
  extraCommands: commands,
7982
10227
  liveCanvasChrome: true
@@ -8033,142 +10278,95 @@ function CanvasTopicCard({
8033
10278
  );
8034
10279
  }
8035
10280
 
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
10281
+ // src/lib/collaboration/memory-transport.ts
10282
+ function createUnsysCanvasMemoryTransportHub() {
10283
+ const peers = /* @__PURE__ */ new Map();
10284
+ let nextId = 1;
10285
+ const createTransport = () => ({
10286
+ open(roomId, handlers) {
10287
+ const id = nextId;
10288
+ nextId += 1;
10289
+ const peer = { id, roomId, handlers };
10290
+ peers.set(id, peer);
10291
+ queueMicrotask(() => {
10292
+ if (peers.get(id) === peer) handlers.onOpen?.();
10293
+ });
10294
+ return {
10295
+ send(bytes) {
10296
+ const copy = new Uint8Array(bytes);
10297
+ for (const other of peers.values()) {
10298
+ if (other.id === id || other.roomId !== roomId) continue;
10299
+ other.handlers.onMessage(copy);
10300
+ }
10301
+ },
10302
+ close() {
10303
+ peers.delete(id);
10304
+ handlers.onClose?.();
10305
+ }
10306
+ };
10307
+ }
8131
10308
  });
10309
+ return { createTransport };
8132
10310
  }
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, "");
10311
+
10312
+ // src/lib/collaboration/websocket-transport.ts
10313
+ function asBytes(data) {
10314
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
10315
+ if (data instanceof Uint8Array) return data;
10316
+ if (typeof Blob !== "undefined" && data instanceof Blob) return null;
10317
+ return null;
8155
10318
  }
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;
10319
+ function createUnsysCanvasWebsocketTransport(options) {
10320
+ const url = String(options.url || "").trim();
10321
+ return {
10322
+ open(roomId, handlers) {
10323
+ if (!url || typeof WebSocket === "undefined") {
10324
+ queueMicrotask(() => handlers.onError?.(new Error("Collaboration relay URL is missing.")));
10325
+ return { send() {
10326
+ }, close() {
10327
+ } };
10328
+ }
10329
+ const ws = new WebSocket(url);
10330
+ ws.binaryType = "arraybuffer";
10331
+ let opened = false;
10332
+ ws.onopen = () => {
10333
+ opened = true;
10334
+ ws.send(JSON.stringify({ type: "join", roomId }));
10335
+ handlers.onOpen?.();
10336
+ };
10337
+ ws.onmessage = (event) => {
10338
+ if (typeof event.data === "string") return;
10339
+ const bytes = asBytes(event.data);
10340
+ if (bytes) handlers.onMessage(bytes);
10341
+ };
10342
+ ws.onerror = () => {
10343
+ handlers.onError?.(new Error("Collaboration relay error."));
10344
+ };
10345
+ ws.onclose = () => {
10346
+ if (opened) handlers.onClose?.();
10347
+ };
10348
+ return {
10349
+ send(bytes) {
10350
+ if (ws.readyState !== WebSocket.OPEN) return;
10351
+ const copy = new Uint8Array(bytes.byteLength);
10352
+ copy.set(bytes);
10353
+ ws.send(copy);
10354
+ },
10355
+ close() {
10356
+ try {
10357
+ ws.close();
10358
+ } catch {
10359
+ }
10360
+ }
10361
+ };
10362
+ }
10363
+ };
8163
10364
  }
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
- }
10365
+ function isUnsysCanvasRelayUrl(value) {
10366
+ const url = String(value || "").trim();
10367
+ return url.startsWith("ws://") || url.startsWith("wss://");
8170
10368
  }
8171
10369
 
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 };
10370
+ 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
10371
  //# sourceMappingURL=index.js.map
8174
10372
  //# sourceMappingURL=index.js.map