unsys-canvas 0.2.0 → 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
@@ -2007,6 +2007,11 @@ function unsysCanvasZoomAtPoint(input) {
2007
2007
  scrollY: baseScrollY - (appLayerY - appLayerY / nextZoom)
2008
2008
  };
2009
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
+ }
2010
2015
  function unsysCanvasSceneToViewport(scene, appState) {
2011
2016
  const zoom = unsysCanvasZoomValue(appState);
2012
2017
  const scrollX = Number(appState?.scrollX) || 0;
@@ -2105,6 +2110,44 @@ function unsysCanvasSelectionHostRect(elements, appState, host) {
2105
2110
  bottom: rect.bottom - originTop
2106
2111
  };
2107
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
+ }
2108
2151
  function ileLearnMoreSelectionKey(selectedElementIds) {
2109
2152
  return Object.keys(selectedElementIds ?? {}).filter((id) => Boolean(selectedElementIds?.[id])).sort().join(",");
2110
2153
  }
@@ -4403,6 +4446,99 @@ function unsysCanvasWithLiveTransparentFill(scene) {
4403
4446
  };
4404
4447
  }
4405
4448
 
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}`;
4540
+ }
4541
+
4406
4542
  // src/lib/work-canvas/work-canvas-xai.ts
4407
4543
  var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
4408
4544
  var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
@@ -4412,7 +4548,7 @@ function unsysCanvasXaiNeedsBoardContext(kind) {
4412
4548
  function unsysCanvasXaiMaxTokens(kind) {
4413
4549
  if (kind === "concepts") return 220;
4414
4550
  if (kind === "simplify") return 280;
4415
- if (kind === "pretty") return 520;
4551
+ if (kind === "pretty") return 1600;
4416
4552
  if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
4417
4553
  if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
4418
4554
  return 800;
@@ -4600,9 +4736,16 @@ function unsysCanvasSceneVisiblyChanged(before, after) {
4600
4736
  }
4601
4737
  return false;
4602
4738
  }
4603
- function unsysCanvasAskFallback(kind) {
4604
- if (!kind || kind === "ask") return "Learn more failed. Try again.";
4605
- return `${kind} failed. Try again.`;
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
+ );
4606
4749
  }
4607
4750
  function applyUnsysCanvasAskReply(input) {
4608
4751
  const live = serializeUnsysCanvasScene(input.live);
@@ -4647,6 +4790,9 @@ function applyUnsysCanvasAskReply(input) {
4647
4790
  elements: input.payload.elements
4648
4791
  });
4649
4792
  if (placed.placed) next = placed.scene;
4793
+ else if (text || normalizeExtraSkeletons(input.payload.elements).length) {
4794
+ next = merge(text);
4795
+ }
4650
4796
  } else if (kind === "concepts") {
4651
4797
  const labels = unsysCanvasConceptLabels(source, {
4652
4798
  text: input.payload.text,
@@ -4661,8 +4807,17 @@ function applyUnsysCanvasAskReply(input) {
4661
4807
  next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
4662
4808
  }
4663
4809
  if (unsysCanvasSceneVisiblyChanged(live, next)) return withUnsysCanvasAutoLayout(next);
4664
- const fallback = stripLearnerFacingWrappers(String(input.payload.text || "").trim()) || unsysCanvasAskFallback(kind);
4665
- return withUnsysCanvasAutoLayout(merge(fallback));
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
+ });
4666
4821
  }
4667
4822
  function applyUnsysCanvasPositionEdits(scene, selectedElements, reply) {
4668
4823
  const current = serializeUnsysCanvasScene(scene);
@@ -4842,7 +4997,7 @@ function defaultBuildPrompt(commandId, context) {
4842
4997
  timeoutMs: unsysCanvasXaiFetchTimeout(kind)
4843
4998
  };
4844
4999
  }
4845
- var MODEL_KIND_LABEL = {
5000
+ var MODEL_KIND_LABEL2 = {
4846
5001
  ask: "Ask",
4847
5002
  check: "Check",
4848
5003
  "selective-compress": "Compress",
@@ -4853,8 +5008,8 @@ var MODEL_KIND_LABEL = {
4853
5008
  function hiddenModelDef(id) {
4854
5009
  return {
4855
5010
  id,
4856
- label: MODEL_KIND_LABEL[id] ?? id,
4857
- tooltip: MODEL_KIND_LABEL[id] ?? id,
5011
+ label: MODEL_KIND_LABEL2[id] ?? id,
5012
+ tooltip: MODEL_KIND_LABEL2[id] ?? id,
4858
5013
  shortcut: "",
4859
5014
  needsSelection: id !== "ask",
4860
5015
  boardOnly: false,
@@ -5131,7 +5286,7 @@ function createUnsysCanvasXaiBrowserRunner(options) {
5131
5286
  return async (request) => {
5132
5287
  const apiKey = String(await options.getApiKey() || "").trim();
5133
5288
  if (!apiKey) {
5134
- throw new Error("No API key.");
5289
+ throw new Error("No xAI API key.");
5135
5290
  }
5136
5291
  const baseURL = String(await options.getBaseUrl?.() || "").replace(/\/+$/, "") || "https://api.x.ai/v1";
5137
5292
  const model = typeof options.model === "function" ? options.model(request.commandId) : options.model || "grok-4.7";
@@ -5164,7 +5319,15 @@ function createUnsysCanvasXaiBrowserRunner(options) {
5164
5319
  if (!response.ok) {
5165
5320
  const err = data.error;
5166
5321
  const message = typeof err === "string" ? err : err && typeof err === "object" && "message" in err ? String(err.message || "") : "";
5167
- throw new Error(message.trim() || `Canvas model failed (${response.status})`);
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
+ );
5168
5331
  }
5169
5332
  const text = choiceContent(data).trim();
5170
5333
  if (!text) throw new Error("Canvas chat returned an empty reply.");
@@ -5190,7 +5353,7 @@ function createUnsysCanvasModelProxyRunner(options) {
5190
5353
  const data = await response.json().catch(() => ({}));
5191
5354
  if (!response.ok) {
5192
5355
  const err = asRecord2(data.error);
5193
- const message = err && typeof err.message === "string" && err.message || (typeof data.error === "string" ? data.error : "") || `Canvas model failed (${response.status})`;
5356
+ const message = err && typeof err.message === "string" && err.message || (typeof data.error === "string" ? data.error : "") || `the model API returned ${response.status}`;
5194
5357
  throw new Error(message);
5195
5358
  }
5196
5359
  const raw = typeof data.raw === "string" && data.raw.trim() ? data.raw : typeof data.message === "string" ? data.message : "";
@@ -6876,9 +7039,51 @@ function useWorkCanvasCommands(input) {
6876
7039
  "[ExcalidrawCanvas] Ask XAI failed:",
6877
7040
  err instanceof Error ? err.message : String(err)
6878
7041
  );
6879
- const fallback = unsysCanvasAskFallback(askInput.kind);
7042
+ const message = formatUnsysCanvasCommandError(err, { commandId: askInput.kind });
6880
7043
  await enqueueCanvasAskApply(() => {
6881
- 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
+ );
6882
7087
  });
6883
7088
  return false;
6884
7089
  } finally {
@@ -8882,15 +9087,25 @@ function ExcalidrawCanvas({
8882
9087
  }
8883
9088
  });
8884
9089
  const openCommandPickerAt = useCallback(
8885
- (x, y) => {
9090
+ (pointer) => {
8886
9091
  const host = canvasHostRef.current;
8887
- const width = host?.clientWidth ?? 320;
8888
- const height = host?.clientHeight ?? 240;
8889
- setPickerPos({
8890
- left: Math.max(8, Math.min(Math.round(x), width - 272)),
8891
- top: Math.max(8, Math.min(Math.round(y), height - 220))
8892
- });
8893
- pickerSelectedRef.current = selectedCanvasElements();
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;
8894
9109
  setCommandText("");
8895
9110
  setSlashBarOpen(true);
8896
9111
  },
@@ -8929,7 +9144,7 @@ function ExcalidrawCanvas({
8929
9144
  return;
8930
9145
  }
8931
9146
  event.preventDefault();
8932
- openCommandPickerAt(lastPointerHostRef.current.x, lastPointerHostRef.current.y);
9147
+ openCommandPickerAt(lastPointerHostRef.current);
8933
9148
  };
8934
9149
  window.addEventListener("keydown", onKey);
8935
9150
  return () => window.removeEventListener("keydown", onKey);
@@ -9277,7 +9492,10 @@ function ExcalidrawCanvas({
9277
9492
  if (!canvasSelectionActive) return;
9278
9493
  event.preventDefault();
9279
9494
  const rect = event.currentTarget.getBoundingClientRect();
9280
- openCommandPickerAt(event.clientX - rect.left, event.clientY - rect.top);
9495
+ openCommandPickerAt({
9496
+ x: event.clientX - rect.left,
9497
+ y: event.clientY - rect.top
9498
+ });
9281
9499
  },
9282
9500
  children: [
9283
9501
  isLoaded && /* @__PURE__ */ jsx(UnsysExcalidrawErrorBoundary, { children: /* @__PURE__ */ jsx(
@@ -9371,6 +9589,14 @@ function ExcalidrawCanvas({
9371
9589
  selected,
9372
9590
  excalidrawAPIRef.current?.getAppState?.() ?? {}
9373
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;
9374
9600
  const pickerOpen = unsysCanvasSlashBarOpen({
9375
9601
  selectionActive: canvasSelectionActive,
9376
9602
  slashIntent: slashBarOpen
@@ -9379,13 +9605,10 @@ function ExcalidrawCanvas({
9379
9605
  /* @__PURE__ */ jsx(
9380
9606
  UnsysCanvasCommandPickerAffordance,
9381
9607
  {
9382
- visible: canvasSelectionActive && !pickerOpen && Boolean(hostRect),
9383
- left: Math.round((hostRect?.right ?? 0) + 6),
9384
- top: Math.round(hostRect?.top ?? 0),
9385
- onOpen: () => openCommandPickerAt(
9386
- (hostRect?.right ?? lastPointerHostRef.current.x) + 8,
9387
- hostRect?.top ?? lastPointerHostRef.current.y
9388
- )
9608
+ visible: canvasSelectionActive && !pickerOpen && Boolean(affordancePos),
9609
+ left: affordancePos?.left ?? 0,
9610
+ top: affordancePos?.top ?? 0,
9611
+ onOpen: () => openCommandPickerAt()
9389
9612
  }
9390
9613
  ),
9391
9614
  /* @__PURE__ */ jsx(